title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Path toFile() method in Java with Examples | 18 Jul, 2019
The toFile() method of java.nio.file.Path interface used to return a java.io.File object representing this path object. if this Path is associated with the default provider, then this method returns a java.io.File object constructed with the String representation of this path. If this path was created by invoking the java.io.File toPath method then there is no guarantee that the File object returned by this method is equal to the original File. This method throws UnsupportedOperationException if this Path is not associated with the default provider.
Syntax:
default File toFile()
Parameters: This method accepts nothing.
Return value: This method returns a java.io.File object representing this path.
Exception: This method throws UnsupportedOperationException if this Path is not associated with the default provider.
Below programs illustrate toFile() method:Program 1:
// Java program to demonstrate// java.nio.file.Path.toFile() method import java.io.File;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("D:\\Apps\\" + "NewTextDocument.txt"); // call toFile() to get // File object from path File file = path.toFile(); // print file details System.out.println("File:" + file.toString() + " is readable " + file.canRead()); }}
Program 2:
// Java program to demonstrate// java.nio.file.Path.toFile() method import java.io.File;import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("D:\\temp\\" + "AmanSinghCV.docx"); // call toFile() to get // File object from path File file = path.toFile(); // print file details System.out.println("File Name:" + file.getName()); }}
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#toFile()
Java-Functions
Java-Path
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Functional Interfaces in Java
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2019"
},
{
"code": null,
"e": 584,
"s": 28,
"text": "The toFile() method of java.nio.file.Path interface used to return a java.io.File object representing this path object. if this Path is associated with the default provider, then this method returns a java.io.File object constructed with the String representation of this path. If this path was created by invoking the java.io.File toPath method then there is no guarantee that the File object returned by this method is equal to the original File. This method throws UnsupportedOperationException if this Path is not associated with the default provider."
},
{
"code": null,
"e": 592,
"s": 584,
"text": "Syntax:"
},
{
"code": null,
"e": 615,
"s": 592,
"text": "default File toFile()\n"
},
{
"code": null,
"e": 656,
"s": 615,
"text": "Parameters: This method accepts nothing."
},
{
"code": null,
"e": 736,
"s": 656,
"text": "Return value: This method returns a java.io.File object representing this path."
},
{
"code": null,
"e": 854,
"s": 736,
"text": "Exception: This method throws UnsupportedOperationException if this Path is not associated with the default provider."
},
{
"code": null,
"e": 907,
"s": 854,
"text": "Below programs illustrate toFile() method:Program 1:"
},
{
"code": "// Java program to demonstrate// java.nio.file.Path.toFile() method import java.io.File;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get(\"D:\\\\Apps\\\\\" + \"NewTextDocument.txt\"); // call toFile() to get // File object from path File file = path.toFile(); // print file details System.out.println(\"File:\" + file.toString() + \" is readable \" + file.canRead()); }}",
"e": 1525,
"s": 907,
"text": null
},
{
"code": null,
"e": 1536,
"s": 1525,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// java.nio.file.Path.toFile() method import java.io.File;import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get(\"D:\\\\temp\\\\\" + \"AmanSinghCV.docx\"); // call toFile() to get // File object from path File file = path.toFile(); // print file details System.out.println(\"File Name:\" + file.getName()); }}",
"e": 2092,
"s": 1536,
"text": null
},
{
"code": null,
"e": 2180,
"s": 2092,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#toFile()"
},
{
"code": null,
"e": 2195,
"s": 2180,
"text": "Java-Functions"
},
{
"code": null,
"e": 2205,
"s": 2195,
"text": "Java-Path"
},
{
"code": null,
"e": 2227,
"s": 2205,
"text": "java.nio.file package"
},
{
"code": null,
"e": 2232,
"s": 2227,
"text": "Java"
},
{
"code": null,
"e": 2237,
"s": 2232,
"text": "Java"
},
{
"code": null,
"e": 2335,
"s": 2237,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2350,
"s": 2335,
"text": "Stream In Java"
},
{
"code": null,
"e": 2371,
"s": 2350,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2392,
"s": 2371,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2411,
"s": 2392,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2428,
"s": 2411,
"text": "Generics in Java"
},
{
"code": null,
"e": 2454,
"s": 2428,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2484,
"s": 2454,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2500,
"s": 2484,
"text": "Strings in Java"
},
{
"code": null,
"e": 2537,
"s": 2500,
"text": "Differences between JDK, JRE and JVM"
}
] |
Python – Length Conditional Concatenation | 17 Jun, 2022
Given a list of strings, perform concatenation of Strings whose length is greater than K.
Input : test_list = [“Gfg”, ‘is’, “Best”, ‘for’, ‘CS’, ‘Everything’], K = 3Output : BestEverything Explanation : All elements with Length > 3 are concatenated.
Input : test_list = [“Gfg”, ‘is’, “Best”, ‘for’, ‘CS’, ‘Everything’], K = 1 Output : GfgisBestforCSEverything Explanation : All elements with Length > 1 are concatenated.
Method #1: Using loop + len():This offers a brute way to solve this problem. In this, we iterate for each string and perform concatenation if the string length is greater than K using len().
Python3
# Python3 code to demonstrate working of# Length Conditional Concatenation# Using loop + len() # initializing liststest_list = ["Gfg", 'is', "Best", 'for', 'CS', 'Everything'] # printing original listprint("The original list : " + str(test_list)) # initializing KK = 2 # loop to run through all the elementsres = ''for ele in test_list: # using len() to check for length if len(ele) > 2: res += ele # printing resultprint("String after Concatenation : " + str(res))
The original list : ['Gfg', 'is', 'Best', 'for', 'CS', 'Everything']
String after Concatenation : GfgBestforEverything
Method #2 : Using join() + filter() + lambda + len():The combination of above functions can be used to solve this problem. In this, we perform concatenation using join(), filter and lambda are used for conditional check using len().
Python3
# Python3 code to demonstrate working of# Length Conditional Concatenation# Using join() + filter() + lambda + len() # initializing liststest_list = ["Gfg", 'is', "Best", 'for', 'CS', 'Everything'] # printing original listprint("The original list : " + str(test_list)) # initializing KK = 2 # join() performing Concatenation of required stringsres = ''.join(filter(lambda ele: len(ele) > K, test_list)) # printing resultprint("String after Concatenation : " + str(res))
The original list : ['Gfg', 'is', 'Best', 'for', 'CS', 'Everything']
String after Concatenation : GfgBestforEverything
Method#3: Using list comprehension + join():This method lists strings whose length is greater than the defined number. With the help of join method, we can join the list in string.
Python3
# Python3 code to demonstrate working of# Length Conditional Concatenation# Using list comprehension + join # Initializing liststest_list = ["Gfg", 'is', "Best", 'for', 'CS', 'Everything'] # Printing original listprint("The original list : " + str(test_list)) # Initializing KK = 3 # list comprehension make list of string with greater length# join() performing Concatenation of required stringstemp = [x for x in test_list if len(x) > K]res = "".join(temp) # Printing resultprint("String after Concatenation : " + str(res))
The original list : ['Gfg', 'is', 'Best', 'for', 'CS', 'Everything']
String after Concatenation : BestEverything
satyam00so
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
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": "\n17 Jun, 2022"
},
{
"code": null,
"e": 118,
"s": 28,
"text": "Given a list of strings, perform concatenation of Strings whose length is greater than K."
},
{
"code": null,
"e": 279,
"s": 118,
"text": "Input : test_list = [“Gfg”, ‘is’, “Best”, ‘for’, ‘CS’, ‘Everything’], K = 3Output : BestEverything Explanation : All elements with Length > 3 are concatenated. "
},
{
"code": null,
"e": 450,
"s": 279,
"text": "Input : test_list = [“Gfg”, ‘is’, “Best”, ‘for’, ‘CS’, ‘Everything’], K = 1 Output : GfgisBestforCSEverything Explanation : All elements with Length > 1 are concatenated."
},
{
"code": null,
"e": 641,
"s": 450,
"text": "Method #1: Using loop + len():This offers a brute way to solve this problem. In this, we iterate for each string and perform concatenation if the string length is greater than K using len()."
},
{
"code": null,
"e": 649,
"s": 641,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Length Conditional Concatenation# Using loop + len() # initializing liststest_list = [\"Gfg\", 'is', \"Best\", 'for', 'CS', 'Everything'] # printing original listprint(\"The original list : \" + str(test_list)) # initializing KK = 2 # loop to run through all the elementsres = ''for ele in test_list: # using len() to check for length if len(ele) > 2: res += ele # printing resultprint(\"String after Concatenation : \" + str(res))",
"e": 1133,
"s": 649,
"text": null
},
{
"code": null,
"e": 1253,
"s": 1133,
"text": "The original list : ['Gfg', 'is', 'Best', 'for', 'CS', 'Everything']\nString after Concatenation : GfgBestforEverything\n"
},
{
"code": null,
"e": 1486,
"s": 1253,
"text": "Method #2 : Using join() + filter() + lambda + len():The combination of above functions can be used to solve this problem. In this, we perform concatenation using join(), filter and lambda are used for conditional check using len()."
},
{
"code": null,
"e": 1494,
"s": 1486,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Length Conditional Concatenation# Using join() + filter() + lambda + len() # initializing liststest_list = [\"Gfg\", 'is', \"Best\", 'for', 'CS', 'Everything'] # printing original listprint(\"The original list : \" + str(test_list)) # initializing KK = 2 # join() performing Concatenation of required stringsres = ''.join(filter(lambda ele: len(ele) > K, test_list)) # printing resultprint(\"String after Concatenation : \" + str(res))",
"e": 1964,
"s": 1494,
"text": null
},
{
"code": null,
"e": 2084,
"s": 1964,
"text": "The original list : ['Gfg', 'is', 'Best', 'for', 'CS', 'Everything']\nString after Concatenation : GfgBestforEverything\n"
},
{
"code": null,
"e": 2266,
"s": 2084,
"text": "Method#3: Using list comprehension + join():This method lists strings whose length is greater than the defined number. With the help of join method, we can join the list in string. "
},
{
"code": null,
"e": 2274,
"s": 2266,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Length Conditional Concatenation# Using list comprehension + join # Initializing liststest_list = [\"Gfg\", 'is', \"Best\", 'for', 'CS', 'Everything'] # Printing original listprint(\"The original list : \" + str(test_list)) # Initializing KK = 3 # list comprehension make list of string with greater length# join() performing Concatenation of required stringstemp = [x for x in test_list if len(x) > K]res = \"\".join(temp) # Printing resultprint(\"String after Concatenation : \" + str(res))",
"e": 2799,
"s": 2274,
"text": null
},
{
"code": null,
"e": 2913,
"s": 2799,
"text": "The original list : ['Gfg', 'is', 'Best', 'for', 'CS', 'Everything']\nString after Concatenation : BestEverything\n"
},
{
"code": null,
"e": 2924,
"s": 2913,
"text": "satyam00so"
},
{
"code": null,
"e": 2945,
"s": 2924,
"text": "Python list-programs"
},
{
"code": null,
"e": 2968,
"s": 2945,
"text": "Python string-programs"
},
{
"code": null,
"e": 2975,
"s": 2968,
"text": "Python"
},
{
"code": null,
"e": 2991,
"s": 2975,
"text": "Python Programs"
},
{
"code": null,
"e": 3089,
"s": 2991,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3121,
"s": 3089,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3148,
"s": 3121,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3169,
"s": 3148,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3200,
"s": 3169,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3256,
"s": 3200,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3278,
"s": 3256,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3317,
"s": 3278,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3355,
"s": 3317,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3404,
"s": 3355,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Python | Extractive Text Summarization using Gensim | 26 Feb, 2021
Summarization is a useful tool for varied textual applications that aims to highlight important information within a large corpus. With the outburst of information on the web, Python provides some handy tools to help summarize a text. This article provides an overview of the two major categories of approaches followed – extractive and abstractive. In this article, we shall look at a working example of extractive summarization.
Algorithm : Below is the algorithm implemented in the gensim library, called “TextRank”, which is based on PageRank algorithm for ranking search results.
Pre-process the given text. This includes stop words removal, punctuation removal, and stemming.Make a graph with sentences that are the vertices.The graph has edges denoting the similarity between the two sentences at the vertices.Run PageRank algorithm on this weighted graph.Pick the highest-scoring vertices and append them to the summary.Based on the ratio or the word count, the number of vertices to be picked is decided.
Pre-process the given text. This includes stop words removal, punctuation removal, and stemming.
Make a graph with sentences that are the vertices.
The graph has edges denoting the similarity between the two sentences at the vertices.
Run PageRank algorithm on this weighted graph.
Pick the highest-scoring vertices and append them to the summary.
Based on the ratio or the word count, the number of vertices to be picked is decided.
Code : Summarizes a Wikipedia article based on (a) ratio and (b) word count.
Python
from gensim.summarization.summarizer import summarizefrom gensim.summarization import keywordsimport wikipediaimport en_core_web_sm # Get wiki content.wikisearch = wikipedia.page("Amitabh Bachchan")wikicontent = wikisearch.contentnlp = en_core_web_sm.load()doc = nlp(wikicontent) # Save the wiki content to a file# (for reference).f = open("wikicontent.txt", "w")f.write(wikicontent)f.close() # Summary (0.5% of the original content).summ_per = summarize(wikicontent, ratio = 0.05)print("Percent summary")print(summ_per) # Summary (200 words)summ_words = summarize(wikicontent, word_count = 200)print("Word count summary")print(summ_words)
Output
Percent summary
Amitabh Bachchan (pronounced [?m??ta?b? ?b?t???n]; born Inquilaab Srivastava;
11 October 1942) is an Indian film actor, film producer, television host,
occasional playback singer and former politician. He first gained popularity
in the early 1970s for films such as Zanjeer, Deewaar and Sholay, and was
dubbed India's "angry young man" for his on-screen roles in Bollywood.
.
.
.
Apart from National Film Awards, Filmfare Awards and other competitive awards
which Bachchan won for his performances throughout the years, he has been
awarded several honours for his achievements in the Indian film industry.
Word count summary
Beyond the Indian subcontinent, he also has a large overseas following
in markets including Africa (such as South Africa), the Middle East
(especially Egypt), United Kingdom, Russia and parts of the United
States. Bachchan has won numerous accolades in his career, including
four National Film Awards as Best Actor and many awards at
international film festivals and award ceremonies.
.
.
.
After a three year stint in politics from 1984 to 1987, Bachchan
returned to films in 1988, playing the title role in Shahenshah,
which was a box office success.
BharatSharma7
Advanced Computer Subject
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Docker - COPY Instruction
Getting started with Machine Learning
How to Run a Python Script using Docker?
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Feb, 2021"
},
{
"code": null,
"e": 460,
"s": 28,
"text": "Summarization is a useful tool for varied textual applications that aims to highlight important information within a large corpus. With the outburst of information on the web, Python provides some handy tools to help summarize a text. This article provides an overview of the two major categories of approaches followed – extractive and abstractive. In this article, we shall look at a working example of extractive summarization. "
},
{
"code": null,
"e": 614,
"s": 460,
"text": "Algorithm : Below is the algorithm implemented in the gensim library, called “TextRank”, which is based on PageRank algorithm for ranking search results."
},
{
"code": null,
"e": 1043,
"s": 614,
"text": "Pre-process the given text. This includes stop words removal, punctuation removal, and stemming.Make a graph with sentences that are the vertices.The graph has edges denoting the similarity between the two sentences at the vertices.Run PageRank algorithm on this weighted graph.Pick the highest-scoring vertices and append them to the summary.Based on the ratio or the word count, the number of vertices to be picked is decided."
},
{
"code": null,
"e": 1140,
"s": 1043,
"text": "Pre-process the given text. This includes stop words removal, punctuation removal, and stemming."
},
{
"code": null,
"e": 1191,
"s": 1140,
"text": "Make a graph with sentences that are the vertices."
},
{
"code": null,
"e": 1278,
"s": 1191,
"text": "The graph has edges denoting the similarity between the two sentences at the vertices."
},
{
"code": null,
"e": 1325,
"s": 1278,
"text": "Run PageRank algorithm on this weighted graph."
},
{
"code": null,
"e": 1391,
"s": 1325,
"text": "Pick the highest-scoring vertices and append them to the summary."
},
{
"code": null,
"e": 1477,
"s": 1391,
"text": "Based on the ratio or the word count, the number of vertices to be picked is decided."
},
{
"code": null,
"e": 1555,
"s": 1477,
"text": "Code : Summarizes a Wikipedia article based on (a) ratio and (b) word count. "
},
{
"code": null,
"e": 1562,
"s": 1555,
"text": "Python"
},
{
"code": "from gensim.summarization.summarizer import summarizefrom gensim.summarization import keywordsimport wikipediaimport en_core_web_sm # Get wiki content.wikisearch = wikipedia.page(\"Amitabh Bachchan\")wikicontent = wikisearch.contentnlp = en_core_web_sm.load()doc = nlp(wikicontent) # Save the wiki content to a file# (for reference).f = open(\"wikicontent.txt\", \"w\")f.write(wikicontent)f.close() # Summary (0.5% of the original content).summ_per = summarize(wikicontent, ratio = 0.05)print(\"Percent summary\")print(summ_per) # Summary (200 words)summ_words = summarize(wikicontent, word_count = 200)print(\"Word count summary\")print(summ_words)",
"e": 2202,
"s": 1562,
"text": null
},
{
"code": null,
"e": 2211,
"s": 2202,
"text": "Output "
},
{
"code": null,
"e": 2835,
"s": 2211,
"text": "Percent summary\nAmitabh Bachchan (pronounced [?m??ta?b? ?b?t???n]; born Inquilaab Srivastava;\n11 October 1942) is an Indian film actor, film producer, television host, \noccasional playback singer and former politician. He first gained popularity\nin the early 1970s for films such as Zanjeer, Deewaar and Sholay, and was\ndubbed India's \"angry young man\" for his on-screen roles in Bollywood.\n.\n.\n.\nApart from National Film Awards, Filmfare Awards and other competitive awards\nwhich Bachchan won for his performances throughout the years, he has been \nawarded several honours for his achievements in the Indian film industry."
},
{
"code": null,
"e": 3416,
"s": 2837,
"text": "Word count summary\nBeyond the Indian subcontinent, he also has a large overseas following \nin markets including Africa (such as South Africa), the Middle East \n(especially Egypt), United Kingdom, Russia and parts of the United \nStates. Bachchan has won numerous accolades in his career, including \nfour National Film Awards as Best Actor and many awards at \ninternational film festivals and award ceremonies.\n.\n.\n.\nAfter a three year stint in politics from 1984 to 1987, Bachchan \nreturned to films in 1988, playing the title role in Shahenshah, \nwhich was a box office success."
},
{
"code": null,
"e": 3432,
"s": 3418,
"text": "BharatSharma7"
},
{
"code": null,
"e": 3458,
"s": 3432,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 3465,
"s": 3458,
"text": "Python"
},
{
"code": null,
"e": 3563,
"s": 3465,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3586,
"s": 3563,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 3609,
"s": 3586,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 3635,
"s": 3609,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3673,
"s": 3635,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 3714,
"s": 3673,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 3742,
"s": 3714,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3792,
"s": 3742,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3814,
"s": 3792,
"text": "Python map() function"
}
] |
SQL | Conditional Expressions | 29 Apr, 2022
Following are Conditional Expressions in SQL
The CASE Expression: Let you use IF-THEN-ELSE statements without having to invoke procedures.In a simple CASE expression, the SQL searches for the first WHEN......THEN pair for which expr is equal to comparison_expr and returns return_expr. If above condition is not satisfied, an ELSE clause exists, the SQL returns else_expr. Otherwise, returns NULL.We cannot specify literal null for the return_expr and the else_expr. All of the expressions(expr, comparison_expr, return_expr) must be of the same data type.Syntax:CASE expr WHEN comparison_expr1 THEN return_expr1
[WHEN comparison_expr2 THEN return_expr2
.
.
.
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END
Example:Input :
SELECT first_name, department_id, salary,
CASE department_id WHEN 50 THEN 1.5*salary
WHEN 12 THEN 2.0*salary
ELSE salary
END "REVISED SALARY"
FROM Employee;Output :Explanation: In above SQL statements, the value of department_id is decoded. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary.The DECODE Function : Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement.The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE logic used in various languages. The DECODE function decodes expression after comparing it to each search value. If the expression is the same as search, result is returned.If the default value is omitted, a null value is returned where a search value does not match any of the result values.Syntax:DECODE(col/expression, search1, result1
[, search2, result2,........,]
[, default])
Input :
SELECT first_name, department_id, salary,
DECODE(department_id, 50, 1.5*salary,
12, 2.0*salary,
salary)
"REVISED SALARY"
FROM Employee;
Output :Explanation: In above SQL statements, the value of department_id is tested. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary.COALESCE : Returns the first non-null argument. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display.NOTE: Same as CASE expressions, COALESCE also will not evaluate the arguments to the right of the first non-null argument found.Syntax:COALESCE(value [, ......] )
Input:
SELECT COALESCE(last_name, '- NA -')
from Employee;
Output:Explanation: “- NA -” will be displayed in place where last name is null else respective last names will be shown.GREATEST: Returns the largest value from a list of any number of expressions. Comparison is case sensitive. If datatypes of all the expressions in the list are not same, rest all expressions are converted to the datatype of the first expression for comparison and if this conversion is not possible, SQL will throw an error.NOTE: Returns null if any expression in the list is null.Syntax:GREATEST(expr1, expr2 [, .....] )
Input:
SELECT GREATEST('XYZ', 'xyz')
from dual;
Output:
GREATEST('XYZ', 'xyz')
xyz
Explanation: ASCII value of small alphabets is greater.Input:
SELECT GREATEST('XYZ', null, 'xyz')
from dual;
Output:
GREATEST('XYZ', null, 'xyz')
-Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above).IFNULL: If expr1 is not NULL, returns expr1; otherwise it returns expr2. Returns a numeric or string value, depending on the context in which it is used.Syntax:IFNULL(expr1, expr2)
Input:
SELECT IFNULL(1,0)
FROM dual;
Output:
-
1
Explanation : Since, no expression is null.Input:
SELECT IFNULL(NULL,10)
FROM dual;
Output:
--
10
Explanation:Since, expr1 is null hence, expr2 is shown.IN: Checks whether a value is present within a set of values and can be used with WHERE, CHECK and creation of views.NOTE: Same as CASE and COALESCE expressions, IN also will not evaluate the arguments to the right of the first non-null argument found.Syntax:WHERE column IN (x1, x2, x3 [,......] )
Input:
SELECT * from Employee
WHERE department_id IN(50, 12);
Output:Explanation:All data of Employees is shown with department ID 50 or 12.LEAST: Returns the smallest value from a list of any number of expressions. Comparison is case sensitive. If datatypes of all the expressions in the list are not same, rest all expressions are converted to the datatype of the first expression for comparison and if this conversion is not possible, SQL will throw an error.NOTE: Returns null if any expression in the list is null.Syntax:LEAST(expr1, expr2 [, ......])
strong>Input:
SELECT LEAST('XYZ', 'xyz')
from dual;
Output:
LEAST('XYZ', 'xyz')
XYZ
Explanation: ASCII value of capital alphabets is smaller.
Input:
SELECT LEAST('XYZ', null, 'xyz')
from dual;
Output:
LEAST('XYZ', null, 'xyz')
-
Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above).NULLIF: Returns a null value if value1=value2, otherwise it returns value1.Syntax:NULLIF(value1, value2)
Example:
Input:
SELECT NULLIF(9995463931, contact_num)
from Employee;
Output:
The CASE Expression: Let you use IF-THEN-ELSE statements without having to invoke procedures.In a simple CASE expression, the SQL searches for the first WHEN......THEN pair for which expr is equal to comparison_expr and returns return_expr. If above condition is not satisfied, an ELSE clause exists, the SQL returns else_expr. Otherwise, returns NULL.We cannot specify literal null for the return_expr and the else_expr. All of the expressions(expr, comparison_expr, return_expr) must be of the same data type.Syntax:CASE expr WHEN comparison_expr1 THEN return_expr1
[WHEN comparison_expr2 THEN return_expr2
.
.
.
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END
Example:Input :
SELECT first_name, department_id, salary,
CASE department_id WHEN 50 THEN 1.5*salary
WHEN 12 THEN 2.0*salary
ELSE salary
END "REVISED SALARY"
FROM Employee;Output :Explanation: In above SQL statements, the value of department_id is decoded. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary.
CASE expr WHEN comparison_expr1 THEN return_expr1
[WHEN comparison_expr2 THEN return_expr2
.
.
.
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END
Example:
Input :
SELECT first_name, department_id, salary,
CASE department_id WHEN 50 THEN 1.5*salary
WHEN 12 THEN 2.0*salary
ELSE salary
END "REVISED SALARY"
FROM Employee;Output :
Input :
SELECT first_name, department_id, salary,
CASE department_id WHEN 50 THEN 1.5*salary
WHEN 12 THEN 2.0*salary
ELSE salary
END "REVISED SALARY"
FROM Employee;
Output :
Explanation: In above SQL statements, the value of department_id is decoded. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary.
The DECODE Function : Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement.The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE logic used in various languages. The DECODE function decodes expression after comparing it to each search value. If the expression is the same as search, result is returned.If the default value is omitted, a null value is returned where a search value does not match any of the result values.Syntax:DECODE(col/expression, search1, result1
[, search2, result2,........,]
[, default])
Input :
SELECT first_name, department_id, salary,
DECODE(department_id, 50, 1.5*salary,
12, 2.0*salary,
salary)
"REVISED SALARY"
FROM Employee;
Output :Explanation: In above SQL statements, the value of department_id is tested. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary.
DECODE(col/expression, search1, result1
[, search2, result2,........,]
[, default])
Input :
SELECT first_name, department_id, salary,
DECODE(department_id, 50, 1.5*salary,
12, 2.0*salary,
salary)
"REVISED SALARY"
FROM Employee;
Output :Explanation: In above SQL statements, the value of department_id is tested. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary.
COALESCE : Returns the first non-null argument. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display.NOTE: Same as CASE expressions, COALESCE also will not evaluate the arguments to the right of the first non-null argument found.Syntax:COALESCE(value [, ......] )
Input:
SELECT COALESCE(last_name, '- NA -')
from Employee;
Output:Explanation: “- NA -” will be displayed in place where last name is null else respective last names will be shown.
COALESCE(value [, ......] )
Input:
SELECT COALESCE(last_name, '- NA -')
from Employee;
Output:Explanation: “- NA -” will be displayed in place where last name is null else respective last names will be shown.
GREATEST: Returns the largest value from a list of any number of expressions. Comparison is case sensitive. If datatypes of all the expressions in the list are not same, rest all expressions are converted to the datatype of the first expression for comparison and if this conversion is not possible, SQL will throw an error.NOTE: Returns null if any expression in the list is null.Syntax:GREATEST(expr1, expr2 [, .....] )
Input:
SELECT GREATEST('XYZ', 'xyz')
from dual;
Output:
GREATEST('XYZ', 'xyz')
xyz
Explanation: ASCII value of small alphabets is greater.Input:
SELECT GREATEST('XYZ', null, 'xyz')
from dual;
Output:
GREATEST('XYZ', null, 'xyz')
-Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above).
GREATEST(expr1, expr2 [, .....] )
Input:
SELECT GREATEST('XYZ', 'xyz')
from dual;
Output:
GREATEST('XYZ', 'xyz')
xyz
Explanation: ASCII value of small alphabets is greater.
Input:
SELECT GREATEST('XYZ', 'xyz')
from dual;
Output:
GREATEST('XYZ', 'xyz')
xyz
Explanation: ASCII value of small alphabets is greater.
Input:
SELECT GREATEST('XYZ', null, 'xyz')
from dual;
Output:
GREATEST('XYZ', null, 'xyz')
-Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above).
Input:
SELECT GREATEST('XYZ', null, 'xyz')
from dual;
Output:
GREATEST('XYZ', null, 'xyz')
-
Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above).
IFNULL: If expr1 is not NULL, returns expr1; otherwise it returns expr2. Returns a numeric or string value, depending on the context in which it is used.Syntax:IFNULL(expr1, expr2)
Input:
SELECT IFNULL(1,0)
FROM dual;
Output:
-
1
Explanation : Since, no expression is null.Input:
SELECT IFNULL(NULL,10)
FROM dual;
Output:
--
10
Explanation:Since, expr1 is null hence, expr2 is shown.
IFNULL(expr1, expr2)
Input:
SELECT IFNULL(1,0)
FROM dual;
Output:
-
1
Explanation : Since, no expression is null.
Input:
SELECT IFNULL(1,0)
FROM dual;
Output:
-
1
Explanation : Since, no expression is null.
Input:
SELECT IFNULL(NULL,10)
FROM dual;
Output:
--
10
Explanation:Since, expr1 is null hence, expr2 is shown.
Input:
SELECT IFNULL(NULL,10)
FROM dual;
Output:
--
10
Explanation:Since, expr1 is null hence, expr2 is shown.
IN: Checks whether a value is present within a set of values and can be used with WHERE, CHECK and creation of views.NOTE: Same as CASE and COALESCE expressions, IN also will not evaluate the arguments to the right of the first non-null argument found.Syntax:WHERE column IN (x1, x2, x3 [,......] )
Input:
SELECT * from Employee
WHERE department_id IN(50, 12);
Output:Explanation:All data of Employees is shown with department ID 50 or 12.
WHERE column IN (x1, x2, x3 [,......] )
Input:
SELECT * from Employee
WHERE department_id IN(50, 12);
Output:
Explanation:All data of Employees is shown with department ID 50 or 12.
LEAST: Returns the smallest value from a list of any number of expressions. Comparison is case sensitive. If datatypes of all the expressions in the list are not same, rest all expressions are converted to the datatype of the first expression for comparison and if this conversion is not possible, SQL will throw an error.NOTE: Returns null if any expression in the list is null.Syntax:LEAST(expr1, expr2 [, ......])
strong>Input:
SELECT LEAST('XYZ', 'xyz')
from dual;
Output:
LEAST('XYZ', 'xyz')
XYZ
Explanation: ASCII value of capital alphabets is smaller.
Input:
SELECT LEAST('XYZ', null, 'xyz')
from dual;
Output:
LEAST('XYZ', null, 'xyz')
-
Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above).
Syntax:
LEAST(expr1, expr2 [, ......])
strong>Input:
SELECT LEAST('XYZ', 'xyz')
from dual;
Output:
LEAST('XYZ', 'xyz')
XYZ
Explanation: ASCII value of capital alphabets is smaller.
strong>Input:
SELECT LEAST('XYZ', 'xyz')
from dual;
Output:
LEAST('XYZ', 'xyz')
XYZ
strong>Input:
SELECT LEAST('XYZ', 'xyz')
from dual;
Output:
LEAST('XYZ', 'xyz')
XYZ
Explanation: ASCII value of capital alphabets is smaller.
Input:
SELECT LEAST('XYZ', null, 'xyz')
from dual;
Output:
LEAST('XYZ', null, 'xyz')
-
Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above).
Input:
SELECT LEAST('XYZ', null, 'xyz')
from dual;
Output:
LEAST('XYZ', null, 'xyz')
-
Input:
SELECT LEAST('XYZ', null, 'xyz')
from dual;
Output:
LEAST('XYZ', null, 'xyz')
-
Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above).
NULLIF: Returns a null value if value1=value2, otherwise it returns value1.Syntax:NULLIF(value1, value2)
Example:
Input:
SELECT NULLIF(9995463931, contact_num)
from Employee;
Output:
NULLIF(value1, value2)
Example:
Input:
SELECT NULLIF(9995463931, contact_num)
from Employee;
Input:
SELECT NULLIF(9995463931, contact_num)
from Employee;
Output:
Explanation: NULL is displayed for the Employee whose number is matched with the given number. For rest of the Employees value1 is returned.
This article is contributed by akanshgupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
surinderdawra388
SQL-Functions
SQL
Technical Scripter
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Apr, 2022"
},
{
"code": null,
"e": 99,
"s": 54,
"text": "Following are Conditional Expressions in SQL"
},
{
"code": null,
"e": 5356,
"s": 99,
"text": "The CASE Expression: Let you use IF-THEN-ELSE statements without having to invoke procedures.In a simple CASE expression, the SQL searches for the first WHEN......THEN pair for which expr is equal to comparison_expr and returns return_expr. If above condition is not satisfied, an ELSE clause exists, the SQL returns else_expr. Otherwise, returns NULL.We cannot specify literal null for the return_expr and the else_expr. All of the expressions(expr, comparison_expr, return_expr) must be of the same data type.Syntax:CASE expr WHEN comparison_expr1 THEN return_expr1\n [WHEN comparison_expr2 THEN return_expr2\n .\n .\n .\n WHEN comparison_exprn THEN return_exprn\n ELSE else_expr]\nEND\nExample:Input :\nSELECT first_name, department_id, salary,\n CASE department_id WHEN 50 THEN 1.5*salary\n WHEN 12 THEN 2.0*salary\n ELSE salary\n END \"REVISED SALARY\"\nFROM Employee;Output :Explanation: In above SQL statements, the value of department_id is decoded. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary.The DECODE Function : Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement.The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE logic used in various languages. The DECODE function decodes expression after comparing it to each search value. If the expression is the same as search, result is returned.If the default value is omitted, a null value is returned where a search value does not match any of the result values.Syntax:DECODE(col/expression, search1, result1\n [, search2, result2,........,]\n [, default])\nInput :\nSELECT first_name, department_id, salary,\n DECODE(department_id, 50, 1.5*salary,\n 12, 2.0*salary,\n salary)\n \"REVISED SALARY\"\nFROM Employee;\nOutput :Explanation: In above SQL statements, the value of department_id is tested. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary.COALESCE : Returns the first non-null argument. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display.NOTE: Same as CASE expressions, COALESCE also will not evaluate the arguments to the right of the first non-null argument found.Syntax:COALESCE(value [, ......] )\nInput:\nSELECT COALESCE(last_name, '- NA -')\nfrom Employee;\nOutput:Explanation: “- NA -” will be displayed in place where last name is null else respective last names will be shown.GREATEST: Returns the largest value from a list of any number of expressions. Comparison is case sensitive. If datatypes of all the expressions in the list are not same, rest all expressions are converted to the datatype of the first expression for comparison and if this conversion is not possible, SQL will throw an error.NOTE: Returns null if any expression in the list is null.Syntax:GREATEST(expr1, expr2 [, .....] )\nInput:\nSELECT GREATEST('XYZ', 'xyz')\nfrom dual;\nOutput:\nGREATEST('XYZ', 'xyz')\nxyz\nExplanation: ASCII value of small alphabets is greater.Input:\nSELECT GREATEST('XYZ', null, 'xyz')\nfrom dual;\n\nOutput:\nGREATEST('XYZ', null, 'xyz')\n-Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above).IFNULL: If expr1 is not NULL, returns expr1; otherwise it returns expr2. Returns a numeric or string value, depending on the context in which it is used.Syntax:IFNULL(expr1, expr2)\nInput:\nSELECT IFNULL(1,0) \nFROM dual;\nOutput:\n-\n1\nExplanation : Since, no expression is null.Input:\nSELECT IFNULL(NULL,10) \nFROM dual;\n\nOutput:\n--\n10\nExplanation:Since, expr1 is null hence, expr2 is shown.IN: Checks whether a value is present within a set of values and can be used with WHERE, CHECK and creation of views.NOTE: Same as CASE and COALESCE expressions, IN also will not evaluate the arguments to the right of the first non-null argument found.Syntax:WHERE column IN (x1, x2, x3 [,......] )\nInput:\nSELECT * from Employee\nWHERE department_id IN(50, 12);\nOutput:Explanation:All data of Employees is shown with department ID 50 or 12.LEAST: Returns the smallest value from a list of any number of expressions. Comparison is case sensitive. If datatypes of all the expressions in the list are not same, rest all expressions are converted to the datatype of the first expression for comparison and if this conversion is not possible, SQL will throw an error.NOTE: Returns null if any expression in the list is null.Syntax:LEAST(expr1, expr2 [, ......])\n\nstrong>Input:\nSELECT LEAST('XYZ', 'xyz')\nfrom dual;\n\nOutput:\nLEAST('XYZ', 'xyz')\nXYZ\nExplanation: ASCII value of capital alphabets is smaller.\nInput:\nSELECT LEAST('XYZ', null, 'xyz')\nfrom dual;\n\nOutput:\nLEAST('XYZ', null, 'xyz')\n-\nExplanation: Since null is present hence, null will be shown as output (as mentioned to note in description above).NULLIF: Returns a null value if value1=value2, otherwise it returns value1.Syntax:NULLIF(value1, value2)\nExample:\nInput:\nSELECT NULLIF(9995463931, contact_num) \nfrom Employee;\nOutput:"
},
{
"code": null,
"e": 6512,
"s": 5356,
"text": "The CASE Expression: Let you use IF-THEN-ELSE statements without having to invoke procedures.In a simple CASE expression, the SQL searches for the first WHEN......THEN pair for which expr is equal to comparison_expr and returns return_expr. If above condition is not satisfied, an ELSE clause exists, the SQL returns else_expr. Otherwise, returns NULL.We cannot specify literal null for the return_expr and the else_expr. All of the expressions(expr, comparison_expr, return_expr) must be of the same data type.Syntax:CASE expr WHEN comparison_expr1 THEN return_expr1\n [WHEN comparison_expr2 THEN return_expr2\n .\n .\n .\n WHEN comparison_exprn THEN return_exprn\n ELSE else_expr]\nEND\nExample:Input :\nSELECT first_name, department_id, salary,\n CASE department_id WHEN 50 THEN 1.5*salary\n WHEN 12 THEN 2.0*salary\n ELSE salary\n END \"REVISED SALARY\"\nFROM Employee;Output :Explanation: In above SQL statements, the value of department_id is decoded. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary."
},
{
"code": null,
"e": 6729,
"s": 6512,
"text": "CASE expr WHEN comparison_expr1 THEN return_expr1\n [WHEN comparison_expr2 THEN return_expr2\n .\n .\n .\n WHEN comparison_exprn THEN return_exprn\n ELSE else_expr]\nEND\n"
},
{
"code": null,
"e": 6738,
"s": 6729,
"text": "Example:"
},
{
"code": null,
"e": 6957,
"s": 6738,
"text": "Input :\nSELECT first_name, department_id, salary,\n CASE department_id WHEN 50 THEN 1.5*salary\n WHEN 12 THEN 2.0*salary\n ELSE salary\n END \"REVISED SALARY\"\nFROM Employee;Output :"
},
{
"code": null,
"e": 7168,
"s": 6957,
"text": "Input :\nSELECT first_name, department_id, salary,\n CASE department_id WHEN 50 THEN 1.5*salary\n WHEN 12 THEN 2.0*salary\n ELSE salary\n END \"REVISED SALARY\"\nFROM Employee;"
},
{
"code": null,
"e": 7177,
"s": 7168,
"text": "Output :"
},
{
"code": null,
"e": 7373,
"s": 7177,
"text": "Explanation: In above SQL statements, the value of department_id is decoded. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary."
},
{
"code": null,
"e": 8397,
"s": 7373,
"text": "The DECODE Function : Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement.The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE logic used in various languages. The DECODE function decodes expression after comparing it to each search value. If the expression is the same as search, result is returned.If the default value is omitted, a null value is returned where a search value does not match any of the result values.Syntax:DECODE(col/expression, search1, result1\n [, search2, result2,........,]\n [, default])\nInput :\nSELECT first_name, department_id, salary,\n DECODE(department_id, 50, 1.5*salary,\n 12, 2.0*salary,\n salary)\n \"REVISED SALARY\"\nFROM Employee;\nOutput :Explanation: In above SQL statements, the value of department_id is tested. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary."
},
{
"code": null,
"e": 8530,
"s": 8397,
"text": "DECODE(col/expression, search1, result1\n [, search2, result2,........,]\n [, default])\n"
},
{
"code": null,
"e": 8732,
"s": 8530,
"text": "Input :\nSELECT first_name, department_id, salary,\n DECODE(department_id, 50, 1.5*salary,\n 12, 2.0*salary,\n salary)\n \"REVISED SALARY\"\nFROM Employee;\n"
},
{
"code": null,
"e": 8935,
"s": 8732,
"text": "Output :Explanation: In above SQL statements, the value of department_id is tested. If it is 50 then salary is made 1.5 times, if it is 12 then salary is made 2 times, else there is no change in salary."
},
{
"code": null,
"e": 9474,
"s": 8935,
"text": "COALESCE : Returns the first non-null argument. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display.NOTE: Same as CASE expressions, COALESCE also will not evaluate the arguments to the right of the first non-null argument found.Syntax:COALESCE(value [, ......] )\nInput:\nSELECT COALESCE(last_name, '- NA -')\nfrom Employee;\nOutput:Explanation: “- NA -” will be displayed in place where last name is null else respective last names will be shown."
},
{
"code": null,
"e": 9503,
"s": 9474,
"text": "COALESCE(value [, ......] )\n"
},
{
"code": null,
"e": 9563,
"s": 9503,
"text": "Input:\nSELECT COALESCE(last_name, '- NA -')\nfrom Employee;\n"
},
{
"code": null,
"e": 9685,
"s": 9563,
"text": "Output:Explanation: “- NA -” will be displayed in place where last name is null else respective last names will be shown."
},
{
"code": null,
"e": 10454,
"s": 9685,
"text": "GREATEST: Returns the largest value from a list of any number of expressions. Comparison is case sensitive. If datatypes of all the expressions in the list are not same, rest all expressions are converted to the datatype of the first expression for comparison and if this conversion is not possible, SQL will throw an error.NOTE: Returns null if any expression in the list is null.Syntax:GREATEST(expr1, expr2 [, .....] )\nInput:\nSELECT GREATEST('XYZ', 'xyz')\nfrom dual;\nOutput:\nGREATEST('XYZ', 'xyz')\nxyz\nExplanation: ASCII value of small alphabets is greater.Input:\nSELECT GREATEST('XYZ', null, 'xyz')\nfrom dual;\n\nOutput:\nGREATEST('XYZ', null, 'xyz')\n-Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above)."
},
{
"code": null,
"e": 10489,
"s": 10454,
"text": "GREATEST(expr1, expr2 [, .....] )\n"
},
{
"code": null,
"e": 10628,
"s": 10489,
"text": "Input:\nSELECT GREATEST('XYZ', 'xyz')\nfrom dual;\nOutput:\nGREATEST('XYZ', 'xyz')\nxyz\nExplanation: ASCII value of small alphabets is greater."
},
{
"code": null,
"e": 10677,
"s": 10628,
"text": "Input:\nSELECT GREATEST('XYZ', 'xyz')\nfrom dual;\n"
},
{
"code": null,
"e": 10713,
"s": 10677,
"text": "Output:\nGREATEST('XYZ', 'xyz')\nxyz\n"
},
{
"code": null,
"e": 10769,
"s": 10713,
"text": "Explanation: ASCII value of small alphabets is greater."
},
{
"code": null,
"e": 10978,
"s": 10769,
"text": "Input:\nSELECT GREATEST('XYZ', null, 'xyz')\nfrom dual;\n\nOutput:\nGREATEST('XYZ', null, 'xyz')\n-Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above)."
},
{
"code": null,
"e": 11072,
"s": 10978,
"text": "Input:\nSELECT GREATEST('XYZ', null, 'xyz')\nfrom dual;\n\nOutput:\nGREATEST('XYZ', null, 'xyz')\n-"
},
{
"code": null,
"e": 11188,
"s": 11072,
"text": "Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above)."
},
{
"code": null,
"e": 11575,
"s": 11188,
"text": "IFNULL: If expr1 is not NULL, returns expr1; otherwise it returns expr2. Returns a numeric or string value, depending on the context in which it is used.Syntax:IFNULL(expr1, expr2)\nInput:\nSELECT IFNULL(1,0) \nFROM dual;\nOutput:\n-\n1\nExplanation : Since, no expression is null.Input:\nSELECT IFNULL(NULL,10) \nFROM dual;\n\nOutput:\n--\n10\nExplanation:Since, expr1 is null hence, expr2 is shown."
},
{
"code": null,
"e": 11597,
"s": 11575,
"text": "IFNULL(expr1, expr2)\n"
},
{
"code": null,
"e": 11691,
"s": 11597,
"text": "Input:\nSELECT IFNULL(1,0) \nFROM dual;\nOutput:\n-\n1\nExplanation : Since, no expression is null."
},
{
"code": null,
"e": 11730,
"s": 11691,
"text": "Input:\nSELECT IFNULL(1,0) \nFROM dual;\n"
},
{
"code": null,
"e": 11743,
"s": 11730,
"text": "Output:\n-\n1\n"
},
{
"code": null,
"e": 11787,
"s": 11743,
"text": "Explanation : Since, no expression is null."
},
{
"code": null,
"e": 11900,
"s": 11787,
"text": "Input:\nSELECT IFNULL(NULL,10) \nFROM dual;\n\nOutput:\n--\n10\nExplanation:Since, expr1 is null hence, expr2 is shown."
},
{
"code": null,
"e": 11958,
"s": 11900,
"text": "Input:\nSELECT IFNULL(NULL,10) \nFROM dual;\n\nOutput:\n--\n10\n"
},
{
"code": null,
"e": 12014,
"s": 11958,
"text": "Explanation:Since, expr1 is null hence, expr2 is shown."
},
{
"code": null,
"e": 12454,
"s": 12014,
"text": "IN: Checks whether a value is present within a set of values and can be used with WHERE, CHECK and creation of views.NOTE: Same as CASE and COALESCE expressions, IN also will not evaluate the arguments to the right of the first non-null argument found.Syntax:WHERE column IN (x1, x2, x3 [,......] )\nInput:\nSELECT * from Employee\nWHERE department_id IN(50, 12);\nOutput:Explanation:All data of Employees is shown with department ID 50 or 12."
},
{
"code": null,
"e": 12495,
"s": 12454,
"text": "WHERE column IN (x1, x2, x3 [,......] )\n"
},
{
"code": null,
"e": 12558,
"s": 12495,
"text": "Input:\nSELECT * from Employee\nWHERE department_id IN(50, 12);\n"
},
{
"code": null,
"e": 12566,
"s": 12558,
"text": "Output:"
},
{
"code": null,
"e": 12638,
"s": 12566,
"text": "Explanation:All data of Employees is shown with department ID 50 or 12."
},
{
"code": null,
"e": 13403,
"s": 12638,
"text": "LEAST: Returns the smallest value from a list of any number of expressions. Comparison is case sensitive. If datatypes of all the expressions in the list are not same, rest all expressions are converted to the datatype of the first expression for comparison and if this conversion is not possible, SQL will throw an error.NOTE: Returns null if any expression in the list is null.Syntax:LEAST(expr1, expr2 [, ......])\n\nstrong>Input:\nSELECT LEAST('XYZ', 'xyz')\nfrom dual;\n\nOutput:\nLEAST('XYZ', 'xyz')\nXYZ\nExplanation: ASCII value of capital alphabets is smaller.\nInput:\nSELECT LEAST('XYZ', null, 'xyz')\nfrom dual;\n\nOutput:\nLEAST('XYZ', null, 'xyz')\n-\nExplanation: Since null is present hence, null will be shown as output (as mentioned to note in description above)."
},
{
"code": null,
"e": 13411,
"s": 13403,
"text": "Syntax:"
},
{
"code": null,
"e": 13443,
"s": 13411,
"text": "LEAST(expr1, expr2 [, ......])\n"
},
{
"code": null,
"e": 13587,
"s": 13443,
"text": "\nstrong>Input:\nSELECT LEAST('XYZ', 'xyz')\nfrom dual;\n\nOutput:\nLEAST('XYZ', 'xyz')\nXYZ\nExplanation: ASCII value of capital alphabets is smaller."
},
{
"code": null,
"e": 13674,
"s": 13587,
"text": "\nstrong>Input:\nSELECT LEAST('XYZ', 'xyz')\nfrom dual;\n\nOutput:\nLEAST('XYZ', 'xyz')\nXYZ\n"
},
{
"code": null,
"e": 13761,
"s": 13674,
"text": "\nstrong>Input:\nSELECT LEAST('XYZ', 'xyz')\nfrom dual;\n\nOutput:\nLEAST('XYZ', 'xyz')\nXYZ\n"
},
{
"code": null,
"e": 13819,
"s": 13761,
"text": "Explanation: ASCII value of capital alphabets is smaller."
},
{
"code": null,
"e": 14024,
"s": 13819,
"text": "\nInput:\nSELECT LEAST('XYZ', null, 'xyz')\nfrom dual;\n\nOutput:\nLEAST('XYZ', null, 'xyz')\n-\nExplanation: Since null is present hence, null will be shown as output (as mentioned to note in description above)."
},
{
"code": null,
"e": 14114,
"s": 14024,
"text": "\nInput:\nSELECT LEAST('XYZ', null, 'xyz')\nfrom dual;\n\nOutput:\nLEAST('XYZ', null, 'xyz')\n-\n"
},
{
"code": null,
"e": 14204,
"s": 14114,
"text": "\nInput:\nSELECT LEAST('XYZ', null, 'xyz')\nfrom dual;\n\nOutput:\nLEAST('XYZ', null, 'xyz')\n-\n"
},
{
"code": null,
"e": 14320,
"s": 14204,
"text": "Explanation: Since null is present hence, null will be shown as output (as mentioned to note in description above)."
},
{
"code": null,
"e": 14504,
"s": 14320,
"text": "NULLIF: Returns a null value if value1=value2, otherwise it returns value1.Syntax:NULLIF(value1, value2)\nExample:\nInput:\nSELECT NULLIF(9995463931, contact_num) \nfrom Employee;\nOutput:"
},
{
"code": null,
"e": 14528,
"s": 14504,
"text": "NULLIF(value1, value2)\n"
},
{
"code": null,
"e": 14537,
"s": 14528,
"text": "Example:"
},
{
"code": null,
"e": 14601,
"s": 14537,
"text": "\nInput:\nSELECT NULLIF(9995463931, contact_num) \nfrom Employee;\n"
},
{
"code": null,
"e": 14665,
"s": 14601,
"text": "\nInput:\nSELECT NULLIF(9995463931, contact_num) \nfrom Employee;\n"
},
{
"code": null,
"e": 14673,
"s": 14665,
"text": "Output:"
},
{
"code": null,
"e": 14814,
"s": 14673,
"text": "Explanation: NULL is displayed for the Employee whose number is matched with the given number. For rest of the Employees value1 is returned."
},
{
"code": null,
"e": 15113,
"s": 14814,
"text": "This article is contributed by akanshgupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 15238,
"s": 15113,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 15255,
"s": 15238,
"text": "surinderdawra388"
},
{
"code": null,
"e": 15269,
"s": 15255,
"text": "SQL-Functions"
},
{
"code": null,
"e": 15273,
"s": 15269,
"text": "SQL"
},
{
"code": null,
"e": 15292,
"s": 15273,
"text": "Technical Scripter"
},
{
"code": null,
"e": 15296,
"s": 15292,
"text": "SQL"
},
{
"code": null,
"e": 15394,
"s": 15296,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15405,
"s": 15394,
"text": "CTE in SQL"
},
{
"code": null,
"e": 15436,
"s": 15405,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 15502,
"s": 15436,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 15526,
"s": 15502,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 15538,
"s": 15526,
"text": "SQL | Views"
},
{
"code": null,
"e": 15583,
"s": 15538,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 15607,
"s": 15583,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 15639,
"s": 15607,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 15678,
"s": 15639,
"text": "Difference between DDL and DML in DBMS"
}
] |
C++ Program to Check if a string can be obtained by rotating another string 2 places | 06 Jan, 2022
Given two strings, the task is to find if a string can be obtained by rotating another string two places.
Examples:
Input: string1 = “amazon”, string2 = “azonam” Output: Yes // rotated anti-clockwiseInput: string1 = “amazon”, string2 = “onamaz” Output: Yes // rotated clockwise
Asked in: Amazon Interview
1- There can be only two cases:
a) Clockwise rotated
b) Anti-clockwise rotated
2- If clockwise rotated that means elements
are shifted in right.
So, check if a substring[2.... len-1] of
string2 when concatenated with substring[0,1]
of string2 is equal to string1. Then, return true.
3- Else, check if it is rotated anti-clockwise
that means elements are shifted to left.
So, check if concatenation of substring[len-2, len-1]
with substring[0....len-3] makes it equals to
string1. Then return true.
4- Else, return false.
Below is the implementation of the above approach.
C++
// C++ program to check if a string // is two time rotation of another string.#include<bits/stdc++.h>using namespace std; // Function to check if string2 is // obtained by string 1bool isRotated(string str1, string str2){ if (str1.length() != str2.length()) return false; if(str1.length()<2){ return str1.compare(str2) == 0; } string clock_rot = ""; string anticlock_rot = ""; int len = str2.length(); // Initialize string as anti-clockwise // rotation anticlock_rot = anticlock_rot + str2.substr(len-2, 2) + str2.substr(0, len-2) ; // Initialize string as clock wise // rotation clock_rot = clock_rot + str2.substr(2) + str2.substr(0, 2) ; // check if any of them is equal // to string1 return (str1.compare(clock_rot) == 0 || str1.compare(anticlock_rot) == 0);} // Driver codeint main(){ string str1 = "geeks"; string str2 = "eksge"; isRotated(str1, str2) ? cout << "Yes" : cout << "No"; return 0;}
Output:
Yes
Please refer complete article on Check if a string can be obtained by rotating another string 2 places for more details!
Accolite
Amazon
rotation
C++
C++ Programs
Strings
Accolite
Amazon
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 135,
"s": 28,
"text": "Given two strings, the task is to find if a string can be obtained by rotating another string two places. "
},
{
"code": null,
"e": 146,
"s": 135,
"text": "Examples: "
},
{
"code": null,
"e": 308,
"s": 146,
"text": "Input: string1 = “amazon”, string2 = “azonam” Output: Yes // rotated anti-clockwiseInput: string1 = “amazon”, string2 = “onamaz” Output: Yes // rotated clockwise"
},
{
"code": null,
"e": 335,
"s": 308,
"text": "Asked in: Amazon Interview"
},
{
"code": null,
"e": 893,
"s": 335,
"text": "1- There can be only two cases:\n a) Clockwise rotated\n b) Anti-clockwise rotated\n\n2- If clockwise rotated that means elements\n are shifted in right.\n So, check if a substring[2.... len-1] of \n string2 when concatenated with substring[0,1]\n of string2 is equal to string1. Then, return true.\n\n3- Else, check if it is rotated anti-clockwise \n that means elements are shifted to left.\n So, check if concatenation of substring[len-2, len-1]\n with substring[0....len-3] makes it equals to\n string1. Then return true.\n\n4- Else, return false."
},
{
"code": null,
"e": 944,
"s": 893,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 948,
"s": 944,
"text": "C++"
},
{
"code": "// C++ program to check if a string // is two time rotation of another string.#include<bits/stdc++.h>using namespace std; // Function to check if string2 is // obtained by string 1bool isRotated(string str1, string str2){ if (str1.length() != str2.length()) return false; if(str1.length()<2){ return str1.compare(str2) == 0; } string clock_rot = \"\"; string anticlock_rot = \"\"; int len = str2.length(); // Initialize string as anti-clockwise // rotation anticlock_rot = anticlock_rot + str2.substr(len-2, 2) + str2.substr(0, len-2) ; // Initialize string as clock wise // rotation clock_rot = clock_rot + str2.substr(2) + str2.substr(0, 2) ; // check if any of them is equal // to string1 return (str1.compare(clock_rot) == 0 || str1.compare(anticlock_rot) == 0);} // Driver codeint main(){ string str1 = \"geeks\"; string str2 = \"eksge\"; isRotated(str1, str2) ? cout << \"Yes\" : cout << \"No\"; return 0;}",
"e": 2050,
"s": 948,
"text": null
},
{
"code": null,
"e": 2059,
"s": 2050,
"text": "Output: "
},
{
"code": null,
"e": 2063,
"s": 2059,
"text": "Yes"
},
{
"code": null,
"e": 2184,
"s": 2063,
"text": "Please refer complete article on Check if a string can be obtained by rotating another string 2 places for more details!"
},
{
"code": null,
"e": 2193,
"s": 2184,
"text": "Accolite"
},
{
"code": null,
"e": 2200,
"s": 2193,
"text": "Amazon"
},
{
"code": null,
"e": 2209,
"s": 2200,
"text": "rotation"
},
{
"code": null,
"e": 2213,
"s": 2209,
"text": "C++"
},
{
"code": null,
"e": 2226,
"s": 2213,
"text": "C++ Programs"
},
{
"code": null,
"e": 2234,
"s": 2226,
"text": "Strings"
},
{
"code": null,
"e": 2243,
"s": 2234,
"text": "Accolite"
},
{
"code": null,
"e": 2250,
"s": 2243,
"text": "Amazon"
},
{
"code": null,
"e": 2258,
"s": 2250,
"text": "Strings"
},
{
"code": null,
"e": 2262,
"s": 2258,
"text": "CPP"
},
{
"code": null,
"e": 2360,
"s": 2262,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2384,
"s": 2360,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2404,
"s": 2384,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2437,
"s": 2404,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2481,
"s": 2437,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2506,
"s": 2481,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2541,
"s": 2506,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 2575,
"s": 2541,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 2619,
"s": 2575,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 2678,
"s": 2619,
"text": "How to return multiple values from a function in C or C++?"
}
] |
xdg-open command in Linux with Examples | 24 May, 2019
xdg-open command in the Linux system is used to open a file or URL in the user’s preferred application.The URL will be opened in the user’s preferred web browser if a URL is provided. The file will be opened in the preferred application for files of that type if a file is provided. xdg-open supports ftp, file, https and http URLs. This can be used inside a desktop session only. It is not recommended to use xdg-open as root. Here, the zero is an indication of success while non-zero show the failure.
Syntax:
xdg-open {file | URL}
Example:
xdg-open read.html
Options:
xdg-open –version : This option will show the xdg-utils version information.xdg-open --version
xdg-open --version
xdg-open –help: This option will show command synopsis.xdg-open --help
xdg-open --help
xdg-open –manual: This option will show the manual page.xdg-open --manual
xdg-open --manual
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 May, 2019"
},
{
"code": null,
"e": 558,
"s": 54,
"text": "xdg-open command in the Linux system is used to open a file or URL in the user’s preferred application.The URL will be opened in the user’s preferred web browser if a URL is provided. The file will be opened in the preferred application for files of that type if a file is provided. xdg-open supports ftp, file, https and http URLs. This can be used inside a desktop session only. It is not recommended to use xdg-open as root. Here, the zero is an indication of success while non-zero show the failure."
},
{
"code": null,
"e": 566,
"s": 558,
"text": "Syntax:"
},
{
"code": null,
"e": 589,
"s": 566,
"text": "xdg-open {file | URL}\n"
},
{
"code": null,
"e": 598,
"s": 589,
"text": "Example:"
},
{
"code": null,
"e": 617,
"s": 598,
"text": "xdg-open read.html"
},
{
"code": null,
"e": 626,
"s": 617,
"text": "Options:"
},
{
"code": null,
"e": 721,
"s": 626,
"text": "xdg-open –version : This option will show the xdg-utils version information.xdg-open --version"
},
{
"code": null,
"e": 740,
"s": 721,
"text": "xdg-open --version"
},
{
"code": null,
"e": 811,
"s": 740,
"text": "xdg-open –help: This option will show command synopsis.xdg-open --help"
},
{
"code": null,
"e": 827,
"s": 811,
"text": "xdg-open --help"
},
{
"code": null,
"e": 901,
"s": 827,
"text": "xdg-open –manual: This option will show the manual page.xdg-open --manual"
},
{
"code": null,
"e": 919,
"s": 901,
"text": "xdg-open --manual"
},
{
"code": null,
"e": 933,
"s": 919,
"text": "linux-command"
},
{
"code": null,
"e": 953,
"s": 933,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 964,
"s": 953,
"text": "Linux-Unix"
}
] |
Find indices of elements equal to zero in a NumPy array | 05 Sep, 2020
Sometimes we need to find out the indices of all null elements in the array. Numpy provides many functions to compute indices of all null elements.
Method 1: Finding indices of null elements using numpy.where()
This function returns the indices of elements in an input array where the given condition is satisfied.
Syntax :
numpy.where(condition[, x, y])
When True, yield x, otherwise yield y
Python3
# importing Numpy packageimport numpy as np # creating a 1-D Numpy arrayn_array = np.array([1, 0, 2, 0, 3, 0, 0, 5, 6, 7, 5, 0, 8]) print("Original array:")print(n_array) # finding indices of null elements using np.where()print("\nIndices of elements equal to zero of the \given 1-D array:") res = np.where(n_array == 0)[0]print(res)
Output:
Method 2: Finding indices of null elements using numpy.argwhere()
This function is used to find the indices of array elements that are non-zero, grouped by element.
Syntax :
numpy.argwhere(arr)
Python3
# importing Numpy packageimport numpy as np # creating a 3-D Numpy arrayn_array = np.array([[0, 2, 3], [4, 1, 0], [0, 0, 2]]) print("Original array:")print(n_array) # finding indices of null elements # using np.argwhere()print("\nIndices of null elements:")res = np.argwhere(n_array == 0) print(res)
Output:
Method 3: Finding the indices of null elements using numpy.nonzero()
This function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension.
Syntax:
numpy.nonzero(arr)
Python3
# importing Numpy packageimport numpy as np # creating a 1-D Numpy arrayn_array = np.array([1, 10, 2, 0, 3, 9, 0, 5, 0, 7, 5, 0, 0]) print("Original array:")print(n_array) # finding indices of null elements using # np.nonzero()print("\nIndices of null elements:") res = np.nonzero(n_array == 0)print(res)
Output:
Python numpy-Indexing
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 177,
"s": 28,
"text": "Sometimes we need to find out the indices of all null elements in the array. Numpy provides many functions to compute indices of all null elements. "
},
{
"code": null,
"e": 240,
"s": 177,
"text": "Method 1: Finding indices of null elements using numpy.where()"
},
{
"code": null,
"e": 344,
"s": 240,
"text": "This function returns the indices of elements in an input array where the given condition is satisfied."
},
{
"code": null,
"e": 354,
"s": 344,
"text": "Syntax : "
},
{
"code": null,
"e": 424,
"s": 354,
"text": "numpy.where(condition[, x, y])\nWhen True, yield x, otherwise yield y\n"
},
{
"code": null,
"e": 432,
"s": 424,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # creating a 1-D Numpy arrayn_array = np.array([1, 0, 2, 0, 3, 0, 0, 5, 6, 7, 5, 0, 8]) print(\"Original array:\")print(n_array) # finding indices of null elements using np.where()print(\"\\nIndices of elements equal to zero of the \\given 1-D array:\") res = np.where(n_array == 0)[0]print(res)",
"e": 789,
"s": 432,
"text": null
},
{
"code": null,
"e": 797,
"s": 789,
"text": "Output:"
},
{
"code": null,
"e": 863,
"s": 797,
"text": "Method 2: Finding indices of null elements using numpy.argwhere()"
},
{
"code": null,
"e": 962,
"s": 863,
"text": "This function is used to find the indices of array elements that are non-zero, grouped by element."
},
{
"code": null,
"e": 972,
"s": 962,
"text": "Syntax : "
},
{
"code": null,
"e": 993,
"s": 972,
"text": "numpy.argwhere(arr)\n"
},
{
"code": null,
"e": 1001,
"s": 993,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # creating a 3-D Numpy arrayn_array = np.array([[0, 2, 3], [4, 1, 0], [0, 0, 2]]) print(\"Original array:\")print(n_array) # finding indices of null elements # using np.argwhere()print(\"\\nIndices of null elements:\")res = np.argwhere(n_array == 0) print(res)",
"e": 1343,
"s": 1001,
"text": null
},
{
"code": null,
"e": 1351,
"s": 1343,
"text": "Output:"
},
{
"code": null,
"e": 1420,
"s": 1351,
"text": "Method 3: Finding the indices of null elements using numpy.nonzero()"
},
{
"code": null,
"e": 1628,
"s": 1420,
"text": "This function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension."
},
{
"code": null,
"e": 1636,
"s": 1628,
"text": "Syntax:"
},
{
"code": null,
"e": 1655,
"s": 1636,
"text": "numpy.nonzero(arr)"
},
{
"code": null,
"e": 1663,
"s": 1655,
"text": "Python3"
},
{
"code": "# importing Numpy packageimport numpy as np # creating a 1-D Numpy arrayn_array = np.array([1, 10, 2, 0, 3, 9, 0, 5, 0, 7, 5, 0, 0]) print(\"Original array:\")print(n_array) # finding indices of null elements using # np.nonzero()print(\"\\nIndices of null elements:\") res = np.nonzero(n_array == 0)print(res)",
"e": 1992,
"s": 1663,
"text": null
},
{
"code": null,
"e": 2000,
"s": 1992,
"text": "Output:"
},
{
"code": null,
"e": 2022,
"s": 2000,
"text": "Python numpy-Indexing"
},
{
"code": null,
"e": 2035,
"s": 2022,
"text": "Python-numpy"
},
{
"code": null,
"e": 2042,
"s": 2035,
"text": "Python"
},
{
"code": null,
"e": 2140,
"s": 2042,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2172,
"s": 2140,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2199,
"s": 2172,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2220,
"s": 2199,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2243,
"s": 2220,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2274,
"s": 2243,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2330,
"s": 2274,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2372,
"s": 2330,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2414,
"s": 2372,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2453,
"s": 2414,
"text": "Python | Get unique values from a list"
}
] |
Declare a const array in C# | In C#, use readonly to declare a const array.
public static readonly string[] a = { "Car", "Motorbike", "Cab" };
In readonly, you can set the value at runtime as well unlike const.
Another alternative of achieving what we saw above −
public ReadOnlyCollection<string> a { get { return new List<string> { "Car", "Motorbike", "Cab" }.AsReadOnly();}}
.NET framework 4.5 brings an improvement to what we saw −
public ReadOnlyCollection<string> a { get; } = new ReadOnlyCollection<string>(
new string[] { "Car", "Motorbike", "Cab" }
); | [
{
"code": null,
"e": 1108,
"s": 1062,
"text": "In C#, use readonly to declare a const array."
},
{
"code": null,
"e": 1175,
"s": 1108,
"text": "public static readonly string[] a = { \"Car\", \"Motorbike\", \"Cab\" };"
},
{
"code": null,
"e": 1243,
"s": 1175,
"text": "In readonly, you can set the value at runtime as well unlike const."
},
{
"code": null,
"e": 1296,
"s": 1243,
"text": "Another alternative of achieving what we saw above −"
},
{
"code": null,
"e": 1411,
"s": 1296,
"text": "public ReadOnlyCollection<string> a { get { return new List<string> { \"Car\", \"Motorbike\", \"Cab\" }.AsReadOnly();}}\n"
},
{
"code": null,
"e": 1469,
"s": 1411,
"text": ".NET framework 4.5 brings an improvement to what we saw −"
},
{
"code": null,
"e": 1594,
"s": 1469,
"text": "public ReadOnlyCollection<string> a { get; } = new ReadOnlyCollection<string>(\nnew string[] { \"Car\", \"Motorbike\", \"Cab\" }\n);"
}
] |
Automating, Orchestrating, and Scheduling tasks in Python data pipelines. | Towards Data Science | I was a big fan of Apache Airflow. Even today, I don’t have many complaints about it. But the new technology Prefect amazed me in many ways, and I can’t help but migrating everything to it.
Prefect (and Airflow) is a workflow automation tool. You can orchestrate individual tasks to do more complex work. You could manage task dependencies, retry tasks when they fail, schedule them, etc.
I trust workflow management is the backbone of every data science project. Even small projects can have remarkable benefits with a tool like Prefect. It eliminates a significant part of repetitive tasks. Not to mention, it also removes the mental clutter in a complex project.
This article covers some of the frequent questions about Prefect. It includes,
a short intro to Prefect’s core concepts;
why I decided to migrate from Airflow;
Prefect’s incredible features and integration with other technologies, and;
how to decide between its cloud vs. on-premise deployment options.
Prefect is both a minimal and complete workflow management tool. It’s unbelievably simple to set up. Yet it can do everything tools such as Airflow can and more.
You can use PyPI, Conda, or Pipenv to install it, and it’s ready to rock. More on this in comparison with the Airflow section.
pip install prefect# conda install -c conda-forge prefect# pipenv install --pre prefect
Before we dive into use Prefect, let’s first see an unmanaged workflow. It makes understanding the role of Prefect in workflow management easy.
The below script queries an API (Extract — E), picks the relevant fields from it (Transform — T), and appends them to a file (Load — L). It contains three functions that perform each of the tasks mentioned. It’s a straightforward yet everyday use case of workflow management tools — ETL.
This script downloads weather data from the OpenWeatherMap API and stores the windspeed value in a file. ETL applications in real life could be complex. But this example application covers the fundamental aspects very well.
Note: Please replace the API key with a real one. You can get one from https://openweathermap.org/api.
You can run this script with the command python app.pywhere app.py is the name of your script file. This will create a new file called windspeed.txt in the current directory with one value. It’s the windspeed at Boston, MA, at the time you reach the API. If you rerun the script, it’ll append another value to the same file.
The above script works well. Yet, it lacks some critical features of a complete ETL, such as retrying and scheduling. Also, as mentioned earlier, a real-life ETL may have hundreds of tasks in a single workflow. Some of them can be run in parallel, whereas some depend on one or more other tasks.
Imagine if there is a temporary network issue that prevents you from calling the API. The script would fail immediately with no further attempt. In live applications, such downtimes aren’t a miracle. They happen for several reasons — server downtime, network downtime, server query limit exceeds.
Also, you have to manually execute the above script every time to update your windspeed.txt file. Yet, scheduling the workflow to run at a specific time in a predefined interval is common in ETL workflows.
This is where tools such as Prefect and Airflow come to the rescue. Here’s how you could tweak the above code to make it a Prefect workflow.
The @task decorator converts a regular python function into a Prefect task. The optional arguments allow you to specify its retry behavior. We’ve configured the function to attempt three times before it fails in the above example. We’ve also configured it to delay each retry by three minutes.
With this new setup, our ETL is resilient to network issues we discussed earlier.
To test its functioning, disconnect your computer from the network and run the script with python app.py. You’ll see a message that the first attempt failed, and the next one will begin in the next 3 minutes. Within three minutes, connect your computer back to the internet. The already running script will now finish without any errors.
Retrying is only part of the ETL story. Another challenge for many workflow applications is to run them in scheduled intervals. Prefect’s scheduling API is straightforward for any Python programmer. Here’s how it works.
We’ve created an IntervalSchedule object that starts five seconds from the execution of the script. We’ve also configured it to run in a one-minute interval.
If you run the script with python app.py and monitor the windspeed.txt file, you will see new values in it every minute.
In addition to this simple scheduling, Prefect’s schedule API offers more control over it. You can schedule workflows in a cron-like method, use clock time with timezones, or do more fun stuff like executing workflow only on weekends. I haven’t covered them all here, but Prefect's official docs about this are perfect.
Like Airflow (and many others,) Prefect too ships with a server with a beautiful UI. It allows you to control and visualize your workflow executions.
To run this, you need to have docker and docker-compose installed on your computer. But starting it is surprisingly a single command.
$ prefect server start
This command will start the prefect server, and you can access it through your web browser: http://localhost:8080/.
However, the Prefect server alone could not execute your workflows. Its role is only enabling a control pannel to all your Prefect activities. Because this dashboard is decoupled from the rest of the application, you can use the Prefect cloud to do the same. We’ll discuss this in detail later.
To execute tasks, we need a few more things. The good news is, they, too, aren’t complicated.
Because servers are only a control panel, we need an agent to execute the workflow. The below command will start a local agent. Instead of a local agent, you can choose a docker agent or a Kubernetes one if your project needs them.
$ prefect agent local start
Once the server and the agent are running, you’ll have to create a project and register your workflow with that project. To do this, change the line that executes the flow to the following.
Now in the terminal, you can create a project with the prefect create project <project name> command. Then rerunning the script will register it to the project instead of running it immediately.
$ prefect create project 'Tutorial'$ python app.py
In the web UI, you can see the new Project ‘Tutorial’ is in the dropdown, and our windspeed tracker is in the list of flows. The flow is already scheduled and running. If you prefer, you can run them manually as well.
The workflow we created in the previous exercise is rigid. It queries only for Boston, MA, and we can not change it. This is where we can use parameters. Here’s how we tweak our code to accept a parameter at the run time.
We’ve changed the function to accept the city argument and set it dynamically in the API query. Inside the Flow, we create a parameter object with the default value ‘Boston’ and pass it to the Extract task.
If you run the windspeed tracker workflow manually in the UI, you’ll see a section called input. Here you can set the value of the city for every execution.
This is a convenient way to run workflows. In many cases, ETLs and any other workflow come with run-time parameters.
Airflow is a fantastic platform for workflow management. It saved me a ton of time on many projects. Yet, we need to appreciate new technologies taking over the old ones. That’s the case with Airflow and Prefect.
Airflow got many things right, but its core assumptions never anticipated the rich variety of data applications that have emerged.
— Prefect Documentation.
What I describe here aren’t dead-ends if you’re preferring Airflow. We have workarounds for most problems. Yet, it’s convenient in Prefect because the tool natively supports them.
Prefect’s installation is exceptionally straightforward compared to Airflow. For trained eyes, it may not be a problem. Yet, for whoever wants to start on workflow orchestration and automation, it’s a hassle.
Airflow needs a server running in the backend to perform any task. Yet, in Prefect, a server is optional. This is a massive benefit of using Prefect. I have many pet projects running on my computer as services. Earlier, I had to have an Airflow server commencing at the startup. Because Prefect could run standalone, I don’t have to turn on this additional server anymore.
Airflow doesn’t have the flexibility to run workflows (or DAGs) with parameters. The workaround I use to have is to let the application read them from a database. This isn’t an excellent programming technique for such a simple task. Prefect’s parameter concept is exceptional on this front.
Prefect allows having different versions of the same workflow. Every time you register a workflow to the project, it creates a new version. If you need to run a previous version, you can easily select it in a dropdown. This isn’t possible with Airflow.
Prefect also allows us to create teams and role-based access controls. Each team could manage its configuration. Authorization is a critical part of every modern application, and Prefect handles it in the best way possible.
Lastly, I find Prefect’s UI more intuitive and appealing. Airflow’s UI, especially its task execution visualization, was difficult at first to understand.
Prefect has inbuilt integration with many other technologies. It eliminates a ton of overhead and makes working with them super easy.
Live projects often have to deal with several technologies. For example, when your ETL fails, you may want to send an email or a Slack notification to the maintainer.
In Prefect, sending such notifications is effortless. You can use the EmailTask from the Prefect’s task library, set the credentials, and start sending emails.
You can learn more about Prefect’s rich ecosystem in their official documentation. In this article, we’ll see how to send email notifications.
To send emails, we need to make the credentials accessible to the Prefect agent. You can do that by creating the below file in $HOME/.prefect/config.toml.
Your app is now ready to send emails. Here’s how we send a notification when we successfully captured a windspeed measure.
In the above code, we’ve created an instance of the EmailTask class. We’ve used all the static elements of our email configurations during initiating. Then inside the Flow, we’ve used it with passing variable content.
This configuration above will send an email with the captured windspeed measurement. But its subject will always remain ‘A new windspeed captured.’
We’ve already looked into how we can start an on-premise server. Because this server is only a control panel, you could easily use the cloud version instead. To do this, we have few additional steps to follow.
Create a Prefect cloud account.Generate a key from the API Key Page.In your terminal, set the backend to cloud: prefect backend cloud.Also login with the generated key: prefect auth login --key YOUR_API_KEY.Now, start the agent as usual. prefect agent local start.
Create a Prefect cloud account.
Generate a key from the API Key Page.
In your terminal, set the backend to cloud: prefect backend cloud.
Also login with the generated key: prefect auth login --key YOUR_API_KEY.
Now, start the agent as usual. prefect agent local start.
In the cloud dashboard, you can manage everything you did on the local server before.
A big question when choosing between cloud and server versions is security. According to Prefect‘s docs, the server only stores workflow execution-related data and voluntary information provided by the user. Since the agent in your local computer executes the logic, you can control where you store your data.
The cloud option is suitable for performance reasons too. With one cloud server, you can manage more than one agent. Thus, you can scale your app effortlessly.
Airflow was my ultimate choice for building ETLs and other workflow management applications. Yet, Prefect changed my mind, and now I’m migrating everything from Airflow to Prefect.
Prefect is a straightforward tool that is flexible to extend beyond what Airflow can do. You can run it even inside a Jupyter notebook. Also, you can host it as a complete task management solution.
In addition to the central problem of workflow management, Prefect solves several other issues you may frequently encounter in a live system. Managing teams with authorization controls, sending notifications are some of them.
In this article, we’ve discussed how to create an ETL that
retries some tasks as configured;
run workflows in a schedule;
accepts run-time parameters, and;
sends an email notification when it’s done.
We’ve only scratched the surface of Prefects capabilities. I recommend reading the official documentation for more information.
Thanks for reading, friend! It seems you, and I have lots of common interests. I’d love to connect with you on LinkedIn, Twitter, and Medium.
Not a Medium member yet? Please use this link to become a member. You can enjoy thousands of insightful articles and support me as I earn a small commission for referring you. | [
{
"code": null,
"e": 237,
"s": 47,
"text": "I was a big fan of Apache Airflow. Even today, I don’t have many complaints about it. But the new technology Prefect amazed me in many ways, and I can’t help but migrating everything to it."
},
{
"code": null,
"e": 436,
"s": 237,
"text": "Prefect (and Airflow) is a workflow automation tool. You can orchestrate individual tasks to do more complex work. You could manage task dependencies, retry tasks when they fail, schedule them, etc."
},
{
"code": null,
"e": 713,
"s": 436,
"text": "I trust workflow management is the backbone of every data science project. Even small projects can have remarkable benefits with a tool like Prefect. It eliminates a significant part of repetitive tasks. Not to mention, it also removes the mental clutter in a complex project."
},
{
"code": null,
"e": 792,
"s": 713,
"text": "This article covers some of the frequent questions about Prefect. It includes,"
},
{
"code": null,
"e": 834,
"s": 792,
"text": "a short intro to Prefect’s core concepts;"
},
{
"code": null,
"e": 873,
"s": 834,
"text": "why I decided to migrate from Airflow;"
},
{
"code": null,
"e": 949,
"s": 873,
"text": "Prefect’s incredible features and integration with other technologies, and;"
},
{
"code": null,
"e": 1016,
"s": 949,
"text": "how to decide between its cloud vs. on-premise deployment options."
},
{
"code": null,
"e": 1178,
"s": 1016,
"text": "Prefect is both a minimal and complete workflow management tool. It’s unbelievably simple to set up. Yet it can do everything tools such as Airflow can and more."
},
{
"code": null,
"e": 1305,
"s": 1178,
"text": "You can use PyPI, Conda, or Pipenv to install it, and it’s ready to rock. More on this in comparison with the Airflow section."
},
{
"code": null,
"e": 1393,
"s": 1305,
"text": "pip install prefect# conda install -c conda-forge prefect# pipenv install --pre prefect"
},
{
"code": null,
"e": 1537,
"s": 1393,
"text": "Before we dive into use Prefect, let’s first see an unmanaged workflow. It makes understanding the role of Prefect in workflow management easy."
},
{
"code": null,
"e": 1825,
"s": 1537,
"text": "The below script queries an API (Extract — E), picks the relevant fields from it (Transform — T), and appends them to a file (Load — L). It contains three functions that perform each of the tasks mentioned. It’s a straightforward yet everyday use case of workflow management tools — ETL."
},
{
"code": null,
"e": 2049,
"s": 1825,
"text": "This script downloads weather data from the OpenWeatherMap API and stores the windspeed value in a file. ETL applications in real life could be complex. But this example application covers the fundamental aspects very well."
},
{
"code": null,
"e": 2152,
"s": 2049,
"text": "Note: Please replace the API key with a real one. You can get one from https://openweathermap.org/api."
},
{
"code": null,
"e": 2477,
"s": 2152,
"text": "You can run this script with the command python app.pywhere app.py is the name of your script file. This will create a new file called windspeed.txt in the current directory with one value. It’s the windspeed at Boston, MA, at the time you reach the API. If you rerun the script, it’ll append another value to the same file."
},
{
"code": null,
"e": 2773,
"s": 2477,
"text": "The above script works well. Yet, it lacks some critical features of a complete ETL, such as retrying and scheduling. Also, as mentioned earlier, a real-life ETL may have hundreds of tasks in a single workflow. Some of them can be run in parallel, whereas some depend on one or more other tasks."
},
{
"code": null,
"e": 3070,
"s": 2773,
"text": "Imagine if there is a temporary network issue that prevents you from calling the API. The script would fail immediately with no further attempt. In live applications, such downtimes aren’t a miracle. They happen for several reasons — server downtime, network downtime, server query limit exceeds."
},
{
"code": null,
"e": 3276,
"s": 3070,
"text": "Also, you have to manually execute the above script every time to update your windspeed.txt file. Yet, scheduling the workflow to run at a specific time in a predefined interval is common in ETL workflows."
},
{
"code": null,
"e": 3417,
"s": 3276,
"text": "This is where tools such as Prefect and Airflow come to the rescue. Here’s how you could tweak the above code to make it a Prefect workflow."
},
{
"code": null,
"e": 3711,
"s": 3417,
"text": "The @task decorator converts a regular python function into a Prefect task. The optional arguments allow you to specify its retry behavior. We’ve configured the function to attempt three times before it fails in the above example. We’ve also configured it to delay each retry by three minutes."
},
{
"code": null,
"e": 3793,
"s": 3711,
"text": "With this new setup, our ETL is resilient to network issues we discussed earlier."
},
{
"code": null,
"e": 4131,
"s": 3793,
"text": "To test its functioning, disconnect your computer from the network and run the script with python app.py. You’ll see a message that the first attempt failed, and the next one will begin in the next 3 minutes. Within three minutes, connect your computer back to the internet. The already running script will now finish without any errors."
},
{
"code": null,
"e": 4351,
"s": 4131,
"text": "Retrying is only part of the ETL story. Another challenge for many workflow applications is to run them in scheduled intervals. Prefect’s scheduling API is straightforward for any Python programmer. Here’s how it works."
},
{
"code": null,
"e": 4509,
"s": 4351,
"text": "We’ve created an IntervalSchedule object that starts five seconds from the execution of the script. We’ve also configured it to run in a one-minute interval."
},
{
"code": null,
"e": 4630,
"s": 4509,
"text": "If you run the script with python app.py and monitor the windspeed.txt file, you will see new values in it every minute."
},
{
"code": null,
"e": 4950,
"s": 4630,
"text": "In addition to this simple scheduling, Prefect’s schedule API offers more control over it. You can schedule workflows in a cron-like method, use clock time with timezones, or do more fun stuff like executing workflow only on weekends. I haven’t covered them all here, but Prefect's official docs about this are perfect."
},
{
"code": null,
"e": 5100,
"s": 4950,
"text": "Like Airflow (and many others,) Prefect too ships with a server with a beautiful UI. It allows you to control and visualize your workflow executions."
},
{
"code": null,
"e": 5234,
"s": 5100,
"text": "To run this, you need to have docker and docker-compose installed on your computer. But starting it is surprisingly a single command."
},
{
"code": null,
"e": 5257,
"s": 5234,
"text": "$ prefect server start"
},
{
"code": null,
"e": 5373,
"s": 5257,
"text": "This command will start the prefect server, and you can access it through your web browser: http://localhost:8080/."
},
{
"code": null,
"e": 5668,
"s": 5373,
"text": "However, the Prefect server alone could not execute your workflows. Its role is only enabling a control pannel to all your Prefect activities. Because this dashboard is decoupled from the rest of the application, you can use the Prefect cloud to do the same. We’ll discuss this in detail later."
},
{
"code": null,
"e": 5762,
"s": 5668,
"text": "To execute tasks, we need a few more things. The good news is, they, too, aren’t complicated."
},
{
"code": null,
"e": 5994,
"s": 5762,
"text": "Because servers are only a control panel, we need an agent to execute the workflow. The below command will start a local agent. Instead of a local agent, you can choose a docker agent or a Kubernetes one if your project needs them."
},
{
"code": null,
"e": 6022,
"s": 5994,
"text": "$ prefect agent local start"
},
{
"code": null,
"e": 6212,
"s": 6022,
"text": "Once the server and the agent are running, you’ll have to create a project and register your workflow with that project. To do this, change the line that executes the flow to the following."
},
{
"code": null,
"e": 6407,
"s": 6212,
"text": "Now in the terminal, you can create a project with the prefect create project <project name> command. Then rerunning the script will register it to the project instead of running it immediately."
},
{
"code": null,
"e": 6458,
"s": 6407,
"text": "$ prefect create project 'Tutorial'$ python app.py"
},
{
"code": null,
"e": 6676,
"s": 6458,
"text": "In the web UI, you can see the new Project ‘Tutorial’ is in the dropdown, and our windspeed tracker is in the list of flows. The flow is already scheduled and running. If you prefer, you can run them manually as well."
},
{
"code": null,
"e": 6898,
"s": 6676,
"text": "The workflow we created in the previous exercise is rigid. It queries only for Boston, MA, and we can not change it. This is where we can use parameters. Here’s how we tweak our code to accept a parameter at the run time."
},
{
"code": null,
"e": 7105,
"s": 6898,
"text": "We’ve changed the function to accept the city argument and set it dynamically in the API query. Inside the Flow, we create a parameter object with the default value ‘Boston’ and pass it to the Extract task."
},
{
"code": null,
"e": 7262,
"s": 7105,
"text": "If you run the windspeed tracker workflow manually in the UI, you’ll see a section called input. Here you can set the value of the city for every execution."
},
{
"code": null,
"e": 7379,
"s": 7262,
"text": "This is a convenient way to run workflows. In many cases, ETLs and any other workflow come with run-time parameters."
},
{
"code": null,
"e": 7592,
"s": 7379,
"text": "Airflow is a fantastic platform for workflow management. It saved me a ton of time on many projects. Yet, we need to appreciate new technologies taking over the old ones. That’s the case with Airflow and Prefect."
},
{
"code": null,
"e": 7723,
"s": 7592,
"text": "Airflow got many things right, but its core assumptions never anticipated the rich variety of data applications that have emerged."
},
{
"code": null,
"e": 7748,
"s": 7723,
"text": "— Prefect Documentation."
},
{
"code": null,
"e": 7928,
"s": 7748,
"text": "What I describe here aren’t dead-ends if you’re preferring Airflow. We have workarounds for most problems. Yet, it’s convenient in Prefect because the tool natively supports them."
},
{
"code": null,
"e": 8137,
"s": 7928,
"text": "Prefect’s installation is exceptionally straightforward compared to Airflow. For trained eyes, it may not be a problem. Yet, for whoever wants to start on workflow orchestration and automation, it’s a hassle."
},
{
"code": null,
"e": 8510,
"s": 8137,
"text": "Airflow needs a server running in the backend to perform any task. Yet, in Prefect, a server is optional. This is a massive benefit of using Prefect. I have many pet projects running on my computer as services. Earlier, I had to have an Airflow server commencing at the startup. Because Prefect could run standalone, I don’t have to turn on this additional server anymore."
},
{
"code": null,
"e": 8801,
"s": 8510,
"text": "Airflow doesn’t have the flexibility to run workflows (or DAGs) with parameters. The workaround I use to have is to let the application read them from a database. This isn’t an excellent programming technique for such a simple task. Prefect’s parameter concept is exceptional on this front."
},
{
"code": null,
"e": 9054,
"s": 8801,
"text": "Prefect allows having different versions of the same workflow. Every time you register a workflow to the project, it creates a new version. If you need to run a previous version, you can easily select it in a dropdown. This isn’t possible with Airflow."
},
{
"code": null,
"e": 9278,
"s": 9054,
"text": "Prefect also allows us to create teams and role-based access controls. Each team could manage its configuration. Authorization is a critical part of every modern application, and Prefect handles it in the best way possible."
},
{
"code": null,
"e": 9433,
"s": 9278,
"text": "Lastly, I find Prefect’s UI more intuitive and appealing. Airflow’s UI, especially its task execution visualization, was difficult at first to understand."
},
{
"code": null,
"e": 9567,
"s": 9433,
"text": "Prefect has inbuilt integration with many other technologies. It eliminates a ton of overhead and makes working with them super easy."
},
{
"code": null,
"e": 9734,
"s": 9567,
"text": "Live projects often have to deal with several technologies. For example, when your ETL fails, you may want to send an email or a Slack notification to the maintainer."
},
{
"code": null,
"e": 9894,
"s": 9734,
"text": "In Prefect, sending such notifications is effortless. You can use the EmailTask from the Prefect’s task library, set the credentials, and start sending emails."
},
{
"code": null,
"e": 10037,
"s": 9894,
"text": "You can learn more about Prefect’s rich ecosystem in their official documentation. In this article, we’ll see how to send email notifications."
},
{
"code": null,
"e": 10192,
"s": 10037,
"text": "To send emails, we need to make the credentials accessible to the Prefect agent. You can do that by creating the below file in $HOME/.prefect/config.toml."
},
{
"code": null,
"e": 10315,
"s": 10192,
"text": "Your app is now ready to send emails. Here’s how we send a notification when we successfully captured a windspeed measure."
},
{
"code": null,
"e": 10533,
"s": 10315,
"text": "In the above code, we’ve created an instance of the EmailTask class. We’ve used all the static elements of our email configurations during initiating. Then inside the Flow, we’ve used it with passing variable content."
},
{
"code": null,
"e": 10681,
"s": 10533,
"text": "This configuration above will send an email with the captured windspeed measurement. But its subject will always remain ‘A new windspeed captured.’"
},
{
"code": null,
"e": 10891,
"s": 10681,
"text": "We’ve already looked into how we can start an on-premise server. Because this server is only a control panel, you could easily use the cloud version instead. To do this, we have few additional steps to follow."
},
{
"code": null,
"e": 11156,
"s": 10891,
"text": "Create a Prefect cloud account.Generate a key from the API Key Page.In your terminal, set the backend to cloud: prefect backend cloud.Also login with the generated key: prefect auth login --key YOUR_API_KEY.Now, start the agent as usual. prefect agent local start."
},
{
"code": null,
"e": 11188,
"s": 11156,
"text": "Create a Prefect cloud account."
},
{
"code": null,
"e": 11226,
"s": 11188,
"text": "Generate a key from the API Key Page."
},
{
"code": null,
"e": 11293,
"s": 11226,
"text": "In your terminal, set the backend to cloud: prefect backend cloud."
},
{
"code": null,
"e": 11367,
"s": 11293,
"text": "Also login with the generated key: prefect auth login --key YOUR_API_KEY."
},
{
"code": null,
"e": 11425,
"s": 11367,
"text": "Now, start the agent as usual. prefect agent local start."
},
{
"code": null,
"e": 11511,
"s": 11425,
"text": "In the cloud dashboard, you can manage everything you did on the local server before."
},
{
"code": null,
"e": 11821,
"s": 11511,
"text": "A big question when choosing between cloud and server versions is security. According to Prefect‘s docs, the server only stores workflow execution-related data and voluntary information provided by the user. Since the agent in your local computer executes the logic, you can control where you store your data."
},
{
"code": null,
"e": 11981,
"s": 11821,
"text": "The cloud option is suitable for performance reasons too. With one cloud server, you can manage more than one agent. Thus, you can scale your app effortlessly."
},
{
"code": null,
"e": 12162,
"s": 11981,
"text": "Airflow was my ultimate choice for building ETLs and other workflow management applications. Yet, Prefect changed my mind, and now I’m migrating everything from Airflow to Prefect."
},
{
"code": null,
"e": 12360,
"s": 12162,
"text": "Prefect is a straightforward tool that is flexible to extend beyond what Airflow can do. You can run it even inside a Jupyter notebook. Also, you can host it as a complete task management solution."
},
{
"code": null,
"e": 12586,
"s": 12360,
"text": "In addition to the central problem of workflow management, Prefect solves several other issues you may frequently encounter in a live system. Managing teams with authorization controls, sending notifications are some of them."
},
{
"code": null,
"e": 12645,
"s": 12586,
"text": "In this article, we’ve discussed how to create an ETL that"
},
{
"code": null,
"e": 12679,
"s": 12645,
"text": "retries some tasks as configured;"
},
{
"code": null,
"e": 12708,
"s": 12679,
"text": "run workflows in a schedule;"
},
{
"code": null,
"e": 12742,
"s": 12708,
"text": "accepts run-time parameters, and;"
},
{
"code": null,
"e": 12786,
"s": 12742,
"text": "sends an email notification when it’s done."
},
{
"code": null,
"e": 12914,
"s": 12786,
"text": "We’ve only scratched the surface of Prefects capabilities. I recommend reading the official documentation for more information."
},
{
"code": null,
"e": 13056,
"s": 12914,
"text": "Thanks for reading, friend! It seems you, and I have lots of common interests. I’d love to connect with you on LinkedIn, Twitter, and Medium."
}
] |
MySQL query to get all characters before a specific character hyphen | For this, you can use SUBSTRING_INDEX(). Let us first create a table −
mysql> create table DemoTable1857
(
Name varchar(20)
);
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1857 values('John-Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1857 values('Brown-Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1857 values('David-Carol-Miller');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1857;
This will produce the following output −
+--------------------+
| Name |
+--------------------+
| John-Smith |
| Brown-Chris |
| David-Carol-Miller |
+--------------------+
3 rows in set (0.00 sec)
Here is the query to get all characters before specific character hyphen −
mysql> select substring_index(Name,'-',1) Name from DemoTable1857;
This will produce the following output −
+-------+
| Name |
+-------+
| John |
| Brown |
| David |
+-------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1133,
"s": 1062,
"text": "For this, you can use SUBSTRING_INDEX(). Let us first create a table −"
},
{
"code": null,
"e": 1241,
"s": 1133,
"text": "mysql> create table DemoTable1857\n (\n Name varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1297,
"s": 1241,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1579,
"s": 1297,
"text": "mysql> insert into DemoTable1857 values('John-Smith');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1857 values('Brown-Chris');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1857 values('David-Carol-Miller');\nQuery OK, 1 row affected (0.00 sec)"
},
{
"code": null,
"e": 1639,
"s": 1579,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1675,
"s": 1639,
"text": "mysql> select * from DemoTable1857;"
},
{
"code": null,
"e": 1716,
"s": 1675,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1902,
"s": 1716,
"text": "+--------------------+\n| Name |\n+--------------------+\n| John-Smith |\n| Brown-Chris |\n| David-Carol-Miller |\n+--------------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1977,
"s": 1902,
"text": "Here is the query to get all characters before specific character hyphen −"
},
{
"code": null,
"e": 2044,
"s": 1977,
"text": "mysql> select substring_index(Name,'-',1) Name from DemoTable1857;"
},
{
"code": null,
"e": 2085,
"s": 2044,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2180,
"s": 2085,
"text": "+-------+\n| Name |\n+-------+\n| John |\n| Brown |\n| David |\n+-------+\n3 rows in set (0.00 sec)"
}
] |
Java | Collectors averagingDouble() with Examples - GeeksforGeeks | 06 Dec, 2018
Collectors averagingDouble(ToDoubleFunction<? super T> mapper) method is used to find the mean of the double values passed in the parameters. This method returns a Collector that produces the arithmetic mean of an double-valued function applied to the input elements. If no elements are passed as the input elements, then this method returns 0.
The formula used by this method to calculate arithmetic mean is:
Syntax:
public static <T>
Collector<T, ?, Double>
averagingDouble(ToDoubleFunction<? super T> mapper)
where the terms are as follows:
Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation.
T: The type of input elements to the reduction operation.
A: The mutable accumulation type of the reduction operation.
R: The result type of the reduction operation.
Double: The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.
ToDoubleFunction: Represents a function that produces a double-valued result.
Parameters: This method accepts a parameter mapper which is double-valued stream converted into Double using ToDoubleFunctions. ToDoubleFunction is a function which extracts a double type of value as it works on the objects of the stream.
Below are examples to illustrate averagingDouble() method:
Program 1:
// Java code to show the implementation of// averagingDouble(ToDoubleFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a string stream Stream<String> s = Stream.of("3", "4", "5"); // using Collectors averagingDouble(ToDoubleFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingDouble( num -> Double.parseDouble(num))); // displaying the result System.out.println(ans); }}
4.0
Program 2:
// Java code to show the implementation of// averagingDouble(ToDoubleFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a string stream Stream<String> s = Stream.of("7", "8", "9", "10"); // using Collectors averagingDouble(ToDoubleFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingDouble( num -> Double.parseDouble(num))); // displaying the result System.out.println(ans); }}
8.5
Program 3: When no value is passed as parameter.
// Java code to show the implementation of// averagingDouble(ToDoubleFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a string stream Stream<String> s = Stream.of(); // using Collectors averagingDouble(ToDoubleFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingDouble( num -> Double.parseDouble(num))); // displaying the result System.out.println(ans); }}
0.0
Java - util package
Java-Collectors
Java-Functions
java-stream
Java-Stream-Collectors
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
Overriding in Java
Multidimensional Arrays in Java
LinkedList in Java
ArrayList in Java
PriorityQueue in Java
How to iterate any Map in Java
Queue Interface In Java
Stack Class in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 24055,
"s": 24027,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 24400,
"s": 24055,
"text": "Collectors averagingDouble(ToDoubleFunction<? super T> mapper) method is used to find the mean of the double values passed in the parameters. This method returns a Collector that produces the arithmetic mean of an double-valued function applied to the input elements. If no elements are passed as the input elements, then this method returns 0."
},
{
"code": null,
"e": 24465,
"s": 24400,
"text": "The formula used by this method to calculate arithmetic mean is:"
},
{
"code": null,
"e": 24473,
"s": 24465,
"text": "Syntax:"
},
{
"code": null,
"e": 24582,
"s": 24473,
"text": "public static <T> \n Collector<T, ?, Double> \n averagingDouble(ToDoubleFunction<? super T> mapper)\n"
},
{
"code": null,
"e": 24614,
"s": 24582,
"text": "where the terms are as follows:"
},
{
"code": null,
"e": 25097,
"s": 24614,
"text": "Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation."
},
{
"code": null,
"e": 25155,
"s": 25097,
"text": "T: The type of input elements to the reduction operation."
},
{
"code": null,
"e": 25216,
"s": 25155,
"text": "A: The mutable accumulation type of the reduction operation."
},
{
"code": null,
"e": 25263,
"s": 25216,
"text": "R: The result type of the reduction operation."
},
{
"code": null,
"e": 25416,
"s": 25263,
"text": "Double: The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double."
},
{
"code": null,
"e": 25494,
"s": 25416,
"text": "ToDoubleFunction: Represents a function that produces a double-valued result."
},
{
"code": null,
"e": 25733,
"s": 25494,
"text": "Parameters: This method accepts a parameter mapper which is double-valued stream converted into Double using ToDoubleFunctions. ToDoubleFunction is a function which extracts a double type of value as it works on the objects of the stream."
},
{
"code": null,
"e": 25792,
"s": 25733,
"text": "Below are examples to illustrate averagingDouble() method:"
},
{
"code": null,
"e": 25803,
"s": 25792,
"text": "Program 1:"
},
{
"code": "// Java code to show the implementation of// averagingDouble(ToDoubleFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a string stream Stream<String> s = Stream.of(\"3\", \"4\", \"5\"); // using Collectors averagingDouble(ToDoubleFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingDouble( num -> Double.parseDouble(num))); // displaying the result System.out.println(ans); }}",
"e": 26530,
"s": 25803,
"text": null
},
{
"code": null,
"e": 26535,
"s": 26530,
"text": "4.0\n"
},
{
"code": null,
"e": 26546,
"s": 26535,
"text": "Program 2:"
},
{
"code": "// Java code to show the implementation of// averagingDouble(ToDoubleFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a string stream Stream<String> s = Stream.of(\"7\", \"8\", \"9\", \"10\"); // using Collectors averagingDouble(ToDoubleFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingDouble( num -> Double.parseDouble(num))); // displaying the result System.out.println(ans); }}",
"e": 27279,
"s": 26546,
"text": null
},
{
"code": null,
"e": 27284,
"s": 27279,
"text": "8.5\n"
},
{
"code": null,
"e": 27333,
"s": 27284,
"text": "Program 3: When no value is passed as parameter."
},
{
"code": "// Java code to show the implementation of// averagingDouble(ToDoubleFunction mapper) function import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a string stream Stream<String> s = Stream.of(); // using Collectors averagingDouble(ToDoubleFunction mapper) // method to find arithmetic mean of inputs given double ans = s .collect(Collectors .averagingDouble( num -> Double.parseDouble(num))); // displaying the result System.out.println(ans); }}",
"e": 28047,
"s": 27333,
"text": null
},
{
"code": null,
"e": 28052,
"s": 28047,
"text": "0.0\n"
},
{
"code": null,
"e": 28072,
"s": 28052,
"text": "Java - util package"
},
{
"code": null,
"e": 28088,
"s": 28072,
"text": "Java-Collectors"
},
{
"code": null,
"e": 28103,
"s": 28088,
"text": "Java-Functions"
},
{
"code": null,
"e": 28115,
"s": 28103,
"text": "java-stream"
},
{
"code": null,
"e": 28138,
"s": 28115,
"text": "Java-Stream-Collectors"
},
{
"code": null,
"e": 28143,
"s": 28138,
"text": "Java"
},
{
"code": null,
"e": 28148,
"s": 28143,
"text": "Java"
},
{
"code": null,
"e": 28246,
"s": 28148,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28255,
"s": 28246,
"text": "Comments"
},
{
"code": null,
"e": 28268,
"s": 28255,
"text": "Old Comments"
},
{
"code": null,
"e": 28300,
"s": 28268,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28319,
"s": 28300,
"text": "Overriding in Java"
},
{
"code": null,
"e": 28351,
"s": 28319,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28370,
"s": 28351,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 28388,
"s": 28370,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28410,
"s": 28388,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 28441,
"s": 28410,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28465,
"s": 28441,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 28485,
"s": 28465,
"text": "Stack Class in Java"
}
] |
Find the Nth term of the series 1, 3, 7, 15, 31 . . . - GeeksforGeeks | 20 Jan, 2022
Given a positive integer N, the task is to find Nth term of the series:
1, 3, 7, 15, 31, .....
Examples:
Input: N = 5Output: 31
Input: N = 1Output: 1
Approach:
The sequence is formed by using the following pattern. For any value N-
TN = 2N – 1
Illustration:
Input: N = 5Output: 31Explanation:TN = 2N – 1 = 25 – 1 = 32 – 1 = 31
Below is the implementation of the above approach:
C++
Java
Python
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to return// Nth term of the seriesint findTerm(int N){ return pow(2, N) - 1;} // Driver Codeint main(){ int N = 5; cout << findTerm(N); return 0;}
// Java program to implement// the above approachimport java.util.*; public class GFG{ // Function to return // Nth term of the series static int findTerm(int N) { return (int)Math.pow(2, N) - 1; } // Driver Code public static void main(String args[]) { int N = 5; System.out.println(findTerm(N)); }} // This code is contributed by Samim Hossain Mondal.
# Python program to implement# the above approach # Function to return# Nth term of the seriesdef findTerm(N): return pow(2, N) - 1 # Driver CodeN = 5print(findTerm(N)) # This code is contributed by samim2000.
// C# program to implement// the above approachusing System; class GFG{ // Function to return // Nth term of the series static int findTerm(int N) { return (int)Math.Pow(2, N) - 1; } // Driver Code public static void Main() { int N = 5; Console.Write(findTerm(N)); }} // This code is contributed by Samim Hossain Mondal.
<script>// Javascript program to implement// the above approach // Function to return// Nth term of the seriesfunction findTerm(N){ return Math.pow(2, N) - 1;} // Driver Codelet N = 5;document.write(findTerm(N)); // This code is contributed by saurabh_jaiswal.</script>
31
Time Complexity: O(1)
Auxiliary Space: O(1)
samim2000
lokeshpotta20
_saurabh_jaiswal
Algo-Geek 2021
series
Algo Geek
Mathematical
Pattern Searching
Mathematical
series
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of operation required to water all the plants
Sort strings on the basis of their numeric part
Encode given String by inserting in Matrix column-wise and printing it row-wise
Check if the given string is valid English word or not
Lexicographically smallest string formed by concatenating any prefix and its mirrored form
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26375,
"s": 26347,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 26447,
"s": 26375,
"text": "Given a positive integer N, the task is to find Nth term of the series:"
},
{
"code": null,
"e": 26470,
"s": 26447,
"text": "1, 3, 7, 15, 31, ....."
},
{
"code": null,
"e": 26480,
"s": 26470,
"text": "Examples:"
},
{
"code": null,
"e": 26503,
"s": 26480,
"text": "Input: N = 5Output: 31"
},
{
"code": null,
"e": 26525,
"s": 26503,
"text": "Input: N = 1Output: 1"
},
{
"code": null,
"e": 26535,
"s": 26525,
"text": "Approach:"
},
{
"code": null,
"e": 26607,
"s": 26535,
"text": "The sequence is formed by using the following pattern. For any value N-"
},
{
"code": null,
"e": 26619,
"s": 26607,
"text": "TN = 2N – 1"
},
{
"code": null,
"e": 26633,
"s": 26619,
"text": "Illustration:"
},
{
"code": null,
"e": 26715,
"s": 26633,
"text": "Input: N = 5Output: 31Explanation:TN = 2N – 1 = 25 – 1 = 32 – 1 = 31"
},
{
"code": null,
"e": 26766,
"s": 26715,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26770,
"s": 26766,
"text": "C++"
},
{
"code": null,
"e": 26775,
"s": 26770,
"text": "Java"
},
{
"code": null,
"e": 26782,
"s": 26775,
"text": "Python"
},
{
"code": null,
"e": 26785,
"s": 26782,
"text": "C#"
},
{
"code": null,
"e": 26796,
"s": 26785,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to return// Nth term of the seriesint findTerm(int N){ return pow(2, N) - 1;} // Driver Codeint main(){ int N = 5; cout << findTerm(N); return 0;}",
"e": 27060,
"s": 26796,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; public class GFG{ // Function to return // Nth term of the series static int findTerm(int N) { return (int)Math.pow(2, N) - 1; } // Driver Code public static void main(String args[]) { int N = 5; System.out.println(findTerm(N)); }} // This code is contributed by Samim Hossain Mondal.",
"e": 27435,
"s": 27060,
"text": null
},
{
"code": "# Python program to implement# the above approach # Function to return# Nth term of the seriesdef findTerm(N): return pow(2, N) - 1 # Driver CodeN = 5print(findTerm(N)) # This code is contributed by samim2000.",
"e": 27653,
"s": 27435,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to return // Nth term of the series static int findTerm(int N) { return (int)Math.Pow(2, N) - 1; } // Driver Code public static void Main() { int N = 5; Console.Write(findTerm(N)); }} // This code is contributed by Samim Hossain Mondal.",
"e": 27995,
"s": 27653,
"text": null
},
{
"code": "<script>// Javascript program to implement// the above approach // Function to return// Nth term of the seriesfunction findTerm(N){ return Math.pow(2, N) - 1;} // Driver Codelet N = 5;document.write(findTerm(N)); // This code is contributed by saurabh_jaiswal.</script>",
"e": 28268,
"s": 27995,
"text": null
},
{
"code": null,
"e": 28274,
"s": 28271,
"text": "31"
},
{
"code": null,
"e": 28298,
"s": 28276,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 28322,
"s": 28300,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28334,
"s": 28324,
"text": "samim2000"
},
{
"code": null,
"e": 28348,
"s": 28334,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 28365,
"s": 28348,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 28380,
"s": 28365,
"text": "Algo-Geek 2021"
},
{
"code": null,
"e": 28387,
"s": 28380,
"text": "series"
},
{
"code": null,
"e": 28397,
"s": 28387,
"text": "Algo Geek"
},
{
"code": null,
"e": 28410,
"s": 28397,
"text": "Mathematical"
},
{
"code": null,
"e": 28428,
"s": 28410,
"text": "Pattern Searching"
},
{
"code": null,
"e": 28441,
"s": 28428,
"text": "Mathematical"
},
{
"code": null,
"e": 28448,
"s": 28441,
"text": "series"
},
{
"code": null,
"e": 28466,
"s": 28448,
"text": "Pattern Searching"
},
{
"code": null,
"e": 28564,
"s": 28466,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28616,
"s": 28564,
"text": "Count of operation required to water all the plants"
},
{
"code": null,
"e": 28664,
"s": 28616,
"text": "Sort strings on the basis of their numeric part"
},
{
"code": null,
"e": 28744,
"s": 28664,
"text": "Encode given String by inserting in Matrix column-wise and printing it row-wise"
},
{
"code": null,
"e": 28799,
"s": 28744,
"text": "Check if the given string is valid English word or not"
},
{
"code": null,
"e": 28890,
"s": 28799,
"text": "Lexicographically smallest string formed by concatenating any prefix and its mirrored form"
},
{
"code": null,
"e": 28920,
"s": 28890,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 28980,
"s": 28920,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 28995,
"s": 28980,
"text": "C++ Data Types"
},
{
"code": null,
"e": 29038,
"s": 28995,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Clear TextField in Flutter - GeeksforGeeks | 23 Sep, 2020
TextField and TextFormField are the two most common widgets to get input from the user. They can be used in making forms, login pages, etc. In order to make their implementation effective and accurate, we need to add certain functionalities. In this article, we’ll learn how to clear TextField on certain actions.
There can be certain scenarios in your app, where you might need clear Text Fields. Suppose, you are creating a form and after submitting you are redirected to a new page, if you go back now then the entered text would still be there and this is not a sign of a good UI. So, in this scenario, you would be required to clear the TextField after submitting.
Using a button to clear TextField :
Step 1: Create a new project and launch main.dart file. Clear the existing code.
Step 2: Import material.dart file
import 'package:flutter/material.dart';
Step 3: Create the main method which would call runApp() method and pass the name of your class to this method.
void main() => runApp(MyApp());
Step 4: Create the root class MyApp() that extends the Stateless Widget and add TextField widget as a child.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('GeeksforGeeks'),
backgroundColor: Colors.green,
),
body: Center(
child: TextField()
)
)
);
}
}
Step 5 : Create a final variable of type TextEditingController(). This variable is used to access various properties and methods of TextField.
final fieldText = TextEditingController();
Step 6 : Create a function clearText(). You can name it accordingly. Inside this function add fieldText.clear();
As mentioned above there are various properties of TextEditingController(). One of them is clear(), and we will use it to clear the TextField.
void clearText() {
fieldText.clear();
}
Step 7: Create a button and link that to clearText() method that we created in the above step. Now, whenever you would press this button TextField would be cleared.
Code :
Dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { final fieldText = TextEditingController(); void clearText() { fieldText.clear(); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: 250, child: TextField( decoration: InputDecoration( hintText: 'Enter Something', focusColor: Colors.green, ), controller: fieldText, ), ), SizedBox(height: 15,), RaisedButton( onPressed: clearText, color: Colors.green, child: Text('Clear'), textColor: Colors.white, ), ], ), ), ), ); }}
The above code creates a TextField with a RaisedButton. Whenever you enter something in the TextField and press the button, TextField would be cleared. Below is the output of the above implementation.
Output :
It is really necessary to add this functionality because if you are pushing a new screen above a screen that contains a form and then if you go back to the form then the values would still be there.
Clearing TextField using clear icon
Also, if you want to add a clear icon in the text field itself, then we would see it also.
Below is the image of the above-mentioned scenario:
Almost all steps, in this case, would be similar to the above-mentioned steps, the only difference would be to add the clear icon instead of the Raised Button.
TextField(
decoration: InputDecoration(
hintText: 'Enter Something',
focusColor: Colors.green,
suffixIcon: IconButton( // Icon to
icon: Icon(Icons.clear), // clear text
onPressed: clearText,
),
),
controller: fieldText,
),
In the above-mentioned code, there is a TextField and suffixIcon is added to it as a decoration. The clearText method is the same as used in the above code.
Complete Code :
Dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { final fieldText = TextEditingController(); void clearText() { fieldText.clear(); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: Container( width: 250, child: TextField( decoration: InputDecoration( hintText: 'Enter Something', focusColor: Colors.green, suffixIcon: IconButton( icon: Icon(Icons.clear), onPressed: clearText, ), ), controller: fieldText, ), ), ), ), ); }}
Output :
Articles
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Time Complexity and Space Complexity
Mutex vs Semaphore
Analysis of Algorithms | Set 3 (Asymptotic Notations)
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
Listview.builder in Flutter
Flutter - DropDownButton Widget
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Custom Bottom Navigation Bar | [
{
"code": null,
"e": 24686,
"s": 24658,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 25000,
"s": 24686,
"text": "TextField and TextFormField are the two most common widgets to get input from the user. They can be used in making forms, login pages, etc. In order to make their implementation effective and accurate, we need to add certain functionalities. In this article, we’ll learn how to clear TextField on certain actions."
},
{
"code": null,
"e": 25357,
"s": 25000,
"text": "There can be certain scenarios in your app, where you might need clear Text Fields. Suppose, you are creating a form and after submitting you are redirected to a new page, if you go back now then the entered text would still be there and this is not a sign of a good UI. So, in this scenario, you would be required to clear the TextField after submitting. "
},
{
"code": null,
"e": 25393,
"s": 25357,
"text": "Using a button to clear TextField :"
},
{
"code": null,
"e": 25474,
"s": 25393,
"text": "Step 1: Create a new project and launch main.dart file. Clear the existing code."
},
{
"code": null,
"e": 25508,
"s": 25474,
"text": "Step 2: Import material.dart file"
},
{
"code": null,
"e": 25548,
"s": 25508,
"text": "import 'package:flutter/material.dart';"
},
{
"code": null,
"e": 25660,
"s": 25548,
"text": "Step 3: Create the main method which would call runApp() method and pass the name of your class to this method."
},
{
"code": null,
"e": 25692,
"s": 25660,
"text": "void main() => runApp(MyApp());"
},
{
"code": null,
"e": 25801,
"s": 25692,
"text": "Step 4: Create the root class MyApp() that extends the Stateless Widget and add TextField widget as a child."
},
{
"code": null,
"e": 26139,
"s": 25801,
"text": "class MyApp extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n home: Scaffold(\n appBar: AppBar(\n title: Text('GeeksforGeeks'),\n backgroundColor: Colors.green,\n ),\n body: Center(\n child: TextField()\n )\n )\n );\n }\n} \n"
},
{
"code": null,
"e": 26282,
"s": 26139,
"text": "Step 5 : Create a final variable of type TextEditingController(). This variable is used to access various properties and methods of TextField."
},
{
"code": null,
"e": 26326,
"s": 26282,
"text": " final fieldText = TextEditingController();"
},
{
"code": null,
"e": 26440,
"s": 26326,
"text": "Step 6 : Create a function clearText(). You can name it accordingly. Inside this function add fieldText.clear(); "
},
{
"code": null,
"e": 26583,
"s": 26440,
"text": "As mentioned above there are various properties of TextEditingController(). One of them is clear(), and we will use it to clear the TextField."
},
{
"code": null,
"e": 26630,
"s": 26583,
"text": "void clearText() {\n fieldText.clear();\n }\n"
},
{
"code": null,
"e": 26795,
"s": 26630,
"text": "Step 7: Create a button and link that to clearText() method that we created in the above step. Now, whenever you would press this button TextField would be cleared."
},
{
"code": null,
"e": 26802,
"s": 26795,
"text": "Code :"
},
{
"code": null,
"e": 26807,
"s": 26802,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { final fieldText = TextEditingController(); void clearText() { fieldText.clear(); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: 250, child: TextField( decoration: InputDecoration( hintText: 'Enter Something', focusColor: Colors.green, ), controller: fieldText, ), ), SizedBox(height: 15,), RaisedButton( onPressed: clearText, color: Colors.green, child: Text('Clear'), textColor: Colors.white, ), ], ), ), ), ); }}",
"e": 27937,
"s": 26807,
"text": null
},
{
"code": null,
"e": 28138,
"s": 27937,
"text": "The above code creates a TextField with a RaisedButton. Whenever you enter something in the TextField and press the button, TextField would be cleared. Below is the output of the above implementation."
},
{
"code": null,
"e": 28147,
"s": 28138,
"text": "Output :"
},
{
"code": null,
"e": 28346,
"s": 28147,
"text": "It is really necessary to add this functionality because if you are pushing a new screen above a screen that contains a form and then if you go back to the form then the values would still be there."
},
{
"code": null,
"e": 28382,
"s": 28346,
"text": "Clearing TextField using clear icon"
},
{
"code": null,
"e": 28473,
"s": 28382,
"text": "Also, if you want to add a clear icon in the text field itself, then we would see it also."
},
{
"code": null,
"e": 28525,
"s": 28473,
"text": "Below is the image of the above-mentioned scenario:"
},
{
"code": null,
"e": 28685,
"s": 28525,
"text": "Almost all steps, in this case, would be similar to the above-mentioned steps, the only difference would be to add the clear icon instead of the Raised Button."
},
{
"code": null,
"e": 28962,
"s": 28685,
"text": "TextField(\n decoration: InputDecoration(\n hintText: 'Enter Something',\n focusColor: Colors.green,\n suffixIcon: IconButton( // Icon to \n icon: Icon(Icons.clear), // clear text\n onPressed: clearText,\n ),\n ),\n controller: fieldText,\n),\n"
},
{
"code": null,
"e": 29119,
"s": 28962,
"text": "In the above-mentioned code, there is a TextField and suffixIcon is added to it as a decoration. The clearText method is the same as used in the above code."
},
{
"code": null,
"e": 29135,
"s": 29119,
"text": "Complete Code :"
},
{
"code": null,
"e": 29140,
"s": 29135,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { final fieldText = TextEditingController(); void clearText() { fieldText.clear(); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: Container( width: 250, child: TextField( decoration: InputDecoration( hintText: 'Enter Something', focusColor: Colors.green, suffixIcon: IconButton( icon: Icon(Icons.clear), onPressed: clearText, ), ), controller: fieldText, ), ), ), ), ); }}",
"e": 30021,
"s": 29140,
"text": null
},
{
"code": null,
"e": 30030,
"s": 30021,
"text": "Output :"
},
{
"code": null,
"e": 30039,
"s": 30030,
"text": "Articles"
},
{
"code": null,
"e": 30044,
"s": 30039,
"text": "Dart"
},
{
"code": null,
"e": 30052,
"s": 30044,
"text": "Flutter"
},
{
"code": null,
"e": 30150,
"s": 30052,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30159,
"s": 30150,
"text": "Comments"
},
{
"code": null,
"e": 30172,
"s": 30159,
"text": "Old Comments"
},
{
"code": null,
"e": 30225,
"s": 30172,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
},
{
"code": null,
"e": 30262,
"s": 30225,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 30281,
"s": 30262,
"text": "Mutex vs Semaphore"
},
{
"code": null,
"e": 30335,
"s": 30281,
"text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)"
},
{
"code": null,
"e": 30398,
"s": 30335,
"text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)"
},
{
"code": null,
"e": 30426,
"s": 30398,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 30458,
"s": 30426,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 30480,
"s": 30458,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 30505,
"s": 30480,
"text": "Splash Screen in Flutter"
}
] |
Sweetviz: Automated EDA in Python | by Himanshu Sharma | Towards Data Science | Exploratory Data Analysis is a process where we tend to analyze the dataset and summarize the main characteristics of the dataset often using visual methods. EDA is really important because if you are not familiar with the dataset you are working on, then you won’t be able to infer something from that data. However, EDA generally takes a lot of time.
But, what if I told you that python can automate the process of EDA with the help of some libraries? Won’t it make your work easier? So let’s start learning about Automated EDA.
In this article, we will work on Automating EDA using Sweetviz. It is a python library that generates beautiful, high-density visualizations to start your EDA. Let us explore Sweetviz in detail.
Like any other python library, we can install Sweetviz by using the pip install command given below.
pip install sweetviz
In this article, I have used an advertising dataset contains 4 attributes and 200 rows. First, we need to load the using pandas.
import pandas as pddf = pd.read_csv('Advertising.csv')
Sweetviz has a function named Analyze() which analyzes the whole dataset and provides a detailed report with visualization.
Let’s Analyze our dataset using the command given below.
# importing sweetvizimport sweetviz as sv#analyzing the datasetadvert_report = sv.analyze(df)#display the reportadvert_report.show_html('Advertising.html')
And here we go, as you can see above our EDA report is ready and contains a lot of information for all the attributes. It’s easy to understand and is prepared in just 3 lines of code.
Other than this Sweetviz can also be used to visualize the comparison of test and train data. For comparison let us divide this data into 2 parts, first 100 rows for train dataset and rest 100 rows for the test dataset.
Compare() function of Sweetviz is used for comparison of the dataset. The commands given below will create and compare our test and train dataset.
df1 = sv.compare(df[100:], df[:100])df1.show_html('Compare.html')
Other than this there are many more functions that Sweetviz provides for that you can go through this.
So what do you think about this beautiful library? Go ahead try this and mention your experiences in the response section.
There are some other libraries that automate the EDA process one of which is Pandas Profiling which I have explained earlier in an article given below.
towardsdatascience.com
towardsdatascience.com
Thanks for reading! If you want to get in touch with me, feel free to reach me on [email protected] or my LinkedIn Profile. You can also view the code and data I have used here in my Github. | [
{
"code": null,
"e": 524,
"s": 171,
"text": "Exploratory Data Analysis is a process where we tend to analyze the dataset and summarize the main characteristics of the dataset often using visual methods. EDA is really important because if you are not familiar with the dataset you are working on, then you won’t be able to infer something from that data. However, EDA generally takes a lot of time."
},
{
"code": null,
"e": 702,
"s": 524,
"text": "But, what if I told you that python can automate the process of EDA with the help of some libraries? Won’t it make your work easier? So let’s start learning about Automated EDA."
},
{
"code": null,
"e": 897,
"s": 702,
"text": "In this article, we will work on Automating EDA using Sweetviz. It is a python library that generates beautiful, high-density visualizations to start your EDA. Let us explore Sweetviz in detail."
},
{
"code": null,
"e": 998,
"s": 897,
"text": "Like any other python library, we can install Sweetviz by using the pip install command given below."
},
{
"code": null,
"e": 1019,
"s": 998,
"text": "pip install sweetviz"
},
{
"code": null,
"e": 1148,
"s": 1019,
"text": "In this article, I have used an advertising dataset contains 4 attributes and 200 rows. First, we need to load the using pandas."
},
{
"code": null,
"e": 1204,
"s": 1148,
"text": "import pandas as pddf = pd.read_csv('Advertising.csv')"
},
{
"code": null,
"e": 1328,
"s": 1204,
"text": "Sweetviz has a function named Analyze() which analyzes the whole dataset and provides a detailed report with visualization."
},
{
"code": null,
"e": 1385,
"s": 1328,
"text": "Let’s Analyze our dataset using the command given below."
},
{
"code": null,
"e": 1541,
"s": 1385,
"text": "# importing sweetvizimport sweetviz as sv#analyzing the datasetadvert_report = sv.analyze(df)#display the reportadvert_report.show_html('Advertising.html')"
},
{
"code": null,
"e": 1725,
"s": 1541,
"text": "And here we go, as you can see above our EDA report is ready and contains a lot of information for all the attributes. It’s easy to understand and is prepared in just 3 lines of code."
},
{
"code": null,
"e": 1945,
"s": 1725,
"text": "Other than this Sweetviz can also be used to visualize the comparison of test and train data. For comparison let us divide this data into 2 parts, first 100 rows for train dataset and rest 100 rows for the test dataset."
},
{
"code": null,
"e": 2092,
"s": 1945,
"text": "Compare() function of Sweetviz is used for comparison of the dataset. The commands given below will create and compare our test and train dataset."
},
{
"code": null,
"e": 2158,
"s": 2092,
"text": "df1 = sv.compare(df[100:], df[:100])df1.show_html('Compare.html')"
},
{
"code": null,
"e": 2261,
"s": 2158,
"text": "Other than this there are many more functions that Sweetviz provides for that you can go through this."
},
{
"code": null,
"e": 2384,
"s": 2261,
"text": "So what do you think about this beautiful library? Go ahead try this and mention your experiences in the response section."
},
{
"code": null,
"e": 2536,
"s": 2384,
"text": "There are some other libraries that automate the EDA process one of which is Pandas Profiling which I have explained earlier in an article given below."
},
{
"code": null,
"e": 2559,
"s": 2536,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2582,
"s": 2559,
"text": "towardsdatascience.com"
}
] |
Unsupervised Learning: Dimensionality Reduction | by Victor Roman | Towards Data Science | As stated in previous articles, unsupervised learning refers to a kind of machine learning algorithms and techniques that are trained and fed with unlabeled data. In other words, we do not know the correct solutions or the values of the target variable beforehand.
The main goal of these types of algorithms is to study the intrinsic and hidden structure of the data in order to get meaningful insights, segment the datasets in similar groups or to simplify them.
Throughout this article, we are going to explore some of the algorithms and techniques most commonly used to reduce the dimensionality of datasets.
Basics of Dimensionality Reduction
Dimensionality is the number of variables, characteristics or features present in the dataset. This dimensions are represented as columns, and the goal is to reduce the number of them.
In most cases, those columns are correlated and, therefore, there is some information that is redundant which increase the dataset’s noise. This redundant information impacts negatively in Machine Learning model’s training and performance and that is why using dimensionality reduction methods becomes of paramount importance. It is a very useful way to reduce model’s complexity and avoid overfitting.
There are two main categories of dimensionality reduction:
Feature Selection → we select a subset of features of the original dataset.
Feature Extraction → we derive information from the orginal set to build a new feature subspace.
Feature Selection stands for a family of greedy algorithms used to reduce the dimensional feature space of a given dataset. The aim is to obtain a model capable of automatically selecting the subset of features most relevant to problem faced.
Greedy algorithms make locally optimal choices at each stage of a combinational search and normally yield suboptimal solutions. This is where they differenciate to exhaustive search algorithms, which evaluate the whole set of combinations and yield the overall optimal solution. The benefits of greedy algorithms is that they are computationally much more efficient, in expenses of precision, but, most of the times they yield sufficiently good solutions.
In that way, we will improve the computation efficiency of the training process, reduce dataset’s noise, avoid overfitting and reduce model’s complexity.
We will study two of the main techniques of feature selection:
Sequential Backward Selection or SBS
Random Forests Feature Importance
The idea behind the SBS algorithm is the following:
We will set the final number of features d that we want in our dataset
Then, we will set a criterion function that will be in charge of minimizing the loss of performance caused by removing one of the dataset’s features.
At each iteration, the algorithm will calculate this reduction of performance, by simply calculating the performance, before and after the removal of each of the current features.
Then, the feature that results in the least performance reduction, will be removed from the dataset.
If the number of features present in the dataset is equal to the d number (set at the beginning) the algorithms stops. Otherwise, it will complete another iteration.
We have studied Random Forests algorithms in a previous article. These are a kind of ensemble algorithms that combine a set of weak Decision Tree models in order to build a more robust and precise one.
Using Random Forest, we can assess the importance of each feature, how much they are contributing to the model’s information, by calculating the averaged impurity decrease computed from all decision trees present in the forest. This will be done without making any assumptions of whether the data is linearly separable or not.
This is a quite simple method of obtaining feature importance, as we are going to use the random forest implementation of the scikit-learn library, which already collects feature importance by using the feature_importance_ attribute after fitting a RandomForesClassifier.
We already have studied an example of this in a previous article where we wanted to identify those features that most strongly help to predict wheter a specific individual made at most or more than $50.000.
# Import Ada Boost Classifierfrom sklearn.ensemble import AdaBoostClassifier# Train the supervised model on the training model = AdaBoostClassifier().fit(X_train, y_train)# Extract the feature importances using .feature_importances_ importances = model.feature_importances_# Plotvs.feature_plot(importances, X_train, y_train)
Feature extraction is also used to reduce the number of features of a certain dataset, but in contrast to feature selection, the output features will not be the same as the originals.
When using feature extraction, we project the data into a new feature space, so the new features will be combinations of the original features, compressed in a way that they will retain the most relevant information.
Some of the most used algorithms for unsupervised feature extraction are:
Principal Component Analysis
Random Projection
Independant Component Analysis
In order to understand how the PCA algorithm works, let’s consider the following distribution of data:
PCA finds a new quadrant system (y’ and x’ axis) that it is obtained from the old one by translation and rotation only.
It will move the centre of the coordinate system from the original point (0,0) to the centre of the distribution of datapoints.
It will then move the x-axis into the principal axis of variation, which is the one with most variation relative to data points (the direction of maximum spread).
Then it moves other axis orthogonally to the principal one, into less important directions of variation.
Basically, PCA finds the directions of maximum variance in high-dimensional data and projects this data into a new subspace with the same or fewer dimensions than the original one.
These new directions that contain the maximum variance are called Principal Components, they have the constraint of being orthogonall to each other.
Maximal Variance and Information Loss
Data points will be projected in the direction of maximal variance to form a new axis. The further the points are to the axis, the biggest the information loss.
It is a mathematical fact that when we project points onto a direction of maximal variance, it minimized the distance from old and higher-dimensional data points to its new transformed value. In other words, it minimizes the information loss.
Core ideas of PCA for Feature Transformation
As a summary, what PCA do is to combine every feature and to extract the top more relevant ones automatically. It is a systemized way to transform input features into principal components, and uses them as the new features.
Principal components are directions in data that maximize variance (minimize information loss) when projecting or compressing them down.
The more the variance of data along a Principal Component, the more information that direction contains and the higher that principal component is ranked.
The number of Principal Components will be less or equall the number of input features.
Scikit-Learn PCA Implementation
Let’s see an example of how this algorithm is implemented in the Scikit-Learn library.
# Import PCA Algorithmfrom sklearn.decomposition import PCA# Initialize the algorithm and set the number of PC'spca = PCA(n_components=2)# Fit the model to data pca.fit(data)# Get list of PC'spca.components_# Transform the model to data pca.transform(data)# Get the eigenvaluespca.explained_variance_ratio
When To Use PCA
When having latent features driving the patterns in data.
For Dimensionality reduction.
To visualize high-dimensional data.
To reduce the noise.
As a preprocessing step to improve the performance of other algorithms.
Random projection is a powerful dimensionality reduction method that is computationally more efficient tha PCA. It is commonly used in datasets that have too many dimensionsfor PCA to be directly computed.
Like PCA, it takes a dataset with d dimensions and n samples and produces a transformation of the dataset with k dimensions, being k much smaller than d (k << d).
Method
The basic premise is to reduce the number of dimension of our dataset by multiplying it to a random matrix. Which will project the dataset into a new subspace of features.
Theoreticall Approach: Johnson — Lindenstrauss Lemma
A datset with N samples in high-dimensional Euclidean space can be mapped down to a space in much lower dimension in a way that preserves the distance to the points to a large degree.
In other words, the distance squared between two points in the dataset is calculated and the distance of those two points in the new dataset must be either:
Smaller than the squared distance multiplied by (1-ε)
Greater than the squared distance multiplied by (1+ε)
Being u and v the considered datapoints.
Random Projection Scikit-learn implementation
# Import Random Projection Algorithmfrom sklearn.random_projection import SparseRandomProjection# Initialize the algorithm and set the number of PC'srandprojection = SparseRandomProjection()# Fit and transformthe model to data randprojection.fit_transform(data)
The epsilon value ε, is the level of error we are allowing between the points of the dataset. The default value of epsilon is 0.1.
We can use random projection by either setting a number of components or by specifying a value for epsilon and having the algorithm automatically calculating a conservative value for the number of dimensions.
ICA is a method for dimensionality reduction similar to PCA or Random Projection in the sense that it takes a set of features and produces a different set that is useful in some way.
But while PCA tries to maximize variance, ICA assumes that the features are mixtures of independent sources and it tries to isolate these independent sources that are mixed in the dataset.
The motivation behind ICA would be to take the original set of features and try to identify those of them that contribute independently to the dataset, in other words, those with the leat correlation to the other features. So it will isolate those most important components. This problem is called Blind Source Isolation.
High Level Algorithm
X: Is our original Dataset.
A: Mixing matrix
S: Source matrix
W: Unmixing matrix
These variables are related as follows:
So the goal is to calculate W, to be able to obtain S, the source matrix of the independant features.
To do so, the algorithm will perform the following steps:
Having X as the dataset, it will center and whiten it.Choose an initial random weight matrix W1,W2,...,Wn.Estimate W, containing vectors.Decorrelate W.Repeat from step 3 until convergence
Having X as the dataset, it will center and whiten it.
Choose an initial random weight matrix W1,W2,...,Wn.
Estimate W, containing vectors.
Decorrelate W.
Repeat from step 3 until convergence
ICA assumes that the components are statistical independent. They must have non Gaussian distributions, as we would not be able to restore the original signals if they were Gaussian.
From this point, the central limit theorem says that the distribution of a sum of independent variables tends towards a Gaussian distribution.
ICA Implementation in Sci-kit learn
# Import Independent Component Analysis Algorithmfrom sklearn.decomposition import FastICA# Initialize the algorithm and set the number of PC'sica = FastICA(n_components=2)# Fit and transform the model to data. It returns a list of independent components ica.fit_transform(data)
One interesting applicaiton of ICA is the analysis of Electroenphalographic data. The following is an example of the readings of 14 channels from an EEG scan that lasted 4.5 seconds and the independent components extracted from the dataset.
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": 437,
"s": 172,
"text": "As stated in previous articles, unsupervised learning refers to a kind of machine learning algorithms and techniques that are trained and fed with unlabeled data. In other words, we do not know the correct solutions or the values of the target variable beforehand."
},
{
"code": null,
"e": 636,
"s": 437,
"text": "The main goal of these types of algorithms is to study the intrinsic and hidden structure of the data in order to get meaningful insights, segment the datasets in similar groups or to simplify them."
},
{
"code": null,
"e": 784,
"s": 636,
"text": "Throughout this article, we are going to explore some of the algorithms and techniques most commonly used to reduce the dimensionality of datasets."
},
{
"code": null,
"e": 819,
"s": 784,
"text": "Basics of Dimensionality Reduction"
},
{
"code": null,
"e": 1004,
"s": 819,
"text": "Dimensionality is the number of variables, characteristics or features present in the dataset. This dimensions are represented as columns, and the goal is to reduce the number of them."
},
{
"code": null,
"e": 1407,
"s": 1004,
"text": "In most cases, those columns are correlated and, therefore, there is some information that is redundant which increase the dataset’s noise. This redundant information impacts negatively in Machine Learning model’s training and performance and that is why using dimensionality reduction methods becomes of paramount importance. It is a very useful way to reduce model’s complexity and avoid overfitting."
},
{
"code": null,
"e": 1466,
"s": 1407,
"text": "There are two main categories of dimensionality reduction:"
},
{
"code": null,
"e": 1542,
"s": 1466,
"text": "Feature Selection → we select a subset of features of the original dataset."
},
{
"code": null,
"e": 1639,
"s": 1542,
"text": "Feature Extraction → we derive information from the orginal set to build a new feature subspace."
},
{
"code": null,
"e": 1882,
"s": 1639,
"text": "Feature Selection stands for a family of greedy algorithms used to reduce the dimensional feature space of a given dataset. The aim is to obtain a model capable of automatically selecting the subset of features most relevant to problem faced."
},
{
"code": null,
"e": 2338,
"s": 1882,
"text": "Greedy algorithms make locally optimal choices at each stage of a combinational search and normally yield suboptimal solutions. This is where they differenciate to exhaustive search algorithms, which evaluate the whole set of combinations and yield the overall optimal solution. The benefits of greedy algorithms is that they are computationally much more efficient, in expenses of precision, but, most of the times they yield sufficiently good solutions."
},
{
"code": null,
"e": 2492,
"s": 2338,
"text": "In that way, we will improve the computation efficiency of the training process, reduce dataset’s noise, avoid overfitting and reduce model’s complexity."
},
{
"code": null,
"e": 2555,
"s": 2492,
"text": "We will study two of the main techniques of feature selection:"
},
{
"code": null,
"e": 2592,
"s": 2555,
"text": "Sequential Backward Selection or SBS"
},
{
"code": null,
"e": 2626,
"s": 2592,
"text": "Random Forests Feature Importance"
},
{
"code": null,
"e": 2678,
"s": 2626,
"text": "The idea behind the SBS algorithm is the following:"
},
{
"code": null,
"e": 2749,
"s": 2678,
"text": "We will set the final number of features d that we want in our dataset"
},
{
"code": null,
"e": 2899,
"s": 2749,
"text": "Then, we will set a criterion function that will be in charge of minimizing the loss of performance caused by removing one of the dataset’s features."
},
{
"code": null,
"e": 3079,
"s": 2899,
"text": "At each iteration, the algorithm will calculate this reduction of performance, by simply calculating the performance, before and after the removal of each of the current features."
},
{
"code": null,
"e": 3180,
"s": 3079,
"text": "Then, the feature that results in the least performance reduction, will be removed from the dataset."
},
{
"code": null,
"e": 3346,
"s": 3180,
"text": "If the number of features present in the dataset is equal to the d number (set at the beginning) the algorithms stops. Otherwise, it will complete another iteration."
},
{
"code": null,
"e": 3548,
"s": 3346,
"text": "We have studied Random Forests algorithms in a previous article. These are a kind of ensemble algorithms that combine a set of weak Decision Tree models in order to build a more robust and precise one."
},
{
"code": null,
"e": 3875,
"s": 3548,
"text": "Using Random Forest, we can assess the importance of each feature, how much they are contributing to the model’s information, by calculating the averaged impurity decrease computed from all decision trees present in the forest. This will be done without making any assumptions of whether the data is linearly separable or not."
},
{
"code": null,
"e": 4147,
"s": 3875,
"text": "This is a quite simple method of obtaining feature importance, as we are going to use the random forest implementation of the scikit-learn library, which already collects feature importance by using the feature_importance_ attribute after fitting a RandomForesClassifier."
},
{
"code": null,
"e": 4354,
"s": 4147,
"text": "We already have studied an example of this in a previous article where we wanted to identify those features that most strongly help to predict wheter a specific individual made at most or more than $50.000."
},
{
"code": null,
"e": 4680,
"s": 4354,
"text": "# Import Ada Boost Classifierfrom sklearn.ensemble import AdaBoostClassifier# Train the supervised model on the training model = AdaBoostClassifier().fit(X_train, y_train)# Extract the feature importances using .feature_importances_ importances = model.feature_importances_# Plotvs.feature_plot(importances, X_train, y_train)"
},
{
"code": null,
"e": 4864,
"s": 4680,
"text": "Feature extraction is also used to reduce the number of features of a certain dataset, but in contrast to feature selection, the output features will not be the same as the originals."
},
{
"code": null,
"e": 5081,
"s": 4864,
"text": "When using feature extraction, we project the data into a new feature space, so the new features will be combinations of the original features, compressed in a way that they will retain the most relevant information."
},
{
"code": null,
"e": 5155,
"s": 5081,
"text": "Some of the most used algorithms for unsupervised feature extraction are:"
},
{
"code": null,
"e": 5184,
"s": 5155,
"text": "Principal Component Analysis"
},
{
"code": null,
"e": 5202,
"s": 5184,
"text": "Random Projection"
},
{
"code": null,
"e": 5233,
"s": 5202,
"text": "Independant Component Analysis"
},
{
"code": null,
"e": 5336,
"s": 5233,
"text": "In order to understand how the PCA algorithm works, let’s consider the following distribution of data:"
},
{
"code": null,
"e": 5456,
"s": 5336,
"text": "PCA finds a new quadrant system (y’ and x’ axis) that it is obtained from the old one by translation and rotation only."
},
{
"code": null,
"e": 5584,
"s": 5456,
"text": "It will move the centre of the coordinate system from the original point (0,0) to the centre of the distribution of datapoints."
},
{
"code": null,
"e": 5747,
"s": 5584,
"text": "It will then move the x-axis into the principal axis of variation, which is the one with most variation relative to data points (the direction of maximum spread)."
},
{
"code": null,
"e": 5852,
"s": 5747,
"text": "Then it moves other axis orthogonally to the principal one, into less important directions of variation."
},
{
"code": null,
"e": 6033,
"s": 5852,
"text": "Basically, PCA finds the directions of maximum variance in high-dimensional data and projects this data into a new subspace with the same or fewer dimensions than the original one."
},
{
"code": null,
"e": 6182,
"s": 6033,
"text": "These new directions that contain the maximum variance are called Principal Components, they have the constraint of being orthogonall to each other."
},
{
"code": null,
"e": 6220,
"s": 6182,
"text": "Maximal Variance and Information Loss"
},
{
"code": null,
"e": 6381,
"s": 6220,
"text": "Data points will be projected in the direction of maximal variance to form a new axis. The further the points are to the axis, the biggest the information loss."
},
{
"code": null,
"e": 6624,
"s": 6381,
"text": "It is a mathematical fact that when we project points onto a direction of maximal variance, it minimized the distance from old and higher-dimensional data points to its new transformed value. In other words, it minimizes the information loss."
},
{
"code": null,
"e": 6669,
"s": 6624,
"text": "Core ideas of PCA for Feature Transformation"
},
{
"code": null,
"e": 6893,
"s": 6669,
"text": "As a summary, what PCA do is to combine every feature and to extract the top more relevant ones automatically. It is a systemized way to transform input features into principal components, and uses them as the new features."
},
{
"code": null,
"e": 7030,
"s": 6893,
"text": "Principal components are directions in data that maximize variance (minimize information loss) when projecting or compressing them down."
},
{
"code": null,
"e": 7185,
"s": 7030,
"text": "The more the variance of data along a Principal Component, the more information that direction contains and the higher that principal component is ranked."
},
{
"code": null,
"e": 7273,
"s": 7185,
"text": "The number of Principal Components will be less or equall the number of input features."
},
{
"code": null,
"e": 7305,
"s": 7273,
"text": "Scikit-Learn PCA Implementation"
},
{
"code": null,
"e": 7392,
"s": 7305,
"text": "Let’s see an example of how this algorithm is implemented in the Scikit-Learn library."
},
{
"code": null,
"e": 7698,
"s": 7392,
"text": "# Import PCA Algorithmfrom sklearn.decomposition import PCA# Initialize the algorithm and set the number of PC'spca = PCA(n_components=2)# Fit the model to data pca.fit(data)# Get list of PC'spca.components_# Transform the model to data pca.transform(data)# Get the eigenvaluespca.explained_variance_ratio"
},
{
"code": null,
"e": 7714,
"s": 7698,
"text": "When To Use PCA"
},
{
"code": null,
"e": 7772,
"s": 7714,
"text": "When having latent features driving the patterns in data."
},
{
"code": null,
"e": 7802,
"s": 7772,
"text": "For Dimensionality reduction."
},
{
"code": null,
"e": 7838,
"s": 7802,
"text": "To visualize high-dimensional data."
},
{
"code": null,
"e": 7859,
"s": 7838,
"text": "To reduce the noise."
},
{
"code": null,
"e": 7931,
"s": 7859,
"text": "As a preprocessing step to improve the performance of other algorithms."
},
{
"code": null,
"e": 8137,
"s": 7931,
"text": "Random projection is a powerful dimensionality reduction method that is computationally more efficient tha PCA. It is commonly used in datasets that have too many dimensionsfor PCA to be directly computed."
},
{
"code": null,
"e": 8300,
"s": 8137,
"text": "Like PCA, it takes a dataset with d dimensions and n samples and produces a transformation of the dataset with k dimensions, being k much smaller than d (k << d)."
},
{
"code": null,
"e": 8307,
"s": 8300,
"text": "Method"
},
{
"code": null,
"e": 8479,
"s": 8307,
"text": "The basic premise is to reduce the number of dimension of our dataset by multiplying it to a random matrix. Which will project the dataset into a new subspace of features."
},
{
"code": null,
"e": 8532,
"s": 8479,
"text": "Theoreticall Approach: Johnson — Lindenstrauss Lemma"
},
{
"code": null,
"e": 8716,
"s": 8532,
"text": "A datset with N samples in high-dimensional Euclidean space can be mapped down to a space in much lower dimension in a way that preserves the distance to the points to a large degree."
},
{
"code": null,
"e": 8873,
"s": 8716,
"text": "In other words, the distance squared between two points in the dataset is calculated and the distance of those two points in the new dataset must be either:"
},
{
"code": null,
"e": 8927,
"s": 8873,
"text": "Smaller than the squared distance multiplied by (1-ε)"
},
{
"code": null,
"e": 8981,
"s": 8927,
"text": "Greater than the squared distance multiplied by (1+ε)"
},
{
"code": null,
"e": 9022,
"s": 8981,
"text": "Being u and v the considered datapoints."
},
{
"code": null,
"e": 9068,
"s": 9022,
"text": "Random Projection Scikit-learn implementation"
},
{
"code": null,
"e": 9330,
"s": 9068,
"text": "# Import Random Projection Algorithmfrom sklearn.random_projection import SparseRandomProjection# Initialize the algorithm and set the number of PC'srandprojection = SparseRandomProjection()# Fit and transformthe model to data randprojection.fit_transform(data)"
},
{
"code": null,
"e": 9461,
"s": 9330,
"text": "The epsilon value ε, is the level of error we are allowing between the points of the dataset. The default value of epsilon is 0.1."
},
{
"code": null,
"e": 9670,
"s": 9461,
"text": "We can use random projection by either setting a number of components or by specifying a value for epsilon and having the algorithm automatically calculating a conservative value for the number of dimensions."
},
{
"code": null,
"e": 9853,
"s": 9670,
"text": "ICA is a method for dimensionality reduction similar to PCA or Random Projection in the sense that it takes a set of features and produces a different set that is useful in some way."
},
{
"code": null,
"e": 10042,
"s": 9853,
"text": "But while PCA tries to maximize variance, ICA assumes that the features are mixtures of independent sources and it tries to isolate these independent sources that are mixed in the dataset."
},
{
"code": null,
"e": 10364,
"s": 10042,
"text": "The motivation behind ICA would be to take the original set of features and try to identify those of them that contribute independently to the dataset, in other words, those with the leat correlation to the other features. So it will isolate those most important components. This problem is called Blind Source Isolation."
},
{
"code": null,
"e": 10385,
"s": 10364,
"text": "High Level Algorithm"
},
{
"code": null,
"e": 10413,
"s": 10385,
"text": "X: Is our original Dataset."
},
{
"code": null,
"e": 10430,
"s": 10413,
"text": "A: Mixing matrix"
},
{
"code": null,
"e": 10447,
"s": 10430,
"text": "S: Source matrix"
},
{
"code": null,
"e": 10466,
"s": 10447,
"text": "W: Unmixing matrix"
},
{
"code": null,
"e": 10506,
"s": 10466,
"text": "These variables are related as follows:"
},
{
"code": null,
"e": 10608,
"s": 10506,
"text": "So the goal is to calculate W, to be able to obtain S, the source matrix of the independant features."
},
{
"code": null,
"e": 10666,
"s": 10608,
"text": "To do so, the algorithm will perform the following steps:"
},
{
"code": null,
"e": 10854,
"s": 10666,
"text": "Having X as the dataset, it will center and whiten it.Choose an initial random weight matrix W1,W2,...,Wn.Estimate W, containing vectors.Decorrelate W.Repeat from step 3 until convergence"
},
{
"code": null,
"e": 10909,
"s": 10854,
"text": "Having X as the dataset, it will center and whiten it."
},
{
"code": null,
"e": 10962,
"s": 10909,
"text": "Choose an initial random weight matrix W1,W2,...,Wn."
},
{
"code": null,
"e": 10994,
"s": 10962,
"text": "Estimate W, containing vectors."
},
{
"code": null,
"e": 11009,
"s": 10994,
"text": "Decorrelate W."
},
{
"code": null,
"e": 11046,
"s": 11009,
"text": "Repeat from step 3 until convergence"
},
{
"code": null,
"e": 11229,
"s": 11046,
"text": "ICA assumes that the components are statistical independent. They must have non Gaussian distributions, as we would not be able to restore the original signals if they were Gaussian."
},
{
"code": null,
"e": 11372,
"s": 11229,
"text": "From this point, the central limit theorem says that the distribution of a sum of independent variables tends towards a Gaussian distribution."
},
{
"code": null,
"e": 11408,
"s": 11372,
"text": "ICA Implementation in Sci-kit learn"
},
{
"code": null,
"e": 11687,
"s": 11408,
"text": "# Import Independent Component Analysis Algorithmfrom sklearn.decomposition import FastICA# Initialize the algorithm and set the number of PC'sica = FastICA(n_components=2)# Fit and transform the model to data. It returns a list of independent components ica.fit_transform(data)"
},
{
"code": null,
"e": 11928,
"s": 11687,
"text": "One interesting applicaiton of ICA is the analysis of Electroenphalographic data. The following is an example of the readings of 14 channels from an EEG scan that lasted 4.5 seconds and the independent components extracted from the dataset."
},
{
"code": null,
"e": 12037,
"s": 11928,
"text": "If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here."
}
] |
How to delete multiple rows of NumPy array ? - GeeksforGeeks | 21 Apr, 2021
NumPy is the Python library that is used for working with arrays. In Python there are lists which serve the purpose of arrays but they are slow. Therefore, NumPy is there to provide us with the array object that is much faster than the traditional Python lists. The reason for them being faster is that they store arrays at one continuous place in memory, unlike lists which makes the process accessing and manipulation much more efficient.
There are a number of ways to delete multiple rows in NumPy array. They are give below :-
numpy.delete() – The numpy.delete() is a function in Python which returns a new array with the deletion of sub-arrays along with the mentioned axis. By keeping the value of the axis as zero, there are two possible ways to delete multiple rows using numphy.delete().
Using arrays of ints, Syntax: np.delete(x, [ 0, 2, 3], axis=0)
Python3
import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) print(geek.delete(x, [0, 1, 2], axis=0))
Output:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]
[30 31 32 33 34]]
Using slice objects – The slice() function allows us to specify how to slice a sequence.
Syntax of slice function: slice(start, stop, step index)
Python3
import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) print(geek.delete(x, slice(0, 3), axis=0))
Output:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]
[30 31 32 33 34]]
Basic Indexing – This is one of the easiest ways to delete multiple rows of NumPy array.Syntax for basic indexing: array object(start:stop:step)
Python3
import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) # Removing all rows before the 4th rowresult = x[4:]print(result)
Output:
[[20 21 22 23 24]
[25 26 27 28 29]
[30 31 32 33 34]]
Fancy Indexing – This is the method in which we index the arrays using arrays allowing us to access multiple array elements at once by referring to their index number.Syntax: array object[row numbers]
Python3
import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) # Fancy indexingprint(x[[0, 1, 2]])
Output:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
numpy.take() – The numpy.take() is a function in python which is used to return elements from arrays along the mentioned axis and indices. Now, if one mentions the value of axis as null/zero, then it is able to provide us with the desired indices and work in a way similar to Fancy Indexing.
Python3
import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) # applying numpy.take() functionprint(geek.take(x, [0, 2, 6], axis=0))
Output:
[[ 0 1 2 3 4]
[10 11 12 13 14]
[30 31 32 33 34]]
Boolean Indexing – This is a very convenient method, specially when we put some condition for the deletion.For example, we want to remove the rows that start with a value greater than 10. Then we can do it by using Boolean Indexing.
Python3
import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) # Performing Boolean Indexingmask_array = x[:, 0] < 10print(x[mask_array])
Output:
[[0 1 2 3 4]
[5 6 7 8 9]]
Picked
Pyhton numpy-arrayCreation
Python numpy-Basics
Python numpy-Indexing
Python numpy-ndarray
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 Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 24733,
"s": 24292,
"text": "NumPy is the Python library that is used for working with arrays. In Python there are lists which serve the purpose of arrays but they are slow. Therefore, NumPy is there to provide us with the array object that is much faster than the traditional Python lists. The reason for them being faster is that they store arrays at one continuous place in memory, unlike lists which makes the process accessing and manipulation much more efficient."
},
{
"code": null,
"e": 24823,
"s": 24733,
"text": "There are a number of ways to delete multiple rows in NumPy array. They are give below :-"
},
{
"code": null,
"e": 25090,
"s": 24823,
"text": "numpy.delete() – The numpy.delete() is a function in Python which returns a new array with the deletion of sub-arrays along with the mentioned axis. By keeping the value of the axis as zero, there are two possible ways to delete multiple rows using numphy.delete(). "
},
{
"code": null,
"e": 25153,
"s": 25090,
"text": "Using arrays of ints, Syntax: np.delete(x, [ 0, 2, 3], axis=0)"
},
{
"code": null,
"e": 25161,
"s": 25153,
"text": "Python3"
},
{
"code": "import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) print(geek.delete(x, [0, 1, 2], axis=0))",
"e": 25280,
"s": 25161,
"text": null
},
{
"code": null,
"e": 25288,
"s": 25280,
"text": "Output:"
},
{
"code": null,
"e": 25560,
"s": 25288,
"text": "[[15 16 17 18 19] \n[20 21 22 23 24] \n[25 26 27 28 29] \n[30 31 32 33 34]]"
},
{
"code": null,
"e": 25650,
"s": 25560,
"text": "Using slice objects – The slice() function allows us to specify how to slice a sequence. "
},
{
"code": null,
"e": 25707,
"s": 25650,
"text": "Syntax of slice function: slice(start, stop, step index)"
},
{
"code": null,
"e": 25715,
"s": 25707,
"text": "Python3"
},
{
"code": "import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) print(geek.delete(x, slice(0, 3), axis=0))",
"e": 25835,
"s": 25715,
"text": null
},
{
"code": null,
"e": 25844,
"s": 25835,
"text": "Output: "
},
{
"code": null,
"e": 26011,
"s": 25844,
"text": "[[15 16 17 18 19]\n [20 21 22 23 24]\n [25 26 27 28 29]\n [30 31 32 33 34]] "
},
{
"code": null,
"e": 26157,
"s": 26011,
"text": "Basic Indexing – This is one of the easiest ways to delete multiple rows of NumPy array.Syntax for basic indexing: array object(start:stop:step) "
},
{
"code": null,
"e": 26165,
"s": 26157,
"text": "Python3"
},
{
"code": "import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) # Removing all rows before the 4th rowresult = x[4:]print(result)",
"e": 26308,
"s": 26165,
"text": null
},
{
"code": null,
"e": 26316,
"s": 26308,
"text": "Output:"
},
{
"code": null,
"e": 26564,
"s": 26316,
"text": "[[20 21 22 23 24] \n[25 26 27 28 29] \n[30 31 32 33 34]] "
},
{
"code": null,
"e": 26766,
"s": 26564,
"text": "Fancy Indexing – This is the method in which we index the arrays using arrays allowing us to access multiple array elements at once by referring to their index number.Syntax: array object[row numbers] "
},
{
"code": null,
"e": 26774,
"s": 26766,
"text": "Python3"
},
{
"code": "import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) # Fancy indexingprint(x[[0, 1, 2]]) ",
"e": 26891,
"s": 26774,
"text": null
},
{
"code": null,
"e": 26899,
"s": 26891,
"text": "Output:"
},
{
"code": null,
"e": 27143,
"s": 26899,
"text": "[[ 0 1 2 3 4] \n[ 5 6 7 8 9] \n[10 11 12 13 14]]"
},
{
"code": null,
"e": 27435,
"s": 27143,
"text": "numpy.take() – The numpy.take() is a function in python which is used to return elements from arrays along the mentioned axis and indices. Now, if one mentions the value of axis as null/zero, then it is able to provide us with the desired indices and work in a way similar to Fancy Indexing."
},
{
"code": null,
"e": 27443,
"s": 27435,
"text": "Python3"
},
{
"code": "import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) # applying numpy.take() functionprint(geek.take(x, [0, 2, 6], axis=0)) ",
"e": 27594,
"s": 27443,
"text": null
},
{
"code": null,
"e": 27602,
"s": 27594,
"text": "Output:"
},
{
"code": null,
"e": 27848,
"s": 27602,
"text": "[[ 0 1 2 3 4] \n[10 11 12 13 14] \n[30 31 32 33 34]] "
},
{
"code": null,
"e": 28082,
"s": 27848,
"text": "Boolean Indexing – This is a very convenient method, specially when we put some condition for the deletion.For example, we want to remove the rows that start with a value greater than 10. Then we can do it by using Boolean Indexing. "
},
{
"code": null,
"e": 28090,
"s": 28082,
"text": "Python3"
},
{
"code": "import numpy as geek # Defining the arrayx = geek.arange(35).reshape(7, 5) # Performing Boolean Indexingmask_array = x[:, 0] < 10print(x[mask_array])",
"e": 28242,
"s": 28090,
"text": null
},
{
"code": null,
"e": 28250,
"s": 28242,
"text": "Output:"
},
{
"code": null,
"e": 28277,
"s": 28250,
"text": "[[0 1 2 3 4]\n [5 6 7 8 9]]"
},
{
"code": null,
"e": 28284,
"s": 28277,
"text": "Picked"
},
{
"code": null,
"e": 28311,
"s": 28284,
"text": "Pyhton numpy-arrayCreation"
},
{
"code": null,
"e": 28331,
"s": 28311,
"text": "Python numpy-Basics"
},
{
"code": null,
"e": 28353,
"s": 28331,
"text": "Python numpy-Indexing"
},
{
"code": null,
"e": 28374,
"s": 28353,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 28381,
"s": 28374,
"text": "Python"
},
{
"code": null,
"e": 28479,
"s": 28381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28511,
"s": 28479,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28553,
"s": 28511,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28609,
"s": 28553,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28651,
"s": 28609,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28706,
"s": 28651,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28737,
"s": 28706,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28759,
"s": 28737,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28788,
"s": 28759,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28827,
"s": 28788,
"text": "Python | Get unique values from a list"
}
] |
How to write a singleton class in C++? | Singleton design pattern is a software design principle that is used to restrict the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. For example, if you are using a logger, that writes logs to a file, you can use a singleton class to create such a logger. You can create a singleton class using the following code.
#include <iostream>
using namespace std;
class Singleton {
static Singleton *instance;
int data;
// Private constructor so that no objects can be created.
Singleton() {
data = 0;
}
public:
static Singleton *getInstance() {
if (!instance)
instance = new Singleton;
return instance;
}
int getData() {
return this -> data;
}
void setData(int data) {
this -> data = data;
}
};
//Initialize pointer to zero so that it can be initialized in first call to getInstance
Singleton *Singleton::instance = 0;
int main(){
Singleton *s = s->getInstance();
cout << s->getData() << endl;
s->setData(100);
cout << s->getData() << endl;
return 0;
}
0
100 | [
{
"code": null,
"e": 1459,
"s": 1062,
"text": "Singleton design pattern is a software design principle that is used to restrict the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. For example, if you are using a logger, that writes logs to a file, you can use a singleton class to create such a logger. You can create a singleton class using the following code."
},
{
"code": null,
"e": 2192,
"s": 1459,
"text": "#include <iostream>\nusing namespace std;\nclass Singleton {\n static Singleton *instance;\n int data;\n // Private constructor so that no objects can be created.\n Singleton() {\n data = 0;\n }\n public:\n static Singleton *getInstance() {\n if (!instance)\n instance = new Singleton;\n return instance;\n }\n int getData() {\n return this -> data;\n }\n void setData(int data) {\n this -> data = data;\n }\n};\n//Initialize pointer to zero so that it can be initialized in first call to getInstance\nSingleton *Singleton::instance = 0;\nint main(){\n Singleton *s = s->getInstance();\n cout << s->getData() << endl;\n s->setData(100);\n cout << s->getData() << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2198,
"s": 2192,
"text": "0\n100"
}
] |
Period between() method in Java | The Period between two dates can be obtained using the between() method in the Period class in Java. This method requires two parameters i.e. the start date and the end date and it returns the Period between these two dates.
A program that demonstrates this is given as follows
Live Demo
import java.time.Period;
import java.time.LocalDate;
public class Demo {
public static void main(String[] args) {
LocalDate startDate = LocalDate.parse("2015-03-15");
LocalDate endDate = LocalDate.parse("2019-05-20");
System.out.println("The start date is: " + startDate);
System.out.println("The end date is: " + endDate);
Period p = Period.between(startDate, endDate);
System.out.println("\nThe Period between the start and end date is : " + p);
}
}
The start date is: 2015-03-15
The end date is: 2019-05-20
The Period between the start and end date is : P4Y2M5D
Now let us understand the above program.
First the start date and end date is displayed. Then the Period between these two dates is obtained using the between() method and displayed. A code snippet that demonstrates this is as follows:
LocalDate startDate = LocalDate.parse("2015-03-15");
LocalDate endDate = LocalDate.parse("2019-05-20");
System.out.println("The start date is: " + startDate);
System.out.println("The end date is: " + endDate);
Period p = Period.between(startDate, endDate);
System.out.println("\nThe Period between the start and end date is : " + p); | [
{
"code": null,
"e": 1287,
"s": 1062,
"text": "The Period between two dates can be obtained using the between() method in the Period class in Java. This method requires two parameters i.e. the start date and the end date and it returns the Period between these two dates."
},
{
"code": null,
"e": 1340,
"s": 1287,
"text": "A program that demonstrates this is given as follows"
},
{
"code": null,
"e": 1351,
"s": 1340,
"text": " Live Demo"
},
{
"code": null,
"e": 1845,
"s": 1351,
"text": "import java.time.Period;\nimport java.time.LocalDate;\npublic class Demo {\n public static void main(String[] args) {\n LocalDate startDate = LocalDate.parse(\"2015-03-15\");\n LocalDate endDate = LocalDate.parse(\"2019-05-20\");\n System.out.println(\"The start date is: \" + startDate);\n System.out.println(\"The end date is: \" + endDate);\n Period p = Period.between(startDate, endDate);\n System.out.println(\"\\nThe Period between the start and end date is : \" + p);\n }\n}"
},
{
"code": null,
"e": 1958,
"s": 1845,
"text": "The start date is: 2015-03-15\nThe end date is: 2019-05-20\nThe Period between the start and end date is : P4Y2M5D"
},
{
"code": null,
"e": 1999,
"s": 1958,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2194,
"s": 1999,
"text": "First the start date and end date is displayed. Then the Period between these two dates is obtained using the between() method and displayed. A code snippet that demonstrates this is as follows:"
},
{
"code": null,
"e": 2528,
"s": 2194,
"text": "LocalDate startDate = LocalDate.parse(\"2015-03-15\");\nLocalDate endDate = LocalDate.parse(\"2019-05-20\");\nSystem.out.println(\"The start date is: \" + startDate);\nSystem.out.println(\"The end date is: \" + endDate);\nPeriod p = Period.between(startDate, endDate);\nSystem.out.println(\"\\nThe Period between the start and end date is : \" + p);"
}
] |
MySQL Tryit Editor v1.0 | SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 61,
"s": 0,
"text": "SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;"
},
{
"code": null,
"e": 63,
"s": 61,
"text": ""
},
{
"code": null,
"e": 135,
"s": 72,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 195,
"s": 135,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 263,
"s": 195,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 301,
"s": 263,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 386,
"s": 301,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 560,
"s": 386,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 611,
"s": 560,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 679,
"s": 611,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 850,
"s": 679,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 950,
"s": 850,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 1000,
"s": 950,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
Apache POI Word - Paragraph | In this chapter you will learn how to create a Paragraph and how to add it to a document using Java. Paragraph is a part of a page in a Word file.
After completing this chapter, you will be able to create a Paragraph and perform read operations on it.
First of all, let us create a Paragraph using the referenced classes discussed in the earlier chapters. By following the previous chapter, create a Document first, and then we can create a Paragraph.
The following code snippet is used to create a spreadsheet −
//Create Blank document
XWPFDocument document = new XWPFDocument();
//Create a blank spreadsheet
XWPFParagraph paragraph = document.createParagraph();
You can enter the text or any object element, using Run. Using Paragraph instance you can create run.
The following code snippet is used to create a Run.
XWPFRun run = paragraph.createRun();
Let us try entering some text into a document. Consider the below text data −
At tutorialspoint.com, we strive hard to provide quality tutorials for self-learning purpose
in the domains of Academics, Information Technology, Management and Computer Programming Languages.
The following code is used to write the above data into a paragraph.
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class CreateParagraph {
public static void main(String[] args)throws Exception {
//Blank Document
XWPFDocument document = new XWPFDocument();
//Write the Document in file system
FileOutputStream out = new FileOutputStream(new File("createparagraph.docx"));
//create Paragraph
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("At tutorialspoint.com, we strive hard to " +
"provide quality tutorials for self-learning " +
"purpose in the domains of Academics, Information " +
"Technology, Management and Computer Programming Languages.");
document.write(out);
out.close();
System.out.println("createparagraph.docx written successfully");
}
}
Save the above Java code as CreateParagraph.java, and then compile and run it from the command prompt as follows −
$javac CreateParagraph.java
$java CreateParagraph
It will compile and execute to generate a Word file named createparagraph.docx in your current directory and you will get the following output in the command prompt −
createparagraph.docx written successfully
The createparagraph.docx file looks as follows.
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2033,
"s": 1886,
"text": "In this chapter you will learn how to create a Paragraph and how to add it to a document using Java. Paragraph is a part of a page in a Word file."
},
{
"code": null,
"e": 2138,
"s": 2033,
"text": "After completing this chapter, you will be able to create a Paragraph and perform read operations on it."
},
{
"code": null,
"e": 2338,
"s": 2138,
"text": "First of all, let us create a Paragraph using the referenced classes discussed in the earlier chapters. By following the previous chapter, create a Document first, and then we can create a Paragraph."
},
{
"code": null,
"e": 2399,
"s": 2338,
"text": "The following code snippet is used to create a spreadsheet −"
},
{
"code": null,
"e": 2552,
"s": 2399,
"text": "//Create Blank document\nXWPFDocument document = new XWPFDocument();\n\n//Create a blank spreadsheet\nXWPFParagraph paragraph = document.createParagraph();\n"
},
{
"code": null,
"e": 2654,
"s": 2552,
"text": "You can enter the text or any object element, using Run. Using Paragraph instance you can create run."
},
{
"code": null,
"e": 2706,
"s": 2654,
"text": "The following code snippet is used to create a Run."
},
{
"code": null,
"e": 2744,
"s": 2706,
"text": "XWPFRun run = paragraph.createRun();\n"
},
{
"code": null,
"e": 2822,
"s": 2744,
"text": "Let us try entering some text into a document. Consider the below text data −"
},
{
"code": null,
"e": 3017,
"s": 2822,
"text": "At tutorialspoint.com, we strive hard to provide quality tutorials for self-learning purpose \nin the domains of Academics, Information Technology, Management and Computer Programming Languages.\n"
},
{
"code": null,
"e": 3086,
"s": 3017,
"text": "The following code is used to write the above data into a paragraph."
},
{
"code": null,
"e": 4111,
"s": 3086,
"text": "import java.io.File;\nimport java.io.FileOutputStream;\nimport org.apache.poi.xwpf.usermodel.XWPFDocument;\nimport org.apache.poi.xwpf.usermodel.XWPFParagraph;\nimport org.apache.poi.xwpf.usermodel.XWPFRun;\n\npublic class CreateParagraph {\n public static void main(String[] args)throws Exception {\n //Blank Document\n XWPFDocument document = new XWPFDocument(); \n \n //Write the Document in file system\n FileOutputStream out = new FileOutputStream(new File(\"createparagraph.docx\"));\n \n //create Paragraph\n XWPFParagraph paragraph = document.createParagraph();\n XWPFRun run = paragraph.createRun();\n run.setText(\"At tutorialspoint.com, we strive hard to \" +\n \"provide quality tutorials for self-learning \" +\n \"purpose in the domains of Academics, Information \" +\n \"Technology, Management and Computer Programming Languages.\");\n\t\t\t\n document.write(out);\n out.close();\n System.out.println(\"createparagraph.docx written successfully\");\n }\n}"
},
{
"code": null,
"e": 4226,
"s": 4111,
"text": "Save the above Java code as CreateParagraph.java, and then compile and run it from the command prompt as follows −"
},
{
"code": null,
"e": 4277,
"s": 4226,
"text": "$javac CreateParagraph.java\n$java CreateParagraph\n"
},
{
"code": null,
"e": 4444,
"s": 4277,
"text": "It will compile and execute to generate a Word file named createparagraph.docx in your current directory and you will get the following output in the command prompt −"
},
{
"code": null,
"e": 4487,
"s": 4444,
"text": "createparagraph.docx written successfully\n"
},
{
"code": null,
"e": 4535,
"s": 4487,
"text": "The createparagraph.docx file looks as follows."
},
{
"code": null,
"e": 4570,
"s": 4535,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4589,
"s": 4570,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4624,
"s": 4589,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4645,
"s": 4624,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 4678,
"s": 4645,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4691,
"s": 4678,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 4726,
"s": 4691,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4744,
"s": 4726,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4777,
"s": 4744,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4795,
"s": 4777,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4828,
"s": 4795,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4846,
"s": 4828,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4853,
"s": 4846,
"text": " Print"
},
{
"code": null,
"e": 4864,
"s": 4853,
"text": " Add Notes"
}
] |
Liar’s Dice by Self-Play. With Counterfactual Regret and Neural... | by Thomas Dybdahl Ahle | Towards Data Science | I’ve been meaning to learn about AIs for games like Poker or Liar’s Dice for a while. Recently while reading Deepmind’s article Player of Games, I thought I might be able to make something really simple that works well enough to be fun. “It shouldn’t take more than an afternoon,” I thought. Of course, I ended up spending much more time on it, but it did turn out to be fun and very simple.
The project allowed me to dive into the exciting concepts of Counterfactual Regret Minimization, Reinforcement Learning, serving PyTorch models in the browser and a few other fun topics, so there are a bunch of things to cover in this blog post.
I understand. It’s a game of deception. But your bet includes all the dice, not just your own. — Will Turner, Pirates of the Caribbean
Liar’s Dice is a game I personally liked to play back when we could still go to bars. It is simpler than Poker, but has many of the same concepts of betting, bluff and hidden information, making it a fun challenge for AI.
The game is also famous from Pirates of the Caribbean, but I will quickly sketch the rules if you don’t know the game.
Each player has a set of dice known only to them. Players take turns bidding on the minimum number of dice that the player believes are showing a given value.
Each turn, the player must bid a higher quantity of any particular face or the same quantity of a higher face. E.g. “2 ⚃” and “3 ⚂” are both valid bets after “3 ⚁”, but “2 ⚂” isn’t.
Alternatively, the player can challenge the previous bid. If the challenge is successful — e.g. the previous bid was a bluff — the challenger wins the round; otherwise, the player who made the bet wins.
Often ⚀’s are considered jokers and count for any face when summing up the dice in the end.
Example: Alice and Bob may have the hands ⚀ ⚁ and ⚂ ⚃. Alice bids “2 ⚁” (which she can support from her own hand alone), Bob says “2 ⚂” (anticipating that Alice has either a ⚂ or a ⚀ (joker)). Alice calls Bob, but Bob was right and wins.
It takes a bit of theory to explain the algorithm — even though it is ultimately very simple. If you want to jump straight to the neural network section or the evaluation of the model in terms of ELO rating and exploitability, feel free to skip the following three sections.
Why are imperfect-information games so hard? After all, we had Deep Blue, we had AlphaGo. Why can’t we take those techniques and apply them out of the box to a game like Poker? — Noam Brown NIPS2017 best paper talk.
Liar’s Dice is a finite game: There are only so many dice combinations you can roll, and so many sequences of bets that can be made. (We call the combination a state, technically it is often called an info-set) However, unlike games of perfect information like chess, there is no single perfect move (or action) we can compute for each state. Instead, as shown by John von Neumann and John Nash, we need a “Mixed Strategy”: For each state, we pick a move from a probability distribution over the set of actions.
Intuitively this is because having a fixed strategy gives away information about our private dice. If we always make a high bet when we roll a lousy roll, our opponent will learn this and start calling our bluff. If we only bluff half the time, and play safe the other half, it gets harder for our opponent to figure us out.
The Nash equilibrium can be computed using Linear Programming, e.g. the method of Daphne Koller and Nimrod Megiddo, which takes polynomial time in the number of states (or “information sets” as is the more common term.) I actually used precisely this method to solve Liar’s Dice years ago. This is possible because with 1 die each, the maximum bid that makes sense is 2 ⚅’s. That makes a total of 12 possible bids. Combined with the dice information, that’s 6*212 ~400,000 states. This is just within what’s possible with modern Linear Algebra solvers like Google or-tools.
Unfortunately, this method doesn’t scale to multiple dice. With 6 dice each, we get ~1026 states, which is comparable to the total legal positions in chess. And while chess could theoretically be solved by a simple depth-first search — taking constant space and linear time in the number of states — Liar’s Dice is much much harder. This is why AIs could play chess quite well in 1998, but only recently got to the same level in Poker.
Okay, time I actually start explaining how this AI actually works, and how machine learning comes into play.
In the past, a lot of people would model decisions by maximizing your payoff. You want to try and win the most, right? But what people found was that what you actually want to try and do is minimize your regret. — Bryan Pellegrino, Poker Pro and AI Researcher
The favoured algorithm for solving imperfect information games is called Counterfactual Regret Minimization. I added some relevant links at the end of this post, but in my casual version, it works like this:
Assign all the final states (where one player has called the other a liar) the value +1 if the starting player wins, and −1 if the second player wins.For all other states, we’ll maintain a value v(state) (between -1 and 1) that approximates the average value observed in previous games that passed through the given state.(In real CFR the values should be inversely weighted by the player’s probability of going into the state, but for simplicity, and since the weighting is already kinda messed up by using Adam and momentum for training the neural network, I just skipped this part.)Define the “counterfactual regret” r(state, i) = v(state+i)−v(state), that is how much worse (or better) we would have scored (in average) if we had made the action i every time we were in the given state.(Here state+i is the resulting state after taking action i.)Finally, define the strategy (probability of picking action i in a given state) by
Assign all the final states (where one player has called the other a liar) the value +1 if the starting player wins, and −1 if the second player wins.
For all other states, we’ll maintain a value v(state) (between -1 and 1) that approximates the average value observed in previous games that passed through the given state.(In real CFR the values should be inversely weighted by the player’s probability of going into the state, but for simplicity, and since the weighting is already kinda messed up by using Adam and momentum for training the neural network, I just skipped this part.)
Define the “counterfactual regret” r(state, i) = v(state+i)−v(state), that is how much worse (or better) we would have scored (in average) if we had made the action i every time we were in the given state.(Here state+i is the resulting state after taking action i.)
Finally, define the strategy (probability of picking action i in a given state) by
where r(state)+ = max(r(state), 0). This ensures there are no negative probabilities.
It might be tempting to always play the action with the highest expected value v(state+i). However, that would be a deterministic strategy and likely exploitable by our opponent. Instead, the above algorithm — known as Regret Matching — is guaranteed to give us the Nash Equilibrium as our estimates of the state values get more precise.
In real CounterFactual Regret Minimization (CFR for short), we repeatedly improve our v(state) estimates by running a depth-first search on the entire game tree and storing the average score seen so far.
This has two main problems:
It uses too much time.It uses too much space.
It uses too much time.
It uses too much space.
To solve the time problem, we replace the depth-first search with game samples (also known as Monte Carlo CFR). Basically, instead of updating every child state — including those following a probability 0 action — we just play a game and update that path up through the game tree with +1 or −1 depending on the game result. In other words, we are doing reinforcement learning.
To ensure we explore all options, we add some noise to the probabilities when playing. The noise also teaches the AI to take advantage of bad moves from its opponent, since it isn’t trained with an opponent always making perfect choices. Ideally we should reduce the amount of noise added over time during training — if we want to eventually get a Nash Equilibrium — but I didn’t do this.
To solve the memory problem, we don’t store the exact mean score for every possible state. We instead use a neural network that computes a good approximation to the average value, v(state). To mimic the CFR update rule, we use a learning rate of 1/T, where T is the current time step. This ensures v(state) learns the average value over the training games, and not just the most recent outcome. (I actually tried other learning rates like 1/sqrt(T) and 1/T2, and amazingly 1/T was the only one that converged to something near the Nash Equilibrium.)
The complete training code is available in github.com/thomasahle/liars-dice/blob/main/code/train.py, and the most critical part — the self-play code — is just 27 lines.
The code saves triples of (private state, public state, game result) to a list called replay_buffer, which is passed to PyTorch for training the neural network (invoked in game.sample_action). After a step of gradient descent, we play another batch of games with the improved policy and repeat.
The neural network is a function v(private, public) that returns a value between −1 and 1. There are lots of ways we might define this, so I just chose the most straightforward thing I could come up with, and it seems to work well enough.
The private input is a 6 × “number of dice” one-hot representation of the player’s hand. We can view it as a histogram of how many dice we have of each face. This encoding is taken from DouZero [2021].
As the maximum call we can make in a game with two players is 2 × “number of dice”,the public state is a 2 × 6 × (2 × num-dice) one-hot representation of the calls that have been made so far by each player.
Each one-hot input is embedded as a 500-dimensional vector and the two are multiplied together. Other ways of pooling, like concatenation, also work fine, but element-wise multiplication mimics compressed bilinear pooling, for which I have a personal bias.
After combining the private and public states, we run 4 fully connected layers, 100 units wide, with rectified linear units in each layer. Eventually we reduce down to a single scalar value, which we map to [−1,+1] using tanh (like AlphaZero did.)
The training loss is simply MSE: (v(private, public) − game_result)2. Again just copying AlphaZero.
Sometimes I beat it. Sometimes it beats me. Liar’s Dice is a game involving a lot of chance and it would take a lot of games to know for sure who’s the better player. So let’s play a lot of games!
During the first week playing against people online at dudo.ai, the AI won 5031 rounds and lost 4416. This corresponds to a 53.3% win-rate across dice numbers. Games of Liar’s Dice consist of multiple rounds with different number of dice. The AI won 846 complete games and lost 640 corresponding to a 56.9% win-rate.
We can convert these percentages into a rating difference using the classical ELO formula:
Plugging in the win-rates from above, the AI has an advantage of somewhere between 23 and 48 ELO points over the human opponents.
Another interesting test is to see how quickly the algorithm improves as it plays against itself. I set up a tournament where different versions of the model played 10,000 games against every other version. I then used a maximum likelihood estimate to compute the ELO for each player.
The models clearly improve faster in the beginning, but they all keep improving for a long time. It took about 24 hours to train the 5-dice model to 230,000 iterations. The training itself doesn’t take much time, but playing 23,000,000 games took a while, since I didn’t implement any parallelization.
An interesting point is that ELO is usually used for games involving little to no luck, like chess. We might add the element of chance to the ELO formula as follows:
If we use this formula to estimate ELO ratings for the tournament between the different versions, it turns out that the model that best explains the data has r ~ 0.20. This means Liar’s Dice is about 80% pure luck. 🤷
There is a more principled approach to computing exactly how close our AI gets to the Nash Equilibrium. This is called measuring the exploitability of the strategy.
The exploitability is the maximum amount anybody can win against the AI even knowing exactly what probabilities the AI is using and having access to infinite computing power.
Actual CFR is guaranteed to eventually produce an unexploitable strategy. We can’t expect our method to be quite that good since the neural network may not even be able to represent this perfect strategy. However, if we get close to 0, it means the AI is objectively pretty good and not just playing well against itself and humans online.
Computing exploitability is done by computing the optimal response strategy for our opponent. We tell our opponent our strategy (our probabilities for each state) which transform the game turns into a Markov decision process (MDP). The opponent can solve this (in linear time with a depth-first search), and the value of the MDP is the most any opponent playing any strategy could win against us.
While the exploitability can be computed in linear time in the number of states, that is still too expensive for games with 4 or more dice. However I managed to compute the 1v1 exploitability (above), as well as 1v2 and 2v1 (below). Coincidentally these are the same games I managed to compute the exact Nash Equilibrium of (using Linear Programming) 5 years ago. The results were as follows:
Apparently, my model is quite good at learning the best strategy for Player 2. Here the exploitability is not far from the optimum. On the other hand, in both games, the strategy for Player 1 isn’t as good. It seems the AI prefers to judge the humans call before making up its own mind.
Does this mean it is just much harder to play well as Player 1? In the 1v1 setting, this didn’t seem to be a problem... Is there a bug 🐛 somewhere in my algorithm, architecture, or best-response exploiter that only comes up with more dice and for Player 1? If I figure it out, I’ll update this post.
Overall the algorithm seems to learn Liar’s Dice very well & very fast. I’m pretty encouraged by this, given how simple the code and architecture is. It is certainly strong enough to win most of the time against people online. Feel free to play around with the code on Github and make it better!
I decided that having only a terminal interface wouldn’t encourage many of my friends to test the model. I needed something browser-based, but I didn’t want to create an entire server/client setup for running the model.
Luckily I found out about ONNX, particularly this great video by Elliot Waite. In two lines of code, the PyTorch model can be converted into an onnx file, which can be used directly from javascript:
torch.onnx.export(model, path=’out.onnx’)
I created a small static javascript frontend, bought a domain name, and you can now play against it on dudo.ai.
This article is inspired by Erik Bernhardsson’s Deep learning for... chess from 2014. Besides Deepmind’s Player of Games, I took inspiration from other exciting poker papers, like DouZero, DeepStack and ReBeL.
The more advanced methods have two main improvements:
They use two neural networks instead of one: One network (like ours) for the expected game value, and another one that predicts the optimal policy/probability distribution. This second network can be trained particularly well because of another innovation:They use search. Search means that the strategy (probability distribution) for a given state is iteratively improved as the AI is given time to “think”. AIs for classical games — like chess — have always done this, but in CFR the strategy is entirely computed at training time, and more “thinking time” during play doesn’t help the AI. Only in recent years was it discovered how to apply this to games like Liar’s Dice, and the methods are much more complicated than what I thought I could do in an afternoon.
They use two neural networks instead of one: One network (like ours) for the expected game value, and another one that predicts the optimal policy/probability distribution. This second network can be trained particularly well because of another innovation:
They use search. Search means that the strategy (probability distribution) for a given state is iteratively improved as the AI is given time to “think”. AIs for classical games — like chess — have always done this, but in CFR the strategy is entirely computed at training time, and more “thinking time” during play doesn’t help the AI. Only in recent years was it discovered how to apply this to games like Liar’s Dice, and the methods are much more complicated than what I thought I could do in an afternoon.
For more information on CFR, you can see
The original paper Regret Minimization in Games with Incomplete Information from NIPS 2007.The Monte Carlo version from NIPS 2009.A more principled paper on Deep Counterfactual Regret Minimization from ICLR 2020.Chapter 12.4.2.2 on Policy-Based Methods in Handbook of Reinforcement Learning and Control from 2021.
The original paper Regret Minimization in Games with Incomplete Information from NIPS 2007.
The Monte Carlo version from NIPS 2009.
A more principled paper on Deep Counterfactual Regret Minimization from ICLR 2020.
Chapter 12.4.2.2 on Policy-Based Methods in Handbook of Reinforcement Learning and Control from 2021.
Thanks to Kosti for reading an earlier draft of the article, and to Troels Bjerre Lund for criticizing my frivolous use of CFR terms. | [
{
"code": null,
"e": 557,
"s": 165,
"text": "I’ve been meaning to learn about AIs for games like Poker or Liar’s Dice for a while. Recently while reading Deepmind’s article Player of Games, I thought I might be able to make something really simple that works well enough to be fun. “It shouldn’t take more than an afternoon,” I thought. Of course, I ended up spending much more time on it, but it did turn out to be fun and very simple."
},
{
"code": null,
"e": 803,
"s": 557,
"text": "The project allowed me to dive into the exciting concepts of Counterfactual Regret Minimization, Reinforcement Learning, serving PyTorch models in the browser and a few other fun topics, so there are a bunch of things to cover in this blog post."
},
{
"code": null,
"e": 938,
"s": 803,
"text": "I understand. It’s a game of deception. But your bet includes all the dice, not just your own. — Will Turner, Pirates of the Caribbean"
},
{
"code": null,
"e": 1160,
"s": 938,
"text": "Liar’s Dice is a game I personally liked to play back when we could still go to bars. It is simpler than Poker, but has many of the same concepts of betting, bluff and hidden information, making it a fun challenge for AI."
},
{
"code": null,
"e": 1279,
"s": 1160,
"text": "The game is also famous from Pirates of the Caribbean, but I will quickly sketch the rules if you don’t know the game."
},
{
"code": null,
"e": 1438,
"s": 1279,
"text": "Each player has a set of dice known only to them. Players take turns bidding on the minimum number of dice that the player believes are showing a given value."
},
{
"code": null,
"e": 1620,
"s": 1438,
"text": "Each turn, the player must bid a higher quantity of any particular face or the same quantity of a higher face. E.g. “2 ⚃” and “3 ⚂” are both valid bets after “3 ⚁”, but “2 ⚂” isn’t."
},
{
"code": null,
"e": 1823,
"s": 1620,
"text": "Alternatively, the player can challenge the previous bid. If the challenge is successful — e.g. the previous bid was a bluff — the challenger wins the round; otherwise, the player who made the bet wins."
},
{
"code": null,
"e": 1915,
"s": 1823,
"text": "Often ⚀’s are considered jokers and count for any face when summing up the dice in the end."
},
{
"code": null,
"e": 2153,
"s": 1915,
"text": "Example: Alice and Bob may have the hands ⚀ ⚁ and ⚂ ⚃. Alice bids “2 ⚁” (which she can support from her own hand alone), Bob says “2 ⚂” (anticipating that Alice has either a ⚂ or a ⚀ (joker)). Alice calls Bob, but Bob was right and wins."
},
{
"code": null,
"e": 2428,
"s": 2153,
"text": "It takes a bit of theory to explain the algorithm — even though it is ultimately very simple. If you want to jump straight to the neural network section or the evaluation of the model in terms of ELO rating and exploitability, feel free to skip the following three sections."
},
{
"code": null,
"e": 2644,
"s": 2428,
"text": "Why are imperfect-information games so hard? After all, we had Deep Blue, we had AlphaGo. Why can’t we take those techniques and apply them out of the box to a game like Poker? — Noam Brown NIPS2017 best paper talk."
},
{
"code": null,
"e": 3156,
"s": 2644,
"text": "Liar’s Dice is a finite game: There are only so many dice combinations you can roll, and so many sequences of bets that can be made. (We call the combination a state, technically it is often called an info-set) However, unlike games of perfect information like chess, there is no single perfect move (or action) we can compute for each state. Instead, as shown by John von Neumann and John Nash, we need a “Mixed Strategy”: For each state, we pick a move from a probability distribution over the set of actions."
},
{
"code": null,
"e": 3481,
"s": 3156,
"text": "Intuitively this is because having a fixed strategy gives away information about our private dice. If we always make a high bet when we roll a lousy roll, our opponent will learn this and start calling our bluff. If we only bluff half the time, and play safe the other half, it gets harder for our opponent to figure us out."
},
{
"code": null,
"e": 4055,
"s": 3481,
"text": "The Nash equilibrium can be computed using Linear Programming, e.g. the method of Daphne Koller and Nimrod Megiddo, which takes polynomial time in the number of states (or “information sets” as is the more common term.) I actually used precisely this method to solve Liar’s Dice years ago. This is possible because with 1 die each, the maximum bid that makes sense is 2 ⚅’s. That makes a total of 12 possible bids. Combined with the dice information, that’s 6*212 ~400,000 states. This is just within what’s possible with modern Linear Algebra solvers like Google or-tools."
},
{
"code": null,
"e": 4491,
"s": 4055,
"text": "Unfortunately, this method doesn’t scale to multiple dice. With 6 dice each, we get ~1026 states, which is comparable to the total legal positions in chess. And while chess could theoretically be solved by a simple depth-first search — taking constant space and linear time in the number of states — Liar’s Dice is much much harder. This is why AIs could play chess quite well in 1998, but only recently got to the same level in Poker."
},
{
"code": null,
"e": 4600,
"s": 4491,
"text": "Okay, time I actually start explaining how this AI actually works, and how machine learning comes into play."
},
{
"code": null,
"e": 4860,
"s": 4600,
"text": "In the past, a lot of people would model decisions by maximizing your payoff. You want to try and win the most, right? But what people found was that what you actually want to try and do is minimize your regret. — Bryan Pellegrino, Poker Pro and AI Researcher"
},
{
"code": null,
"e": 5068,
"s": 4860,
"text": "The favoured algorithm for solving imperfect information games is called Counterfactual Regret Minimization. I added some relevant links at the end of this post, but in my casual version, it works like this:"
},
{
"code": null,
"e": 6001,
"s": 5068,
"text": "Assign all the final states (where one player has called the other a liar) the value +1 if the starting player wins, and −1 if the second player wins.For all other states, we’ll maintain a value v(state) (between -1 and 1) that approximates the average value observed in previous games that passed through the given state.(In real CFR the values should be inversely weighted by the player’s probability of going into the state, but for simplicity, and since the weighting is already kinda messed up by using Adam and momentum for training the neural network, I just skipped this part.)Define the “counterfactual regret” r(state, i) = v(state+i)−v(state), that is how much worse (or better) we would have scored (in average) if we had made the action i every time we were in the given state.(Here state+i is the resulting state after taking action i.)Finally, define the strategy (probability of picking action i in a given state) by"
},
{
"code": null,
"e": 6152,
"s": 6001,
"text": "Assign all the final states (where one player has called the other a liar) the value +1 if the starting player wins, and −1 if the second player wins."
},
{
"code": null,
"e": 6588,
"s": 6152,
"text": "For all other states, we’ll maintain a value v(state) (between -1 and 1) that approximates the average value observed in previous games that passed through the given state.(In real CFR the values should be inversely weighted by the player’s probability of going into the state, but for simplicity, and since the weighting is already kinda messed up by using Adam and momentum for training the neural network, I just skipped this part.)"
},
{
"code": null,
"e": 6854,
"s": 6588,
"text": "Define the “counterfactual regret” r(state, i) = v(state+i)−v(state), that is how much worse (or better) we would have scored (in average) if we had made the action i every time we were in the given state.(Here state+i is the resulting state after taking action i.)"
},
{
"code": null,
"e": 6937,
"s": 6854,
"text": "Finally, define the strategy (probability of picking action i in a given state) by"
},
{
"code": null,
"e": 7023,
"s": 6937,
"text": "where r(state)+ = max(r(state), 0). This ensures there are no negative probabilities."
},
{
"code": null,
"e": 7361,
"s": 7023,
"text": "It might be tempting to always play the action with the highest expected value v(state+i). However, that would be a deterministic strategy and likely exploitable by our opponent. Instead, the above algorithm — known as Regret Matching — is guaranteed to give us the Nash Equilibrium as our estimates of the state values get more precise."
},
{
"code": null,
"e": 7565,
"s": 7361,
"text": "In real CounterFactual Regret Minimization (CFR for short), we repeatedly improve our v(state) estimates by running a depth-first search on the entire game tree and storing the average score seen so far."
},
{
"code": null,
"e": 7593,
"s": 7565,
"text": "This has two main problems:"
},
{
"code": null,
"e": 7639,
"s": 7593,
"text": "It uses too much time.It uses too much space."
},
{
"code": null,
"e": 7662,
"s": 7639,
"text": "It uses too much time."
},
{
"code": null,
"e": 7686,
"s": 7662,
"text": "It uses too much space."
},
{
"code": null,
"e": 8063,
"s": 7686,
"text": "To solve the time problem, we replace the depth-first search with game samples (also known as Monte Carlo CFR). Basically, instead of updating every child state — including those following a probability 0 action — we just play a game and update that path up through the game tree with +1 or −1 depending on the game result. In other words, we are doing reinforcement learning."
},
{
"code": null,
"e": 8452,
"s": 8063,
"text": "To ensure we explore all options, we add some noise to the probabilities when playing. The noise also teaches the AI to take advantage of bad moves from its opponent, since it isn’t trained with an opponent always making perfect choices. Ideally we should reduce the amount of noise added over time during training — if we want to eventually get a Nash Equilibrium — but I didn’t do this."
},
{
"code": null,
"e": 9002,
"s": 8452,
"text": "To solve the memory problem, we don’t store the exact mean score for every possible state. We instead use a neural network that computes a good approximation to the average value, v(state). To mimic the CFR update rule, we use a learning rate of 1/T, where T is the current time step. This ensures v(state) learns the average value over the training games, and not just the most recent outcome. (I actually tried other learning rates like 1/sqrt(T) and 1/T2, and amazingly 1/T was the only one that converged to something near the Nash Equilibrium.)"
},
{
"code": null,
"e": 9171,
"s": 9002,
"text": "The complete training code is available in github.com/thomasahle/liars-dice/blob/main/code/train.py, and the most critical part — the self-play code — is just 27 lines."
},
{
"code": null,
"e": 9466,
"s": 9171,
"text": "The code saves triples of (private state, public state, game result) to a list called replay_buffer, which is passed to PyTorch for training the neural network (invoked in game.sample_action). After a step of gradient descent, we play another batch of games with the improved policy and repeat."
},
{
"code": null,
"e": 9705,
"s": 9466,
"text": "The neural network is a function v(private, public) that returns a value between −1 and 1. There are lots of ways we might define this, so I just chose the most straightforward thing I could come up with, and it seems to work well enough."
},
{
"code": null,
"e": 9907,
"s": 9705,
"text": "The private input is a 6 × “number of dice” one-hot representation of the player’s hand. We can view it as a histogram of how many dice we have of each face. This encoding is taken from DouZero [2021]."
},
{
"code": null,
"e": 10114,
"s": 9907,
"text": "As the maximum call we can make in a game with two players is 2 × “number of dice”,the public state is a 2 × 6 × (2 × num-dice) one-hot representation of the calls that have been made so far by each player."
},
{
"code": null,
"e": 10371,
"s": 10114,
"text": "Each one-hot input is embedded as a 500-dimensional vector and the two are multiplied together. Other ways of pooling, like concatenation, also work fine, but element-wise multiplication mimics compressed bilinear pooling, for which I have a personal bias."
},
{
"code": null,
"e": 10619,
"s": 10371,
"text": "After combining the private and public states, we run 4 fully connected layers, 100 units wide, with rectified linear units in each layer. Eventually we reduce down to a single scalar value, which we map to [−1,+1] using tanh (like AlphaZero did.)"
},
{
"code": null,
"e": 10719,
"s": 10619,
"text": "The training loss is simply MSE: (v(private, public) − game_result)2. Again just copying AlphaZero."
},
{
"code": null,
"e": 10916,
"s": 10719,
"text": "Sometimes I beat it. Sometimes it beats me. Liar’s Dice is a game involving a lot of chance and it would take a lot of games to know for sure who’s the better player. So let’s play a lot of games!"
},
{
"code": null,
"e": 11233,
"s": 10916,
"text": "During the first week playing against people online at dudo.ai, the AI won 5031 rounds and lost 4416. This corresponds to a 53.3% win-rate across dice numbers. Games of Liar’s Dice consist of multiple rounds with different number of dice. The AI won 846 complete games and lost 640 corresponding to a 56.9% win-rate."
},
{
"code": null,
"e": 11324,
"s": 11233,
"text": "We can convert these percentages into a rating difference using the classical ELO formula:"
},
{
"code": null,
"e": 11454,
"s": 11324,
"text": "Plugging in the win-rates from above, the AI has an advantage of somewhere between 23 and 48 ELO points over the human opponents."
},
{
"code": null,
"e": 11739,
"s": 11454,
"text": "Another interesting test is to see how quickly the algorithm improves as it plays against itself. I set up a tournament where different versions of the model played 10,000 games against every other version. I then used a maximum likelihood estimate to compute the ELO for each player."
},
{
"code": null,
"e": 12041,
"s": 11739,
"text": "The models clearly improve faster in the beginning, but they all keep improving for a long time. It took about 24 hours to train the 5-dice model to 230,000 iterations. The training itself doesn’t take much time, but playing 23,000,000 games took a while, since I didn’t implement any parallelization."
},
{
"code": null,
"e": 12207,
"s": 12041,
"text": "An interesting point is that ELO is usually used for games involving little to no luck, like chess. We might add the element of chance to the ELO formula as follows:"
},
{
"code": null,
"e": 12424,
"s": 12207,
"text": "If we use this formula to estimate ELO ratings for the tournament between the different versions, it turns out that the model that best explains the data has r ~ 0.20. This means Liar’s Dice is about 80% pure luck. 🤷"
},
{
"code": null,
"e": 12589,
"s": 12424,
"text": "There is a more principled approach to computing exactly how close our AI gets to the Nash Equilibrium. This is called measuring the exploitability of the strategy."
},
{
"code": null,
"e": 12764,
"s": 12589,
"text": "The exploitability is the maximum amount anybody can win against the AI even knowing exactly what probabilities the AI is using and having access to infinite computing power."
},
{
"code": null,
"e": 13103,
"s": 12764,
"text": "Actual CFR is guaranteed to eventually produce an unexploitable strategy. We can’t expect our method to be quite that good since the neural network may not even be able to represent this perfect strategy. However, if we get close to 0, it means the AI is objectively pretty good and not just playing well against itself and humans online."
},
{
"code": null,
"e": 13500,
"s": 13103,
"text": "Computing exploitability is done by computing the optimal response strategy for our opponent. We tell our opponent our strategy (our probabilities for each state) which transform the game turns into a Markov decision process (MDP). The opponent can solve this (in linear time with a depth-first search), and the value of the MDP is the most any opponent playing any strategy could win against us."
},
{
"code": null,
"e": 13893,
"s": 13500,
"text": "While the exploitability can be computed in linear time in the number of states, that is still too expensive for games with 4 or more dice. However I managed to compute the 1v1 exploitability (above), as well as 1v2 and 2v1 (below). Coincidentally these are the same games I managed to compute the exact Nash Equilibrium of (using Linear Programming) 5 years ago. The results were as follows:"
},
{
"code": null,
"e": 14180,
"s": 13893,
"text": "Apparently, my model is quite good at learning the best strategy for Player 2. Here the exploitability is not far from the optimum. On the other hand, in both games, the strategy for Player 1 isn’t as good. It seems the AI prefers to judge the humans call before making up its own mind."
},
{
"code": null,
"e": 14480,
"s": 14180,
"text": "Does this mean it is just much harder to play well as Player 1? In the 1v1 setting, this didn’t seem to be a problem... Is there a bug 🐛 somewhere in my algorithm, architecture, or best-response exploiter that only comes up with more dice and for Player 1? If I figure it out, I’ll update this post."
},
{
"code": null,
"e": 14776,
"s": 14480,
"text": "Overall the algorithm seems to learn Liar’s Dice very well & very fast. I’m pretty encouraged by this, given how simple the code and architecture is. It is certainly strong enough to win most of the time against people online. Feel free to play around with the code on Github and make it better!"
},
{
"code": null,
"e": 14996,
"s": 14776,
"text": "I decided that having only a terminal interface wouldn’t encourage many of my friends to test the model. I needed something browser-based, but I didn’t want to create an entire server/client setup for running the model."
},
{
"code": null,
"e": 15195,
"s": 14996,
"text": "Luckily I found out about ONNX, particularly this great video by Elliot Waite. In two lines of code, the PyTorch model can be converted into an onnx file, which can be used directly from javascript:"
},
{
"code": null,
"e": 15237,
"s": 15195,
"text": "torch.onnx.export(model, path=’out.onnx’)"
},
{
"code": null,
"e": 15349,
"s": 15237,
"text": "I created a small static javascript frontend, bought a domain name, and you can now play against it on dudo.ai."
},
{
"code": null,
"e": 15559,
"s": 15349,
"text": "This article is inspired by Erik Bernhardsson’s Deep learning for... chess from 2014. Besides Deepmind’s Player of Games, I took inspiration from other exciting poker papers, like DouZero, DeepStack and ReBeL."
},
{
"code": null,
"e": 15613,
"s": 15559,
"text": "The more advanced methods have two main improvements:"
},
{
"code": null,
"e": 16379,
"s": 15613,
"text": "They use two neural networks instead of one: One network (like ours) for the expected game value, and another one that predicts the optimal policy/probability distribution. This second network can be trained particularly well because of another innovation:They use search. Search means that the strategy (probability distribution) for a given state is iteratively improved as the AI is given time to “think”. AIs for classical games — like chess — have always done this, but in CFR the strategy is entirely computed at training time, and more “thinking time” during play doesn’t help the AI. Only in recent years was it discovered how to apply this to games like Liar’s Dice, and the methods are much more complicated than what I thought I could do in an afternoon."
},
{
"code": null,
"e": 16636,
"s": 16379,
"text": "They use two neural networks instead of one: One network (like ours) for the expected game value, and another one that predicts the optimal policy/probability distribution. This second network can be trained particularly well because of another innovation:"
},
{
"code": null,
"e": 17146,
"s": 16636,
"text": "They use search. Search means that the strategy (probability distribution) for a given state is iteratively improved as the AI is given time to “think”. AIs for classical games — like chess — have always done this, but in CFR the strategy is entirely computed at training time, and more “thinking time” during play doesn’t help the AI. Only in recent years was it discovered how to apply this to games like Liar’s Dice, and the methods are much more complicated than what I thought I could do in an afternoon."
},
{
"code": null,
"e": 17187,
"s": 17146,
"text": "For more information on CFR, you can see"
},
{
"code": null,
"e": 17501,
"s": 17187,
"text": "The original paper Regret Minimization in Games with Incomplete Information from NIPS 2007.The Monte Carlo version from NIPS 2009.A more principled paper on Deep Counterfactual Regret Minimization from ICLR 2020.Chapter 12.4.2.2 on Policy-Based Methods in Handbook of Reinforcement Learning and Control from 2021."
},
{
"code": null,
"e": 17593,
"s": 17501,
"text": "The original paper Regret Minimization in Games with Incomplete Information from NIPS 2007."
},
{
"code": null,
"e": 17633,
"s": 17593,
"text": "The Monte Carlo version from NIPS 2009."
},
{
"code": null,
"e": 17716,
"s": 17633,
"text": "A more principled paper on Deep Counterfactual Regret Minimization from ICLR 2020."
},
{
"code": null,
"e": 17818,
"s": 17716,
"text": "Chapter 12.4.2.2 on Policy-Based Methods in Handbook of Reinforcement Learning and Control from 2021."
}
] |
How to pass data from one activity to another in Android using shared preferences? | This example demonstrate about How to pass data from one activity to another in Android using shared preferences
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_margin = "16dp"
android:orientation = "vertical"
tools:context = ".MainActivity">
<EditText
android:id = "@+id/edit_text"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_gravity = "center"
android:hint = "Enter something to pass"
android:inputType = "text" />
<Button
android:id = "@+id/button"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "center"
android:layout_marginTop = "16dp"
android:text = "Next" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = findViewById(R.id.edit_text);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String value = editText.getText().toString().trim();
SharedPreferences sharedPref = getSharedPreferences("myKey", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("value", value);
editor.apply();
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
}
Step 4 − Add the following code to res/layout/activity_second.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_margin = "16dp"
android:orientation = "vertical"
tools:context = ".SecondActivity">
<TextView
android:id = "@+id/text_view"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_gravity = "center" />
</LinearLayout>
Step 5 − Add the following code to src/SecondActivity.java
package com.example.myapplication;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TextView textView = findViewById(R.id.text_view);
SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE);
String value = sharedPreferences.getString("value","");
textView.setText(value);
}
}
Step 6 − 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.myapplication">
<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>
<activity android:name = ".SecondActivity"></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 Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "This example demonstrate about How to pass data from one activity to another in Android using shared preferences"
},
{
"code": null,
"e": 1304,
"s": 1175,
"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": 1369,
"s": 1304,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2249,
"s": 1369,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".MainActivity\">\n <EditText\n android:id = \"@+id/edit_text\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:hint = \"Enter something to pass\"\n android:inputType = \"text\" />\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:layout_marginTop = \"16dp\"\n android:text = \"Next\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2306,
"s": 2249,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3455,
"s": 2306,
"text": "package com.example.myapplication;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final EditText editText = findViewById(R.id.edit_text);\n Button button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String value = editText.getText().toString().trim();\n SharedPreferences sharedPref = getSharedPreferences(\"myKey\", MODE_PRIVATE);\n SharedPreferences.Editor editor = sharedPref.edit();\n editor.putString(\"value\", value);\n editor.apply();\n Intent intent = new Intent(MainActivity.this, SecondActivity.class);\n startActivity(intent);\n }\n });\n }\n}"
},
{
"code": null,
"e": 3522,
"s": 3455,
"text": "Step 4 − Add the following code to res/layout/activity_second.xml."
},
{
"code": null,
"e": 4080,
"s": 3522,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".SecondActivity\">\n <TextView\n android:id = \"@+id/text_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\" />\n</LinearLayout>"
},
{
"code": null,
"e": 4139,
"s": 4080,
"text": "Step 5 − Add the following code to src/SecondActivity.java"
},
{
"code": null,
"e": 4784,
"s": 4139,
"text": "package com.example.myapplication;\nimport android.content.SharedPreferences;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\n\npublic class SecondActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n TextView textView = findViewById(R.id.text_view);\n SharedPreferences sharedPreferences = getSharedPreferences(\"myKey\", MODE_PRIVATE);\n String value = sharedPreferences.getString(\"value\",\"\");\n textView.setText(value);\n }\n}"
},
{
"code": null,
"e": 4839,
"s": 4784,
"text": "Step 6 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5610,
"s": 4839,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\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 <activity android:name = \".SecondActivity\"></activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5957,
"s": 5610,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 5997,
"s": 5957,
"text": "Click here to download the project code"
}
] |
Write a SQL query to count the number of duplicate TRANSACTION_ID in an ORDERS DB2 table | We can find the duplicate TRANSACTION_ID in the ORDERS DB2 table using the below query:
SELECT TRANSACTION_ID, COUNT(*) AS TRANSACTION_COUNT FROM ORDER
GROUP BY TRANSACTION_ID
HAVING COUNT(*) > 1
The purpose of COUNT(*) is to count the number of rows. We will group the result based on the TRANSACTION_ID using GROUP BY function and to display the duplicate transaction ids, we will place a predicate using HAVING statement for COUNT(*) greater than one.
For example, consider the below TRANSACTIONS DB2 table:
The query will give the below result: | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "We can find the duplicate TRANSACTION_ID in the ORDERS DB2 table using the below query:"
},
{
"code": null,
"e": 1258,
"s": 1150,
"text": "SELECT TRANSACTION_ID, COUNT(*) AS TRANSACTION_COUNT FROM ORDER\nGROUP BY TRANSACTION_ID\nHAVING COUNT(*) > 1"
},
{
"code": null,
"e": 1517,
"s": 1258,
"text": "The purpose of COUNT(*) is to count the number of rows. We will group the result based on the TRANSACTION_ID using GROUP BY function and to display the duplicate transaction ids, we will place a predicate using HAVING statement for COUNT(*) greater than one."
},
{
"code": null,
"e": 1573,
"s": 1517,
"text": "For example, consider the below TRANSACTIONS DB2 table:"
},
{
"code": null,
"e": 1611,
"s": 1573,
"text": "The query will give the below result:"
}
] |
How to Run a Python Script - GeeksforGeeks | 27 Dec, 2019
Python is a well known high-level programming language. The Python script is basically a file containing code written in Python. The file containing python script has the extension ‘.py’ or can also have the extension ‘.pyw’ if it is being run on a windows machine. To run a python script, we need a python interpreter that needs to be downloaded and installed.
Here is a simple python script to print ‘Hello World!’:
print('Hello World!')
Here, the ‘print()’ function is to print out any text written within the parenthesis. We can write the text that we want to be printed using either a single quote as shown in the above script or a double quote.
If you are coming from any other language then you will also notice that there is no semicolon at the end of the statement as with Python, you no need to specify the end of the line. And also we don’t need to include or import any files to run a simple python script.
There is more than one way to run a python script but before going toward the different ways to run a python script, we first have to check whether a python interpreter is installed on the system or not. So in windows, open ‘cmd’ (Command Prompt) and type the following command.
python -V
This command will give the version number of the Python interpreter installed or will display an error if otherwise.
Here are the ways with which we can run a Python script.
Interactive ModeCommand LineText Editor (VS Code)IDE (PyCharm)
Interactive Mode
Command Line
Text Editor (VS Code)
IDE (PyCharm)
Interactive Mode:In Interactive Mode, you can run your script line by line in a sequence.To enter in an interactive mode, you will have to open Command Prompt on your windows machine and type ‘python’ and press Enter.Example 1:Run the following line in the interactive mode:print('Hello World !')Output:Example 2:Run the following lines one by one in the interactive mode:name = "Aakash"print("My name is " + name)Output:Example 3:Run the following line one by one in the interactive mode:a = 1b = 3if a > b: print("a is Greater") else: print("b is Greater")Output:Note: To exit from this mode, press ‘Ctrl+Z’ and then press ‘Enter’ or type ‘exit()’ and then press Enter.Command LineTo run a Python script store in a ‘.py’ file in command line, we have to write ‘python’ keyword before the file name in the command prompt.python hello.py
You can write your own file name in place of ‘hello.py’.Output:Text Editor (VS Code)To run Python script on a text editor like VS Code (Visual Studio Code) then you will have to do the following:Go in the extension section or press ‘Ctrl+Shift+X’ on windows, then search and install the extension named ‘Python’ and ‘Code Runner’. Restart your vs code after that.Now, create a new file with the name ‘hello.py’ and write the below code in it:print('Hello World!')
Then, right click anywhere in the text area and select the option that says ‘Run Code’ or press ‘Ctrl+Alt+N’ to run the code.Output:IDE (PyCharm)To run Python script on a IDE (Integrated Development Environment) like PyCharm, you will have to do the following:Create a new project.Give a name to that project as ‘GfG’ and click on Create.Select the root directory with the project name we specified in the last step. Right click on it, go in New and click on ‘Python file’ option. Then give the name of the file as ‘hello’ (you can specify any name as per your project requirement). This will create a ‘hello.py’ file in the project root directory.Note: You don’t have to specify the extension as it will take it automatically.Now write the below Python script to print the message:print('Hello World !')To run this python script, Right click and select ‘Run File in Python Console’ option. This will open a console box at the bottom and show the out put there. We can also run using the Green Play Button at the top right corner of the IDE.Output:
Interactive Mode:In Interactive Mode, you can run your script line by line in a sequence.To enter in an interactive mode, you will have to open Command Prompt on your windows machine and type ‘python’ and press Enter.Example 1:Run the following line in the interactive mode:print('Hello World !')Output:Example 2:Run the following lines one by one in the interactive mode:name = "Aakash"print("My name is " + name)Output:Example 3:Run the following line one by one in the interactive mode:a = 1b = 3if a > b: print("a is Greater") else: print("b is Greater")Output:Note: To exit from this mode, press ‘Ctrl+Z’ and then press ‘Enter’ or type ‘exit()’ and then press Enter.
To enter in an interactive mode, you will have to open Command Prompt on your windows machine and type ‘python’ and press Enter.
Example 1:Run the following line in the interactive mode:
print('Hello World !')
Output:
Example 2:Run the following lines one by one in the interactive mode:
name = "Aakash"print("My name is " + name)
Output:
Example 3:Run the following line one by one in the interactive mode:
a = 1b = 3if a > b: print("a is Greater") else: print("b is Greater")
Output:
Note: To exit from this mode, press ‘Ctrl+Z’ and then press ‘Enter’ or type ‘exit()’ and then press Enter.
Command LineTo run a Python script store in a ‘.py’ file in command line, we have to write ‘python’ keyword before the file name in the command prompt.python hello.py
You can write your own file name in place of ‘hello.py’.Output:
python hello.py
You can write your own file name in place of ‘hello.py’.
Output:
Text Editor (VS Code)To run Python script on a text editor like VS Code (Visual Studio Code) then you will have to do the following:Go in the extension section or press ‘Ctrl+Shift+X’ on windows, then search and install the extension named ‘Python’ and ‘Code Runner’. Restart your vs code after that.Now, create a new file with the name ‘hello.py’ and write the below code in it:print('Hello World!')
Then, right click anywhere in the text area and select the option that says ‘Run Code’ or press ‘Ctrl+Alt+N’ to run the code.Output:
Go in the extension section or press ‘Ctrl+Shift+X’ on windows, then search and install the extension named ‘Python’ and ‘Code Runner’. Restart your vs code after that.
Now, create a new file with the name ‘hello.py’ and write the below code in it:print('Hello World!')
print('Hello World!')
Then, right click anywhere in the text area and select the option that says ‘Run Code’ or press ‘Ctrl+Alt+N’ to run the code.
Output:
IDE (PyCharm)To run Python script on a IDE (Integrated Development Environment) like PyCharm, you will have to do the following:Create a new project.Give a name to that project as ‘GfG’ and click on Create.Select the root directory with the project name we specified in the last step. Right click on it, go in New and click on ‘Python file’ option. Then give the name of the file as ‘hello’ (you can specify any name as per your project requirement). This will create a ‘hello.py’ file in the project root directory.Note: You don’t have to specify the extension as it will take it automatically.Now write the below Python script to print the message:print('Hello World !')To run this python script, Right click and select ‘Run File in Python Console’ option. This will open a console box at the bottom and show the out put there. We can also run using the Green Play Button at the top right corner of the IDE.Output:
Create a new project.
Give a name to that project as ‘GfG’ and click on Create.
Select the root directory with the project name we specified in the last step. Right click on it, go in New and click on ‘Python file’ option. Then give the name of the file as ‘hello’ (you can specify any name as per your project requirement). This will create a ‘hello.py’ file in the project root directory.Note: You don’t have to specify the extension as it will take it automatically.
Now write the below Python script to print the message:print('Hello World !')
print('Hello World !')
To run this python script, Right click and select ‘Run File in Python Console’ option. This will open a console box at the bottom and show the out put there. We can also run using the Green Play Button at the top right corner of the IDE.
Output:
python-basics
Python-scripting
Python
Technical Scripter
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
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python
Stack in Python | [
{
"code": null,
"e": 23909,
"s": 23881,
"text": "\n27 Dec, 2019"
},
{
"code": null,
"e": 24271,
"s": 23909,
"text": "Python is a well known high-level programming language. The Python script is basically a file containing code written in Python. The file containing python script has the extension ‘.py’ or can also have the extension ‘.pyw’ if it is being run on a windows machine. To run a python script, we need a python interpreter that needs to be downloaded and installed."
},
{
"code": null,
"e": 24327,
"s": 24271,
"text": "Here is a simple python script to print ‘Hello World!’:"
},
{
"code": null,
"e": 24350,
"s": 24327,
"text": "print('Hello World!')\n"
},
{
"code": null,
"e": 24561,
"s": 24350,
"text": "Here, the ‘print()’ function is to print out any text written within the parenthesis. We can write the text that we want to be printed using either a single quote as shown in the above script or a double quote."
},
{
"code": null,
"e": 24829,
"s": 24561,
"text": "If you are coming from any other language then you will also notice that there is no semicolon at the end of the statement as with Python, you no need to specify the end of the line. And also we don’t need to include or import any files to run a simple python script."
},
{
"code": null,
"e": 25108,
"s": 24829,
"text": "There is more than one way to run a python script but before going toward the different ways to run a python script, we first have to check whether a python interpreter is installed on the system or not. So in windows, open ‘cmd’ (Command Prompt) and type the following command."
},
{
"code": null,
"e": 25119,
"s": 25108,
"text": "python -V\n"
},
{
"code": null,
"e": 25236,
"s": 25119,
"text": "This command will give the version number of the Python interpreter installed or will display an error if otherwise."
},
{
"code": null,
"e": 25293,
"s": 25236,
"text": "Here are the ways with which we can run a Python script."
},
{
"code": null,
"e": 25356,
"s": 25293,
"text": "Interactive ModeCommand LineText Editor (VS Code)IDE (PyCharm)"
},
{
"code": null,
"e": 25373,
"s": 25356,
"text": "Interactive Mode"
},
{
"code": null,
"e": 25386,
"s": 25373,
"text": "Command Line"
},
{
"code": null,
"e": 25408,
"s": 25386,
"text": "Text Editor (VS Code)"
},
{
"code": null,
"e": 25422,
"s": 25408,
"text": "IDE (PyCharm)"
},
{
"code": null,
"e": 27779,
"s": 25422,
"text": "Interactive Mode:In Interactive Mode, you can run your script line by line in a sequence.To enter in an interactive mode, you will have to open Command Prompt on your windows machine and type ‘python’ and press Enter.Example 1:Run the following line in the interactive mode:print('Hello World !')Output:Example 2:Run the following lines one by one in the interactive mode:name = \"Aakash\"print(\"My name is \" + name)Output:Example 3:Run the following line one by one in the interactive mode:a = 1b = 3if a > b: print(\"a is Greater\") else: print(\"b is Greater\")Output:Note: To exit from this mode, press ‘Ctrl+Z’ and then press ‘Enter’ or type ‘exit()’ and then press Enter.Command LineTo run a Python script store in a ‘.py’ file in command line, we have to write ‘python’ keyword before the file name in the command prompt.python hello.py\nYou can write your own file name in place of ‘hello.py’.Output:Text Editor (VS Code)To run Python script on a text editor like VS Code (Visual Studio Code) then you will have to do the following:Go in the extension section or press ‘Ctrl+Shift+X’ on windows, then search and install the extension named ‘Python’ and ‘Code Runner’. Restart your vs code after that.Now, create a new file with the name ‘hello.py’ and write the below code in it:print('Hello World!')\nThen, right click anywhere in the text area and select the option that says ‘Run Code’ or press ‘Ctrl+Alt+N’ to run the code.Output:IDE (PyCharm)To run Python script on a IDE (Integrated Development Environment) like PyCharm, you will have to do the following:Create a new project.Give a name to that project as ‘GfG’ and click on Create.Select the root directory with the project name we specified in the last step. Right click on it, go in New and click on ‘Python file’ option. Then give the name of the file as ‘hello’ (you can specify any name as per your project requirement). This will create a ‘hello.py’ file in the project root directory.Note: You don’t have to specify the extension as it will take it automatically.Now write the below Python script to print the message:print('Hello World !')To run this python script, Right click and select ‘Run File in Python Console’ option. This will open a console box at the bottom and show the out put there. We can also run using the Green Play Button at the top right corner of the IDE.Output:"
},
{
"code": null,
"e": 28457,
"s": 27779,
"text": "Interactive Mode:In Interactive Mode, you can run your script line by line in a sequence.To enter in an interactive mode, you will have to open Command Prompt on your windows machine and type ‘python’ and press Enter.Example 1:Run the following line in the interactive mode:print('Hello World !')Output:Example 2:Run the following lines one by one in the interactive mode:name = \"Aakash\"print(\"My name is \" + name)Output:Example 3:Run the following line one by one in the interactive mode:a = 1b = 3if a > b: print(\"a is Greater\") else: print(\"b is Greater\")Output:Note: To exit from this mode, press ‘Ctrl+Z’ and then press ‘Enter’ or type ‘exit()’ and then press Enter."
},
{
"code": null,
"e": 28586,
"s": 28457,
"text": "To enter in an interactive mode, you will have to open Command Prompt on your windows machine and type ‘python’ and press Enter."
},
{
"code": null,
"e": 28644,
"s": 28586,
"text": "Example 1:Run the following line in the interactive mode:"
},
{
"code": "print('Hello World !')",
"e": 28667,
"s": 28644,
"text": null
},
{
"code": null,
"e": 28675,
"s": 28667,
"text": "Output:"
},
{
"code": null,
"e": 28745,
"s": 28675,
"text": "Example 2:Run the following lines one by one in the interactive mode:"
},
{
"code": "name = \"Aakash\"print(\"My name is \" + name)",
"e": 28788,
"s": 28745,
"text": null
},
{
"code": null,
"e": 28796,
"s": 28788,
"text": "Output:"
},
{
"code": null,
"e": 28865,
"s": 28796,
"text": "Example 3:Run the following line one by one in the interactive mode:"
},
{
"code": "a = 1b = 3if a > b: print(\"a is Greater\") else: print(\"b is Greater\")",
"e": 28941,
"s": 28865,
"text": null
},
{
"code": null,
"e": 28949,
"s": 28941,
"text": "Output:"
},
{
"code": null,
"e": 29056,
"s": 28949,
"text": "Note: To exit from this mode, press ‘Ctrl+Z’ and then press ‘Enter’ or type ‘exit()’ and then press Enter."
},
{
"code": null,
"e": 29287,
"s": 29056,
"text": "Command LineTo run a Python script store in a ‘.py’ file in command line, we have to write ‘python’ keyword before the file name in the command prompt.python hello.py\nYou can write your own file name in place of ‘hello.py’.Output:"
},
{
"code": null,
"e": 29304,
"s": 29287,
"text": "python hello.py\n"
},
{
"code": null,
"e": 29361,
"s": 29304,
"text": "You can write your own file name in place of ‘hello.py’."
},
{
"code": null,
"e": 29369,
"s": 29361,
"text": "Output:"
},
{
"code": null,
"e": 29903,
"s": 29369,
"text": "Text Editor (VS Code)To run Python script on a text editor like VS Code (Visual Studio Code) then you will have to do the following:Go in the extension section or press ‘Ctrl+Shift+X’ on windows, then search and install the extension named ‘Python’ and ‘Code Runner’. Restart your vs code after that.Now, create a new file with the name ‘hello.py’ and write the below code in it:print('Hello World!')\nThen, right click anywhere in the text area and select the option that says ‘Run Code’ or press ‘Ctrl+Alt+N’ to run the code.Output:"
},
{
"code": null,
"e": 30072,
"s": 29903,
"text": "Go in the extension section or press ‘Ctrl+Shift+X’ on windows, then search and install the extension named ‘Python’ and ‘Code Runner’. Restart your vs code after that."
},
{
"code": null,
"e": 30174,
"s": 30072,
"text": "Now, create a new file with the name ‘hello.py’ and write the below code in it:print('Hello World!')\n"
},
{
"code": null,
"e": 30197,
"s": 30174,
"text": "print('Hello World!')\n"
},
{
"code": null,
"e": 30323,
"s": 30197,
"text": "Then, right click anywhere in the text area and select the option that says ‘Run Code’ or press ‘Ctrl+Alt+N’ to run the code."
},
{
"code": null,
"e": 30331,
"s": 30323,
"text": "Output:"
},
{
"code": null,
"e": 31248,
"s": 30331,
"text": "IDE (PyCharm)To run Python script on a IDE (Integrated Development Environment) like PyCharm, you will have to do the following:Create a new project.Give a name to that project as ‘GfG’ and click on Create.Select the root directory with the project name we specified in the last step. Right click on it, go in New and click on ‘Python file’ option. Then give the name of the file as ‘hello’ (you can specify any name as per your project requirement). This will create a ‘hello.py’ file in the project root directory.Note: You don’t have to specify the extension as it will take it automatically.Now write the below Python script to print the message:print('Hello World !')To run this python script, Right click and select ‘Run File in Python Console’ option. This will open a console box at the bottom and show the out put there. We can also run using the Green Play Button at the top right corner of the IDE.Output:"
},
{
"code": null,
"e": 31270,
"s": 31248,
"text": "Create a new project."
},
{
"code": null,
"e": 31328,
"s": 31270,
"text": "Give a name to that project as ‘GfG’ and click on Create."
},
{
"code": null,
"e": 31718,
"s": 31328,
"text": "Select the root directory with the project name we specified in the last step. Right click on it, go in New and click on ‘Python file’ option. Then give the name of the file as ‘hello’ (you can specify any name as per your project requirement). This will create a ‘hello.py’ file in the project root directory.Note: You don’t have to specify the extension as it will take it automatically."
},
{
"code": null,
"e": 31796,
"s": 31718,
"text": "Now write the below Python script to print the message:print('Hello World !')"
},
{
"code": "print('Hello World !')",
"e": 31819,
"s": 31796,
"text": null
},
{
"code": null,
"e": 32057,
"s": 31819,
"text": "To run this python script, Right click and select ‘Run File in Python Console’ option. This will open a console box at the bottom and show the out put there. We can also run using the Green Play Button at the top right corner of the IDE."
},
{
"code": null,
"e": 32065,
"s": 32057,
"text": "Output:"
},
{
"code": null,
"e": 32079,
"s": 32065,
"text": "python-basics"
},
{
"code": null,
"e": 32096,
"s": 32079,
"text": "Python-scripting"
},
{
"code": null,
"e": 32103,
"s": 32096,
"text": "Python"
},
{
"code": null,
"e": 32122,
"s": 32103,
"text": "Technical Scripter"
},
{
"code": null,
"e": 32220,
"s": 32122,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32229,
"s": 32220,
"text": "Comments"
},
{
"code": null,
"e": 32242,
"s": 32229,
"text": "Old Comments"
},
{
"code": null,
"e": 32260,
"s": 32242,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32295,
"s": 32260,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 32317,
"s": 32295,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 32359,
"s": 32317,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 32384,
"s": 32359,
"text": "sum() function in Python"
},
{
"code": null,
"e": 32416,
"s": 32384,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 32432,
"s": 32416,
"text": "Deque in Python"
},
{
"code": null,
"e": 32458,
"s": 32432,
"text": "Python String | replace()"
},
{
"code": null,
"e": 32494,
"s": 32458,
"text": "Convert integer to string in Python"
}
] |
How to use $regex in MongoDB? | Following is the syntax to use $regex in MongoDB −
db.yourCollectionName.find({yourFieldName: { $regex: yourValue}});
Let us first create a collection with documents −
> db.regularExpressionDemo.insertOne({"UserName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdffc25bf3115999ed51210")
}
> db.regularExpressionDemo.insertOne({"UserName":"JOHN"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdffc2ebf3115999ed51211")
}
> db.regularExpressionDemo.insertOne({"UserName":"john"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdffc35bf3115999ed51212")
}
> db.regularExpressionDemo.insertOne({"UserName":"JoHn"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdffc3ebf3115999ed51213")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.regularExpressionDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }
Following is the query to use $regex −
> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN'}});
This will produce the following output −
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
Let us now match all the cases. Following is the query −
> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN', $options: 'i' }});
This will produce the following output −
{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" }
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
{ "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" }
{ "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" } | [
{
"code": null,
"e": 1113,
"s": 1062,
"text": "Following is the syntax to use $regex in MongoDB −"
},
{
"code": null,
"e": 1180,
"s": 1113,
"text": "db.yourCollectionName.find({yourFieldName: { $regex: yourValue}});"
},
{
"code": null,
"e": 1230,
"s": 1180,
"text": "Let us first create a collection with documents −"
},
{
"code": null,
"e": 1806,
"s": 1230,
"text": "> db.regularExpressionDemo.insertOne({\"UserName\":\"John\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdffc25bf3115999ed51210\")\n}\n> db.regularExpressionDemo.insertOne({\"UserName\":\"JOHN\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdffc2ebf3115999ed51211\")\n}\n> db.regularExpressionDemo.insertOne({\"UserName\":\"john\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdffc35bf3115999ed51212\")\n}\n> db.regularExpressionDemo.insertOne({\"UserName\":\"JoHn\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdffc3ebf3115999ed51213\")\n}"
},
{
"code": null,
"e": 1905,
"s": 1806,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1940,
"s": 1905,
"text": "> db.regularExpressionDemo.find();"
},
{
"code": null,
"e": 1981,
"s": 1940,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2261,
"s": 1981,
"text": "{ \"_id\" : ObjectId(\"5cdffc25bf3115999ed51210\"), \"UserName\" : \"John\" }\n{ \"_id\" : ObjectId(\"5cdffc2ebf3115999ed51211\"), \"UserName\" : \"JOHN\" }\n{ \"_id\" : ObjectId(\"5cdffc35bf3115999ed51212\"), \"UserName\" : \"john\" }\n{ \"_id\" : ObjectId(\"5cdffc3ebf3115999ed51213\"), \"UserName\" : \"JoHn\" }"
},
{
"code": null,
"e": 2300,
"s": 2261,
"text": "Following is the query to use $regex −"
},
{
"code": null,
"e": 2366,
"s": 2300,
"text": "> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN'}});"
},
{
"code": null,
"e": 2407,
"s": 2366,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2477,
"s": 2407,
"text": "{ \"_id\" : ObjectId(\"5cdffc2ebf3115999ed51211\"), \"UserName\" : \"JOHN\" }"
},
{
"code": null,
"e": 2534,
"s": 2477,
"text": "Let us now match all the cases. Following is the query −"
},
{
"code": null,
"e": 2616,
"s": 2534,
"text": "> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN', $options: 'i' }});"
},
{
"code": null,
"e": 2657,
"s": 2616,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2937,
"s": 2657,
"text": "{ \"_id\" : ObjectId(\"5cdffc25bf3115999ed51210\"), \"UserName\" : \"John\" }\n{ \"_id\" : ObjectId(\"5cdffc2ebf3115999ed51211\"), \"UserName\" : \"JOHN\" }\n{ \"_id\" : ObjectId(\"5cdffc35bf3115999ed51212\"), \"UserName\" : \"john\" }\n{ \"_id\" : ObjectId(\"5cdffc3ebf3115999ed51213\"), \"UserName\" : \"JoHn\" }"
}
] |
How to run a node.js app as a background service ? - GeeksforGeeks | 19 Feb, 2021
Node. js is a platform built on Chrome’s JavaScript v8 engine, which is used for easily building fast and scalable network applications, javascript uses an event-driven, non-blocking I/O model that makes it lightweight and efficient which is perfect for data-intensive real-time applications that run across distributed devices and to make use of the tools (or packages) in Node. js, we need to be able to install in our machine and manage them in a useful way.
To run a node.js app as a background service is to even after closing the node terminal, the app server needs to be kept running.
Methods to run node.js app as background service:
Method 1: The easiest method to make a node.js app run as a background service is to use the forever tool. The forever is a simple Command Line Interface Tool that ensures that a given particular script runs continuously without any interaction.
Command for Installation: The following command installs the forever tool in the app.
$ npm install forever -g
Example of Installation of forever
Command to Start forever: To start the forever tool, run the following commands replacing <app_name> with the name of the node.js app.
$ forever start /<app_name>/index.js
Example of Starting forever
Method 2: The second method involves create a service file and manually starting the app and enabling the service to keep it running in the background.
Step 1: Create a new file <app_name>.service file replacing <app_name> with the name of the node.js app. Inside the files, enter the following values:ExecStart=/var/www/<app_name>/app.js
Restart=always
User=nobody
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/<app_name>
Step 1: Create a new file <app_name>.service file replacing <app_name> with the name of the node.js app. Inside the files, enter the following values:
ExecStart=/var/www/<app_name>/app.js
Restart=always
User=nobody
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/<app_name>
Step 2: After configuring the service file,Copy the <app_name>.service file into the /etc/systemd/system.
Step 2: After configuring the service file,
Copy the <app_name>.service file into the /etc/systemd/system.
Step3: Start the app with the following command to make it run with the service file:systemctl start <app_name>
Step3: Start the app with the following command to make it run with the service file:
systemctl start <app_name>
Method 3: Another method which can be used to run a node.js app as a background by using nohup. The nohup is another Command Line Interface Tool which can be used to run a node.js app as a background service.
Run the following command to start the nohup replacing the <app_name> with the name of the node.js app:
$ nohup node /<app_name>/index.js &
The nohup command does not terminate this process even then the command terminal is closed.
Example of using nohup
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Difference between npm i and npm ci in Node.js
Express.js req.params Property
Mongoose Populate() Method
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 ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Angular Libraries For Web Developers | [
{
"code": null,
"e": 24842,
"s": 24814,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 25304,
"s": 24842,
"text": "Node. js is a platform built on Chrome’s JavaScript v8 engine, which is used for easily building fast and scalable network applications, javascript uses an event-driven, non-blocking I/O model that makes it lightweight and efficient which is perfect for data-intensive real-time applications that run across distributed devices and to make use of the tools (or packages) in Node. js, we need to be able to install in our machine and manage them in a useful way."
},
{
"code": null,
"e": 25434,
"s": 25304,
"text": "To run a node.js app as a background service is to even after closing the node terminal, the app server needs to be kept running."
},
{
"code": null,
"e": 25484,
"s": 25434,
"text": "Methods to run node.js app as background service:"
},
{
"code": null,
"e": 25730,
"s": 25484,
"text": "Method 1: The easiest method to make a node.js app run as a background service is to use the forever tool. The forever is a simple Command Line Interface Tool that ensures that a given particular script runs continuously without any interaction."
},
{
"code": null,
"e": 25816,
"s": 25730,
"text": "Command for Installation: The following command installs the forever tool in the app."
},
{
"code": null,
"e": 25841,
"s": 25816,
"text": "$ npm install forever -g"
},
{
"code": null,
"e": 25876,
"s": 25841,
"text": "Example of Installation of forever"
},
{
"code": null,
"e": 26011,
"s": 25876,
"text": "Command to Start forever: To start the forever tool, run the following commands replacing <app_name> with the name of the node.js app."
},
{
"code": null,
"e": 26048,
"s": 26011,
"text": "$ forever start /<app_name>/index.js"
},
{
"code": null,
"e": 26076,
"s": 26048,
"text": "Example of Starting forever"
},
{
"code": null,
"e": 26228,
"s": 26076,
"text": "Method 2: The second method involves create a service file and manually starting the app and enabling the service to keep it running in the background."
},
{
"code": null,
"e": 26566,
"s": 26228,
"text": "Step 1: Create a new file <app_name>.service file replacing <app_name> with the name of the node.js app. Inside the files, enter the following values:ExecStart=/var/www/<app_name>/app.js\nRestart=always\nUser=nobody\nGroup=nogroup\nEnvironment=PATH=/usr/bin:/usr/local/bin\nEnvironment=NODE_ENV=production\nWorkingDirectory=/var/www/<app_name>"
},
{
"code": null,
"e": 26717,
"s": 26566,
"text": "Step 1: Create a new file <app_name>.service file replacing <app_name> with the name of the node.js app. Inside the files, enter the following values:"
},
{
"code": null,
"e": 26905,
"s": 26717,
"text": "ExecStart=/var/www/<app_name>/app.js\nRestart=always\nUser=nobody\nGroup=nogroup\nEnvironment=PATH=/usr/bin:/usr/local/bin\nEnvironment=NODE_ENV=production\nWorkingDirectory=/var/www/<app_name>"
},
{
"code": null,
"e": 27011,
"s": 26905,
"text": "Step 2: After configuring the service file,Copy the <app_name>.service file into the /etc/systemd/system."
},
{
"code": null,
"e": 27055,
"s": 27011,
"text": "Step 2: After configuring the service file,"
},
{
"code": null,
"e": 27118,
"s": 27055,
"text": "Copy the <app_name>.service file into the /etc/systemd/system."
},
{
"code": null,
"e": 27230,
"s": 27118,
"text": "Step3: Start the app with the following command to make it run with the service file:systemctl start <app_name>"
},
{
"code": null,
"e": 27316,
"s": 27230,
"text": "Step3: Start the app with the following command to make it run with the service file:"
},
{
"code": null,
"e": 27343,
"s": 27316,
"text": "systemctl start <app_name>"
},
{
"code": null,
"e": 27552,
"s": 27343,
"text": "Method 3: Another method which can be used to run a node.js app as a background by using nohup. The nohup is another Command Line Interface Tool which can be used to run a node.js app as a background service."
},
{
"code": null,
"e": 27656,
"s": 27552,
"text": "Run the following command to start the nohup replacing the <app_name> with the name of the node.js app:"
},
{
"code": null,
"e": 27692,
"s": 27656,
"text": "$ nohup node /<app_name>/index.js &"
},
{
"code": null,
"e": 27784,
"s": 27692,
"text": "The nohup command does not terminate this process even then the command terminal is closed."
},
{
"code": null,
"e": 27807,
"s": 27784,
"text": "Example of using nohup"
},
{
"code": null,
"e": 27824,
"s": 27807,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 27831,
"s": 27824,
"text": "Picked"
},
{
"code": null,
"e": 27839,
"s": 27831,
"text": "Node.js"
},
{
"code": null,
"e": 27856,
"s": 27839,
"text": "Web Technologies"
},
{
"code": null,
"e": 27954,
"s": 27856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27963,
"s": 27954,
"text": "Comments"
},
{
"code": null,
"e": 27976,
"s": 27963,
"text": "Old Comments"
},
{
"code": null,
"e": 28013,
"s": 27976,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 28045,
"s": 28013,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 28092,
"s": 28045,
"text": "Difference between npm i and npm ci in Node.js"
},
{
"code": null,
"e": 28123,
"s": 28092,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 28150,
"s": 28123,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 28192,
"s": 28150,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28254,
"s": 28192,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28297,
"s": 28254,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28347,
"s": 28297,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Design Patterns - Prototype Pattern | Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.
We're going to create an abstract class Shape and concrete classes extending the Shape class. A class ShapeCache is defined as a next step which stores shape objects in a Hashtable and returns their clone when requested.
PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape object.
Create an abstract class implementing Clonable interface.
Shape.java
public abstract class Shape implements Cloneable {
private String id;
protected String type;
abstract void draw();
public String getType(){
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
Create concrete classes extending the above class.
Rectangle.java
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
public class Square extends Shape {
public Square(){
type = "Square";
}
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
public class Circle extends Shape {
public Circle(){
type = "Circle";
}
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
Create a class to get concrete classes from database and store them in a Hashtable.
ShapeCache.java
import java.util.Hashtable;
public class ShapeCache {
private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>();
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
// for each shape run database query and create shape
// shapeMap.put(shapeKey, shape);
// for example, we are adding three shapes
public static void loadCache() {
Circle circle = new Circle();
circle.setId("1");
shapeMap.put(circle.getId(),circle);
Square square = new Square();
square.setId("2");
shapeMap.put(square.getId(),square);
Rectangle rectangle = new Rectangle();
rectangle.setId("3");
shapeMap.put(rectangle.getId(), rectangle);
}
}
PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in a Hashtable.
PrototypePatternDemo.java
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape clonedShape = (Shape) ShapeCache.getShape("1");
System.out.println("Shape : " + clonedShape.getType());
Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
System.out.println("Shape : " + clonedShape2.getType());
Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
System.out.println("Shape : " + clonedShape3.getType());
}
}
Verify the output.
Shape : Circle
Shape : Square
Shape : Rectangle
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2966,
"s": 2751,
"text": "Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object."
},
{
"code": null,
"e": 3348,
"s": 2966,
"text": "This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls."
},
{
"code": null,
"e": 3570,
"s": 3348,
"text": "We're going to create an abstract class Shape and concrete classes extending the Shape class. A class ShapeCache is defined as a next step which stores shape objects in a Hashtable and returns their clone when requested."
},
{
"code": null,
"e": 3655,
"s": 3570,
"text": "PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape object."
},
{
"code": null,
"e": 3713,
"s": 3655,
"text": "Create an abstract class implementing Clonable interface."
},
{
"code": null,
"e": 3724,
"s": 3713,
"text": "Shape.java"
},
{
"code": null,
"e": 4266,
"s": 3724,
"text": "public abstract class Shape implements Cloneable {\n \n private String id;\n protected String type;\n \n abstract void draw();\n \n public String getType(){\n return type;\n }\n \n public String getId() {\n return id;\n }\n \n public void setId(String id) {\n this.id = id;\n }\n \n public Object clone() {\n Object clone = null;\n \n try {\n clone = super.clone();\n \n } catch (CloneNotSupportedException e) {\n e.printStackTrace();\n }\n \n return clone;\n }\n}"
},
{
"code": null,
"e": 4317,
"s": 4266,
"text": "Create concrete classes extending the above class."
},
{
"code": null,
"e": 4332,
"s": 4317,
"text": "Rectangle.java"
},
{
"code": null,
"e": 4532,
"s": 4332,
"text": "public class Rectangle extends Shape {\n\n public Rectangle(){\n type = \"Rectangle\";\n }\n\n @Override\n public void draw() {\n System.out.println(\"Inside Rectangle::draw() method.\");\n }\n}"
},
{
"code": null,
"e": 4544,
"s": 4532,
"text": "Square.java"
},
{
"code": null,
"e": 4732,
"s": 4544,
"text": "public class Square extends Shape {\n\n public Square(){\n type = \"Square\";\n }\n\n @Override\n public void draw() {\n System.out.println(\"Inside Square::draw() method.\");\n }\n}"
},
{
"code": null,
"e": 4744,
"s": 4732,
"text": "Circle.java"
},
{
"code": null,
"e": 4932,
"s": 4744,
"text": "public class Circle extends Shape {\n\n public Circle(){\n type = \"Circle\";\n }\n\n @Override\n public void draw() {\n System.out.println(\"Inside Circle::draw() method.\");\n }\n}"
},
{
"code": null,
"e": 5016,
"s": 4932,
"text": "Create a class to get concrete classes from database and store them in a Hashtable."
},
{
"code": null,
"e": 5032,
"s": 5016,
"text": "ShapeCache.java"
},
{
"code": null,
"e": 5844,
"s": 5032,
"text": "import java.util.Hashtable;\n\npublic class ShapeCache {\n\t\n private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>();\n\n public static Shape getShape(String shapeId) {\n Shape cachedShape = shapeMap.get(shapeId);\n return (Shape) cachedShape.clone();\n }\n\n // for each shape run database query and create shape\n // shapeMap.put(shapeKey, shape);\n // for example, we are adding three shapes\n \n public static void loadCache() {\n Circle circle = new Circle();\n circle.setId(\"1\");\n shapeMap.put(circle.getId(),circle);\n\n Square square = new Square();\n square.setId(\"2\");\n shapeMap.put(square.getId(),square);\n\n Rectangle rectangle = new Rectangle();\n rectangle.setId(\"3\");\n shapeMap.put(rectangle.getId(), rectangle);\n }\n}"
},
{
"code": null,
"e": 5935,
"s": 5844,
"text": "PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in a Hashtable."
},
{
"code": null,
"e": 5961,
"s": 5935,
"text": "PrototypePatternDemo.java"
},
{
"code": null,
"e": 6457,
"s": 5961,
"text": "public class PrototypePatternDemo {\n public static void main(String[] args) {\n ShapeCache.loadCache();\n\n Shape clonedShape = (Shape) ShapeCache.getShape(\"1\");\n System.out.println(\"Shape : \" + clonedShape.getType());\t\t\n\n Shape clonedShape2 = (Shape) ShapeCache.getShape(\"2\");\n System.out.println(\"Shape : \" + clonedShape2.getType());\t\t\n\n Shape clonedShape3 = (Shape) ShapeCache.getShape(\"3\");\n System.out.println(\"Shape : \" + clonedShape3.getType());\t\t\n }\n}"
},
{
"code": null,
"e": 6476,
"s": 6457,
"text": "Verify the output."
},
{
"code": null,
"e": 6525,
"s": 6476,
"text": "Shape : Circle\nShape : Square\nShape : Rectangle\n"
},
{
"code": null,
"e": 6560,
"s": 6525,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6579,
"s": 6560,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6612,
"s": 6579,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6631,
"s": 6612,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6664,
"s": 6631,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6683,
"s": 6664,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6718,
"s": 6683,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6731,
"s": 6718,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 6763,
"s": 6731,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6776,
"s": 6763,
"text": " Zach Miller"
},
{
"code": null,
"e": 6809,
"s": 6776,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6823,
"s": 6809,
"text": " Sasha Miller"
},
{
"code": null,
"e": 6830,
"s": 6823,
"text": " Print"
},
{
"code": null,
"e": 6841,
"s": 6830,
"text": " Add Notes"
}
] |
Python - Get Nth column elements in Tuple Strings - GeeksforGeeks | 29 Dec, 2019
Yet another peculiar problem which might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This articles solves problem of extracting only the Nth index element of each string in tuple. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehensionAlmost every problem can be solved using list comprehension as a shorthand to naive approach and this problem isn’t an exception. In this, we just iterate through each list picking just the Nth index element to build the resultant list.
# Python3 code to demonstrate# Nth column in Tuple Strings# using list comprehension # initializing tupletest_tuple = ('GfG', 'for', 'Geeks') # initializing N N = 1 # printing original tuple print("The original tuple : " + str(test_tuple)) # using list comprehsion# Nth column in Tuple Stringsres = list(sub[N] for sub in test_tuple) # print resultprint("The Nth index string character list : " + str(res))
The original tuple : ('GfG', 'for', 'Geeks')
The Nth index string character list : ['f', 'o', 'e']
Method #2 : Using next() + zip()This particular task can also be performed using the combination of above two in more efficient way, using the iterators to do this task. The zip function can be used bind together the string elements.
# Python3 code to demonstrate# Nth column in Tuple Strings# using next() + zip() # initializing tupletest_tuple = ('GfG', 'for', 'Geeks') # printing original tuple print("The original tuple : " + str(test_tuple)) # initializing N N = 1 # using next() + zip()# Nth column in Tuple Stringstemp = zip(*test_tuple)for idx in range(0, N): next(temp)res = list(next(temp)) # print resultprint("The Nth index string character list : " + str(res))
The original tuple : ('GfG', 'for', 'Geeks')
The Nth index string character list : ['f', 'o', 'e']
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n29 Dec, 2019"
},
{
"code": null,
"e": 24617,
"s": 24212,
"text": "Yet another peculiar problem which might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This articles solves problem of extracting only the Nth index element of each string in tuple. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 24890,
"s": 24617,
"text": "Method #1 : Using list comprehensionAlmost every problem can be solved using list comprehension as a shorthand to naive approach and this problem isn’t an exception. In this, we just iterate through each list picking just the Nth index element to build the resultant list."
},
{
"code": "# Python3 code to demonstrate# Nth column in Tuple Strings# using list comprehension # initializing tupletest_tuple = ('GfG', 'for', 'Geeks') # initializing N N = 1 # printing original tuple print(\"The original tuple : \" + str(test_tuple)) # using list comprehsion# Nth column in Tuple Stringsres = list(sub[N] for sub in test_tuple) # print resultprint(\"The Nth index string character list : \" + str(res))",
"e": 25302,
"s": 24890,
"text": null
},
{
"code": null,
"e": 25402,
"s": 25302,
"text": "The original tuple : ('GfG', 'for', 'Geeks')\nThe Nth index string character list : ['f', 'o', 'e']\n"
},
{
"code": null,
"e": 25638,
"s": 25404,
"text": "Method #2 : Using next() + zip()This particular task can also be performed using the combination of above two in more efficient way, using the iterators to do this task. The zip function can be used bind together the string elements."
},
{
"code": "# Python3 code to demonstrate# Nth column in Tuple Strings# using next() + zip() # initializing tupletest_tuple = ('GfG', 'for', 'Geeks') # printing original tuple print(\"The original tuple : \" + str(test_tuple)) # initializing N N = 1 # using next() + zip()# Nth column in Tuple Stringstemp = zip(*test_tuple)for idx in range(0, N): next(temp)res = list(next(temp)) # print resultprint(\"The Nth index string character list : \" + str(res))",
"e": 26086,
"s": 25638,
"text": null
},
{
"code": null,
"e": 26186,
"s": 26086,
"text": "The original tuple : ('GfG', 'for', 'Geeks')\nThe Nth index string character list : ['f', 'o', 'e']\n"
},
{
"code": null,
"e": 26207,
"s": 26186,
"text": "Python list-programs"
},
{
"code": null,
"e": 26214,
"s": 26207,
"text": "Python"
},
{
"code": null,
"e": 26230,
"s": 26214,
"text": "Python Programs"
},
{
"code": null,
"e": 26328,
"s": 26230,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26337,
"s": 26328,
"text": "Comments"
},
{
"code": null,
"e": 26350,
"s": 26337,
"text": "Old Comments"
},
{
"code": null,
"e": 26382,
"s": 26350,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26438,
"s": 26382,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26459,
"s": 26438,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26498,
"s": 26459,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26540,
"s": 26498,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26562,
"s": 26540,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26601,
"s": 26562,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26647,
"s": 26601,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26685,
"s": 26647,
"text": "Python | Convert a list to dictionary"
}
] |
Building an Image Captioning Model with Keras | by Eunjoo Byeon | Towards Data Science | I have been working on an exploratory project to build a conceptual description model that generates interpretation for artworks. To begin, I started using a CNN-LSTM architecture that can work as a simple caption generator. In this post, I will describe how to build a basic CNN-LSTM architecture to create a model that can output text caption based on images. Please stay tuned for more on my project later.
The main approach to this image captioning is in three parts: 1. to use a pre-trained object-recognition network to get features from images and 2. to map these extracted feature embeddings to text sequences, then lastly 3. to use the long-short term memory (LSTM) to predict the word that follows a sequence given the map of features and text sequence.
This is a supervised network where we are mapping the image to a set of specific captions. So we need a set of data that has images and captions. Here are a few datasets that are publicly available to explore.
Flickr30K Dataset: Bryan Plummer and his colleagues' work of 30,000 images from Flickr and multiple corresponding descriptions.
Conceptual Captions Dataset: Google AI’s effort to collect conceptual caption from the web. It contains captions and URL links for more than 3 million images.
I will not go into details of how to download or resize images here. I have resized all images to fit within 500x500 pixels and in the jpg format. Each file name should be an identifying ID that links the file to image descriptions.
The first step is to extract features using a pre-trained network. This code takes the local directory containing jpg files and outputs the reference dictionary that has an image ID as a key and the feature embedding as its value.
This process may take a while, so I added a code that lets you dump the progress on a local drive at every 1000 iterations.
The accompanying captions need to be preprocessed. This function assumes that the set of description takes the format of a list with nested tuples (id, description). Some images may have more than one description associated with them, and each pair should be represented as a separate tuple. In this step, we are also adding special words in each sentence to mark the beginning and the end of the sequence (seqini and seqfin).
[(id1, 'description1-1'), (id1, 'description1-2'), (id2, 'description2-1') ... ]
Additionally, I added a function that randomly selects n numbers of descriptions, so I can set the maximum number of captions, in case there are way too many captions per some images.
This function converts the list of description tuples into a dictionary of preprocessed descriptions in the below format:
{ 'id1': ['description1-1', 'description1-2', ...], 'id2': ... } # or{ 'id1': 'description1', 'id2': 'description2 }
Now that we have our dataset, let’s divide them into train, validation, test sets (here I’m dividing it into 7:1.5:1.5).
from sklearn.model_selection import train_test_splittrain_list, test_list = train_test_split(list(descriptions.keys()), test_size = 0.3)val_list, test_list = train_test_split(test_list, test_size = 0.5)
To recap, now we have three lists of ids for a train set, test set, and a validation set. We also have a description dictionary and a feature dictionary. Now we need to convert the description into a sequence. For example, let’s say an image with an id of 1234 has a description that says “dog is running”. This needs to be broken down into input and output sets as below:
1234: [seqini] → [dog]
1234: [seqini][dog] → [is]
1234: [seqini][dog][is] → [running]
1234: [seqini][dog][is][running] → [seqfin]
But not only do we need to tokenize the sentence into text sequences, but we also need to map these into the integer labels. So for instance, let’s say our entire corpus has these unique words: [seqini, fast, dog, is, running, seqfin]. We can map these to an integer map: [0, 1, 2, 3, 4, 5]. This will result in the below sets:
1234: [0] → [2]
1234: [0, 2] → [3]
1234: [0, 2, 3] → [4]
1234: [0, 2, 3, 4] → [5]
So the logic is to assign unique words in the entire training description set to unique indices to create a text to sequence map. Then we iterate through each of the descriptions to tokenize them, create subsets (input → output) of sequence development, then convert them into an integer sequence. Since we use several variables created during the training set to process the test set, I put them all into a sequence generator object class.
This will return the two sets of inputs and one set of output for each training and validation set.
Now let’s train the model using Keras. As mentioned in the approach, the idea is to train the sequence of words through the LSTM layers so it can derive the best possible word (actually a number assigned to a word) that would follow the sequence.
Predicting a test image follows the above steps backward. You compute the feature embedding for the test image and feed it into the model with the initial sequence, which is an integer representation of the initiating word ‘seqini’. Then you take the prediction, add it to the sequence, and feed it into the model again, and repeats until the model predicts the integer sequence for the ending word ‘seqfin’. Then using the tokenizer, we convert the integers back to the mapped vocabularies. The below function will make a prediction given an image id.
Evaluating a machine-generated caption is not really straightforward as we can imagine. Instead, we can look at how well the n-grams of the prediction match the reference captions. This measure is called the BLEU (Bilingual Evaluation Understudy) Score. The idea is to take the average of the percentage of 1- to 4-grams within the reference descriptions that were found in the machine-generated captions, then to apply a penalty for texts that may inflate the percentage.
from nltk.translate.bleu_score import corpus_bleubleu_1 = corpus_bleu(references, # list (or next list) predictions, # list weights = (1, 0, 0, 0)) # 1-4 grams weights
We looked at how to create an image captioning model using CNN-LSTM architecture. For humans, describing the visual scene involves a different level of language representation and the perception that depends on one’s past experience and current context. Also developing a sentence sequence in human cognition might not be actually ‘sequential’, as the syntax does not directly match the visual saliency. So there are some important distinctions that can be taken into consideration to push this model further for more successful and human-like performance. | [
{
"code": null,
"e": 582,
"s": 172,
"text": "I have been working on an exploratory project to build a conceptual description model that generates interpretation for artworks. To begin, I started using a CNN-LSTM architecture that can work as a simple caption generator. In this post, I will describe how to build a basic CNN-LSTM architecture to create a model that can output text caption based on images. Please stay tuned for more on my project later."
},
{
"code": null,
"e": 936,
"s": 582,
"text": "The main approach to this image captioning is in three parts: 1. to use a pre-trained object-recognition network to get features from images and 2. to map these extracted feature embeddings to text sequences, then lastly 3. to use the long-short term memory (LSTM) to predict the word that follows a sequence given the map of features and text sequence."
},
{
"code": null,
"e": 1146,
"s": 936,
"text": "This is a supervised network where we are mapping the image to a set of specific captions. So we need a set of data that has images and captions. Here are a few datasets that are publicly available to explore."
},
{
"code": null,
"e": 1274,
"s": 1146,
"text": "Flickr30K Dataset: Bryan Plummer and his colleagues' work of 30,000 images from Flickr and multiple corresponding descriptions."
},
{
"code": null,
"e": 1433,
"s": 1274,
"text": "Conceptual Captions Dataset: Google AI’s effort to collect conceptual caption from the web. It contains captions and URL links for more than 3 million images."
},
{
"code": null,
"e": 1666,
"s": 1433,
"text": "I will not go into details of how to download or resize images here. I have resized all images to fit within 500x500 pixels and in the jpg format. Each file name should be an identifying ID that links the file to image descriptions."
},
{
"code": null,
"e": 1897,
"s": 1666,
"text": "The first step is to extract features using a pre-trained network. This code takes the local directory containing jpg files and outputs the reference dictionary that has an image ID as a key and the feature embedding as its value."
},
{
"code": null,
"e": 2021,
"s": 1897,
"text": "This process may take a while, so I added a code that lets you dump the progress on a local drive at every 1000 iterations."
},
{
"code": null,
"e": 2448,
"s": 2021,
"text": "The accompanying captions need to be preprocessed. This function assumes that the set of description takes the format of a list with nested tuples (id, description). Some images may have more than one description associated with them, and each pair should be represented as a separate tuple. In this step, we are also adding special words in each sentence to mark the beginning and the end of the sequence (seqini and seqfin)."
},
{
"code": null,
"e": 2529,
"s": 2448,
"text": "[(id1, 'description1-1'), (id1, 'description1-2'), (id2, 'description2-1') ... ]"
},
{
"code": null,
"e": 2713,
"s": 2529,
"text": "Additionally, I added a function that randomly selects n numbers of descriptions, so I can set the maximum number of captions, in case there are way too many captions per some images."
},
{
"code": null,
"e": 2835,
"s": 2713,
"text": "This function converts the list of description tuples into a dictionary of preprocessed descriptions in the below format:"
},
{
"code": null,
"e": 2952,
"s": 2835,
"text": "{ 'id1': ['description1-1', 'description1-2', ...], 'id2': ... } # or{ 'id1': 'description1', 'id2': 'description2 }"
},
{
"code": null,
"e": 3073,
"s": 2952,
"text": "Now that we have our dataset, let’s divide them into train, validation, test sets (here I’m dividing it into 7:1.5:1.5)."
},
{
"code": null,
"e": 3276,
"s": 3073,
"text": "from sklearn.model_selection import train_test_splittrain_list, test_list = train_test_split(list(descriptions.keys()), test_size = 0.3)val_list, test_list = train_test_split(test_list, test_size = 0.5)"
},
{
"code": null,
"e": 3649,
"s": 3276,
"text": "To recap, now we have three lists of ids for a train set, test set, and a validation set. We also have a description dictionary and a feature dictionary. Now we need to convert the description into a sequence. For example, let’s say an image with an id of 1234 has a description that says “dog is running”. This needs to be broken down into input and output sets as below:"
},
{
"code": null,
"e": 3672,
"s": 3649,
"text": "1234: [seqini] → [dog]"
},
{
"code": null,
"e": 3699,
"s": 3672,
"text": "1234: [seqini][dog] → [is]"
},
{
"code": null,
"e": 3735,
"s": 3699,
"text": "1234: [seqini][dog][is] → [running]"
},
{
"code": null,
"e": 3779,
"s": 3735,
"text": "1234: [seqini][dog][is][running] → [seqfin]"
},
{
"code": null,
"e": 4107,
"s": 3779,
"text": "But not only do we need to tokenize the sentence into text sequences, but we also need to map these into the integer labels. So for instance, let’s say our entire corpus has these unique words: [seqini, fast, dog, is, running, seqfin]. We can map these to an integer map: [0, 1, 2, 3, 4, 5]. This will result in the below sets:"
},
{
"code": null,
"e": 4123,
"s": 4107,
"text": "1234: [0] → [2]"
},
{
"code": null,
"e": 4142,
"s": 4123,
"text": "1234: [0, 2] → [3]"
},
{
"code": null,
"e": 4164,
"s": 4142,
"text": "1234: [0, 2, 3] → [4]"
},
{
"code": null,
"e": 4189,
"s": 4164,
"text": "1234: [0, 2, 3, 4] → [5]"
},
{
"code": null,
"e": 4630,
"s": 4189,
"text": "So the logic is to assign unique words in the entire training description set to unique indices to create a text to sequence map. Then we iterate through each of the descriptions to tokenize them, create subsets (input → output) of sequence development, then convert them into an integer sequence. Since we use several variables created during the training set to process the test set, I put them all into a sequence generator object class."
},
{
"code": null,
"e": 4730,
"s": 4630,
"text": "This will return the two sets of inputs and one set of output for each training and validation set."
},
{
"code": null,
"e": 4977,
"s": 4730,
"text": "Now let’s train the model using Keras. As mentioned in the approach, the idea is to train the sequence of words through the LSTM layers so it can derive the best possible word (actually a number assigned to a word) that would follow the sequence."
},
{
"code": null,
"e": 5530,
"s": 4977,
"text": "Predicting a test image follows the above steps backward. You compute the feature embedding for the test image and feed it into the model with the initial sequence, which is an integer representation of the initiating word ‘seqini’. Then you take the prediction, add it to the sequence, and feed it into the model again, and repeats until the model predicts the integer sequence for the ending word ‘seqfin’. Then using the tokenizer, we convert the integers back to the mapped vocabularies. The below function will make a prediction given an image id."
},
{
"code": null,
"e": 6003,
"s": 5530,
"text": "Evaluating a machine-generated caption is not really straightforward as we can imagine. Instead, we can look at how well the n-grams of the prediction match the reference captions. This measure is called the BLEU (Bilingual Evaluation Understudy) Score. The idea is to take the average of the percentage of 1- to 4-grams within the reference descriptions that were found in the machine-generated captions, then to apply a penalty for texts that may inflate the percentage."
},
{
"code": null,
"e": 6213,
"s": 6003,
"text": "from nltk.translate.bleu_score import corpus_bleubleu_1 = corpus_bleu(references, # list (or next list) predictions, # list weights = (1, 0, 0, 0)) # 1-4 grams weights "
}
] |
K-Means++ Implementation in Python and Spark | by Syed Sadat Nazrul | Towards Data Science | For this tutorial, we will be using PySpark, the Python wrapper for Apache Spark. While PySpark has a nice K-Means++ implementation, we will write our own one from scratch.
If you do not have PySpark on Jupyter Notebook, I found this tutorial useful:
blog.sicara.com
Before starting, ensure you have access to the weather station dataset:https://github.com/yoavfreund/UCSD_BigData_2016/tree/master/Data/Weather
def parse_data(row): ''' Parse each pandas row into a tuple of (station_name, feature_vec),`l where feature_vec is the concatenation of the projection vectors of TAVG, TRANGE, and SNWD. ''' return (row[0], np.concatenate([row[1], row[2], row[3]]))## Read datadata = pickle.load(open("stations_projections.pickle", "rb"))rdd = sc.parallelize([parse_data(row[1]) for row in data.iterrows()])
Let’s look at the first row:
rdd.take(1)
The name of the weather station is USC00044534 and the rest are the different weather information we will use for clustering.
import numpy as np import pickle import sys import timefrom numpy.linalg import norm from matplotlib import pyplot as plt
# Number of centroidsK = 5 # Number of K-means runs that are executed in parallel. Equivalently, number of sets of initial pointsRUNS = 25 # For reproducability of resultsRANDOM_SEED = 60295531 # The K-means algorithm is terminated when the change in the # location of the centroids is smaller than 0.1converge_dist = 0.1
The following functions will come in handy as we move forwards:
def print_log(s): ''' Print progress logs ''' sys.stdout.write(s + "\n") sys.stdout.flush()def compute_entropy(d): ''' Compute the entropy given the frequency vector `d` ''' d = np.array(d) d = 1.0 * d / d.sum() return -np.sum(d * np.log2(d))def choice(p): ''' Generates a random sample from [0, len(p)), where p[i] is the probability associated with i. ''' random = np.random.random() r = 0.0 for idx in range(len(p)): r = r + p[idx] if r > random: return idx assert(False)
For K-Means++, we wish to have the centroids as far apart as possible upon initialization. The idea is to have the centroids to be closer to the distinct cluster centers upon initialization and hence reach convergence faster.
def kmeans_init(rdd, K, RUNS, seed): ''' Select `RUNS` sets of initial points for `K`-means++ ''' # the `centers` variable is what we want to return n_data = rdd.count() shape = rdd.take(1)[0][1].shape[0] centers = np.zeros((RUNS, K, shape)) def update_dist(vec, dist, k): new_dist = norm(vec - centers[:, k], axis=1)**2 return np.min([dist, new_dist], axis=0) # The second element `dist` in the tuple below is the # closest distance from each data point to the selected # points in the initial set, where `dist[i]` is the # closest distance to the points in the i-th initial set data = (rdd .map(lambda p: (p, [np.inf] * RUNS)) \ .cache()) # Collect the feature vectors of all data points # beforehand, might be useful in the following # for-loop local_data = (rdd .map(lambda (name, vec): vec) .collect()) # Randomly select the first point for every run of # k-means++, i.e. randomly select `RUNS` points # and add it to the `centers` variable sample = [local_data[k] for k in np.random.randint(0, len(local_data), RUNS)] centers[:, 0] = sample for idx in range(K - 1): ######################################################## # In each iteration, you need to select one point for # each set of initial points (so select `RUNS` points # in total). For each data point x, let D_i(x) be the # distance between x and the nearest center that has # already been added to the i-th set. Choose a new # data point for i-th set using a weighted probability # where point x is chosen with probability proportional # to D_i(x)^2 . Repeat each data point by 25 times # (for each RUN) to get 12140x25 ######################################################## #Update distance data = (data .map(lambda ((name,vec),dist): ((name,vec),update_dist(vec,dist,idx))) .cache()) #Calculate sum of D_i(x)^2 d1 = data.map(lambda ((name,vec),dist): (1,dist)) d2 = d1.reduceByKey(lambda x,y: np.sum([x,y], axis=0)) total = d2.collect()[0][1] #Normalize each distance to get the probabilities and #reshapte to 12140x25 prob = (data .map(lambda ((name,vec),dist): np.divide(dist,total)) .collect()) prob = np.reshape(prob,(len(local_data), RUNS)) #K'th centroid for each run data_id = [choice(prob[:,i]) for i in xrange(RUNS)] sample = [local_data[i] for i in data_id] centers[:, idx+1] = sample return centers # The second element `dist` in the tuple below is the # closest distance from each data point to the selected # points in the initial set, where `dist[i]` is the # closest distance to the points in the i-th initial set data = (rdd .map(lambda p: (p, [np.inf] * RUNS)) \ .cache()) # Collect the feature vectors of all data points # beforehand, might be useful in the following # for-loop local_data = (rdd .map(lambda (name, vec): vec) .collect()) # Randomly select the first point for every run of # k-means++, i.e. randomly select `RUNS` points # and add it to the `centers` variable sample = [local_data[k] for k in np.random.randint(0, len(local_data), RUNS)] centers[:, 0] = sample for idx in range(K - 1): ######################################################## # In each iteration, you need to select one point for # each set of initial points (so select `RUNS` points # in total). For each data point x, let D_i(x) be the # distance between x and the nearest center that has # already been added to the i-th set. Choose a new # data point for i-th set using a weighted probability # where point x is chosen with probability proportional # to D_i(x)^2 . Repeat each data point by 25 times # (for each RUN) to get 12140x25 ######################################################## #Update distance data = (data .map(lambda ((name,vec),dist): ((name,vec),update_dist(vec,dist,idx))) .cache()) #Calculate sum of D_i(x)^2 d1 = data.map(lambda ((name,vec),dist): (1,dist)) d2 = d1.reduceByKey(lambda x,y: np.sum([x,y], axis=0)) total = d2.collect()[0][1] #Normalize each distance to get the probabilities and # reshape to 12140x25 prob = (data .map(lambda ((name,vec),dist): np.divide(dist,total)) .collect()) prob = np.reshape(prob,(len(local_data), RUNS)) #K'th centroid for each run data_id = [choice(prob[:,i]) for i in xrange(RUNS)] sample = [local_data[i] for i in data_id] centers[:, idx+1] = sample return centers
Now that we have the initialization function, we can now use this to implement the K-Means++ algorithm.
def get_closest(p, centers): ''' Return the indices the nearest centroids of `p`. `centers` contains sets of centroids, where `centers[i]` is the i-th set of centroids. ''' best = [0] * len(centers) closest = [np.inf] * len(centers) for idx in range(len(centers)): for j in range(len(centers[0])): temp_dist = norm(p - centers[idx][j]) if temp_dist < closest[idx]: closest[idx] = temp_dist best[idx] = j return bestdef kmeans(rdd, K, RUNS, converge_dist, seed): ''' Run K-means++ algorithm on `rdd`, where `RUNS` is the number of initial sets to use. ''' k_points = kmeans_init(rdd, K, RUNS, seed) print_log("Initialized.") temp_dist = 1.0 iters = 0 st = time.time() while temp_dist > converge_dist: # Update all `RUNS` sets of centroids using standard k-means # algorithm # Outline: # - For each point x, select its nearest centroid in i-th # centroids set # - Average all points that are assigned to the same # centroid # - Update the centroid with the average of all points # that are assigned to it temp_dist = np.max([ np.sum([norm(k_points[idx][j] - new_points[(idx, j)]) for idx,j in new_points.keys()]) ]) iters = iters + 1 if iters % 5 == 0: print_log("Iteration %d max shift: %.2f (time: %.2f)" % (iters, temp_dist, time.time() - st)) st = time.time() # update old centroids # You modify this for-loop to meet your need for ((idx, j), p) in new_points.items(): k_points[idx][j] = p return k_points
The beauty of K-Means++ over K-Means is its speed of convergence due to its initialization algorithm. Also, Spark is being used to parallelize this algorithm as much as possible. Hence, let use Benchmark this implementation.
st = time.time()np.random.seed(RANDOM_SEED)centroids = kmeans(rdd, K, RUNS, converge_dist, np.random.randint(1000))group = rdd.mapValues(lambda p: get_closest(p, centroids)) \ .collect()print "Time takes to converge:", time.time() - st
Depending on the number of processor cores, core memory set for each executor, and the number of executors used, this result will differ.
In order to verify the accuracy of the model, we need to pick a cost function and attempt to minimize it using the model. The final cost function will give us an idea for accuracy. For K-Means, we look at the distance between the datapoints and the nearest centroids.
def get_cost(rdd, centers): ''' Compute the square of l2 norm from each data point in `rdd` to the centroids in `centers` ''' def _get_cost(p, centers): best = [0] * len(centers) closest = [np.inf] * len(centers) for idx in range(len(centers)): for j in range(len(centers[0])): temp_dist = norm(p - centers[idx][j]) if temp_dist < closest[idx]: closest[idx] = temp_dist best[idx] = j return np.array(closest)**2 cost = rdd.map(lambda (name, v): _get_cost(v, centroids)).collect() return np.array(cost).sum(axis=0)cost = get_cost(rdd, centroids)log2 = np.log2print "Min Cost:\t"+str(log2(np.max(cost)))print "Max Cost:\t"+str(log2(np.min(cost)))print "Mean Cost:\t"+str(log2(np.mean(cost)))
Min Cost: 33.7575332525Max Cost: 33.8254902123Mean Cost: 33.7790236109
Here is the final result:
print 'entropy=',entropybest = np.argmin(cost)print 'best_centers=',list(centroids[best]) | [
{
"code": null,
"e": 344,
"s": 171,
"text": "For this tutorial, we will be using PySpark, the Python wrapper for Apache Spark. While PySpark has a nice K-Means++ implementation, we will write our own one from scratch."
},
{
"code": null,
"e": 422,
"s": 344,
"text": "If you do not have PySpark on Jupyter Notebook, I found this tutorial useful:"
},
{
"code": null,
"e": 438,
"s": 422,
"text": "blog.sicara.com"
},
{
"code": null,
"e": 582,
"s": 438,
"text": "Before starting, ensure you have access to the weather station dataset:https://github.com/yoavfreund/UCSD_BigData_2016/tree/master/Data/Weather"
},
{
"code": null,
"e": 1016,
"s": 582,
"text": "def parse_data(row): ''' Parse each pandas row into a tuple of (station_name, feature_vec),`l where feature_vec is the concatenation of the projection vectors of TAVG, TRANGE, and SNWD. ''' return (row[0], np.concatenate([row[1], row[2], row[3]]))## Read datadata = pickle.load(open(\"stations_projections.pickle\", \"rb\"))rdd = sc.parallelize([parse_data(row[1]) for row in data.iterrows()])"
},
{
"code": null,
"e": 1045,
"s": 1016,
"text": "Let’s look at the first row:"
},
{
"code": null,
"e": 1057,
"s": 1045,
"text": "rdd.take(1)"
},
{
"code": null,
"e": 1183,
"s": 1057,
"text": "The name of the weather station is USC00044534 and the rest are the different weather information we will use for clustering."
},
{
"code": null,
"e": 1305,
"s": 1183,
"text": "import numpy as np import pickle import sys import timefrom numpy.linalg import norm from matplotlib import pyplot as plt"
},
{
"code": null,
"e": 1629,
"s": 1305,
"text": "# Number of centroidsK = 5 # Number of K-means runs that are executed in parallel. Equivalently, number of sets of initial pointsRUNS = 25 # For reproducability of resultsRANDOM_SEED = 60295531 # The K-means algorithm is terminated when the change in the # location of the centroids is smaller than 0.1converge_dist = 0.1"
},
{
"code": null,
"e": 1693,
"s": 1629,
"text": "The following functions will come in handy as we move forwards:"
},
{
"code": null,
"e": 2251,
"s": 1693,
"text": "def print_log(s): ''' Print progress logs ''' sys.stdout.write(s + \"\\n\") sys.stdout.flush()def compute_entropy(d): ''' Compute the entropy given the frequency vector `d` ''' d = np.array(d) d = 1.0 * d / d.sum() return -np.sum(d * np.log2(d))def choice(p): ''' Generates a random sample from [0, len(p)), where p[i] is the probability associated with i. ''' random = np.random.random() r = 0.0 for idx in range(len(p)): r = r + p[idx] if r > random: return idx assert(False)"
},
{
"code": null,
"e": 2477,
"s": 2251,
"text": "For K-Means++, we wish to have the centroids as far apart as possible upon initialization. The idea is to have the centroids to be closer to the distinct cluster centers upon initialization and hence reach convergence faster."
},
{
"code": null,
"e": 7476,
"s": 2477,
"text": "def kmeans_init(rdd, K, RUNS, seed): ''' Select `RUNS` sets of initial points for `K`-means++ ''' # the `centers` variable is what we want to return n_data = rdd.count() shape = rdd.take(1)[0][1].shape[0] centers = np.zeros((RUNS, K, shape)) def update_dist(vec, dist, k): new_dist = norm(vec - centers[:, k], axis=1)**2 return np.min([dist, new_dist], axis=0) # The second element `dist` in the tuple below is the # closest distance from each data point to the selected # points in the initial set, where `dist[i]` is the # closest distance to the points in the i-th initial set data = (rdd .map(lambda p: (p, [np.inf] * RUNS)) \\ .cache()) # Collect the feature vectors of all data points # beforehand, might be useful in the following # for-loop local_data = (rdd .map(lambda (name, vec): vec) .collect()) # Randomly select the first point for every run of # k-means++, i.e. randomly select `RUNS` points # and add it to the `centers` variable sample = [local_data[k] for k in np.random.randint(0, len(local_data), RUNS)] centers[:, 0] = sample for idx in range(K - 1): ######################################################## # In each iteration, you need to select one point for # each set of initial points (so select `RUNS` points # in total). For each data point x, let D_i(x) be the # distance between x and the nearest center that has # already been added to the i-th set. Choose a new # data point for i-th set using a weighted probability # where point x is chosen with probability proportional # to D_i(x)^2 . Repeat each data point by 25 times # (for each RUN) to get 12140x25 ######################################################## #Update distance data = (data .map(lambda ((name,vec),dist): ((name,vec),update_dist(vec,dist,idx))) .cache()) #Calculate sum of D_i(x)^2 d1 = data.map(lambda ((name,vec),dist): (1,dist)) d2 = d1.reduceByKey(lambda x,y: np.sum([x,y], axis=0)) total = d2.collect()[0][1] #Normalize each distance to get the probabilities and #reshapte to 12140x25 prob = (data .map(lambda ((name,vec),dist): np.divide(dist,total)) .collect()) prob = np.reshape(prob,(len(local_data), RUNS)) #K'th centroid for each run data_id = [choice(prob[:,i]) for i in xrange(RUNS)] sample = [local_data[i] for i in data_id] centers[:, idx+1] = sample return centers # The second element `dist` in the tuple below is the # closest distance from each data point to the selected # points in the initial set, where `dist[i]` is the # closest distance to the points in the i-th initial set data = (rdd .map(lambda p: (p, [np.inf] * RUNS)) \\ .cache()) # Collect the feature vectors of all data points # beforehand, might be useful in the following # for-loop local_data = (rdd .map(lambda (name, vec): vec) .collect()) # Randomly select the first point for every run of # k-means++, i.e. randomly select `RUNS` points # and add it to the `centers` variable sample = [local_data[k] for k in np.random.randint(0, len(local_data), RUNS)] centers[:, 0] = sample for idx in range(K - 1): ######################################################## # In each iteration, you need to select one point for # each set of initial points (so select `RUNS` points # in total). For each data point x, let D_i(x) be the # distance between x and the nearest center that has # already been added to the i-th set. Choose a new # data point for i-th set using a weighted probability # where point x is chosen with probability proportional # to D_i(x)^2 . Repeat each data point by 25 times # (for each RUN) to get 12140x25 ######################################################## #Update distance data = (data .map(lambda ((name,vec),dist): ((name,vec),update_dist(vec,dist,idx))) .cache()) #Calculate sum of D_i(x)^2 d1 = data.map(lambda ((name,vec),dist): (1,dist)) d2 = d1.reduceByKey(lambda x,y: np.sum([x,y], axis=0)) total = d2.collect()[0][1] #Normalize each distance to get the probabilities and # reshape to 12140x25 prob = (data .map(lambda ((name,vec),dist): np.divide(dist,total)) .collect()) prob = np.reshape(prob,(len(local_data), RUNS)) #K'th centroid for each run data_id = [choice(prob[:,i]) for i in xrange(RUNS)] sample = [local_data[i] for i in data_id] centers[:, idx+1] = sample return centers"
},
{
"code": null,
"e": 7580,
"s": 7476,
"text": "Now that we have the initialization function, we can now use this to implement the K-Means++ algorithm."
},
{
"code": null,
"e": 9339,
"s": 7580,
"text": "def get_closest(p, centers): ''' Return the indices the nearest centroids of `p`. `centers` contains sets of centroids, where `centers[i]` is the i-th set of centroids. ''' best = [0] * len(centers) closest = [np.inf] * len(centers) for idx in range(len(centers)): for j in range(len(centers[0])): temp_dist = norm(p - centers[idx][j]) if temp_dist < closest[idx]: closest[idx] = temp_dist best[idx] = j return bestdef kmeans(rdd, K, RUNS, converge_dist, seed): ''' Run K-means++ algorithm on `rdd`, where `RUNS` is the number of initial sets to use. ''' k_points = kmeans_init(rdd, K, RUNS, seed) print_log(\"Initialized.\") temp_dist = 1.0 iters = 0 st = time.time() while temp_dist > converge_dist: # Update all `RUNS` sets of centroids using standard k-means # algorithm # Outline: # - For each point x, select its nearest centroid in i-th # centroids set # - Average all points that are assigned to the same # centroid # - Update the centroid with the average of all points # that are assigned to it temp_dist = np.max([ np.sum([norm(k_points[idx][j] - new_points[(idx, j)]) for idx,j in new_points.keys()]) ]) iters = iters + 1 if iters % 5 == 0: print_log(\"Iteration %d max shift: %.2f (time: %.2f)\" % (iters, temp_dist, time.time() - st)) st = time.time() # update old centroids # You modify this for-loop to meet your need for ((idx, j), p) in new_points.items(): k_points[idx][j] = p return k_points"
},
{
"code": null,
"e": 9564,
"s": 9339,
"text": "The beauty of K-Means++ over K-Means is its speed of convergence due to its initialization algorithm. Also, Spark is being used to parallelize this algorithm as much as possible. Hence, let use Benchmark this implementation."
},
{
"code": null,
"e": 9830,
"s": 9564,
"text": "st = time.time()np.random.seed(RANDOM_SEED)centroids = kmeans(rdd, K, RUNS, converge_dist, np.random.randint(1000))group = rdd.mapValues(lambda p: get_closest(p, centroids)) \\ .collect()print \"Time takes to converge:\", time.time() - st"
},
{
"code": null,
"e": 9968,
"s": 9830,
"text": "Depending on the number of processor cores, core memory set for each executor, and the number of executors used, this result will differ."
},
{
"code": null,
"e": 10236,
"s": 9968,
"text": "In order to verify the accuracy of the model, we need to pick a cost function and attempt to minimize it using the model. The final cost function will give us an idea for accuracy. For K-Means, we look at the distance between the datapoints and the nearest centroids."
},
{
"code": null,
"e": 11069,
"s": 10236,
"text": "def get_cost(rdd, centers): ''' Compute the square of l2 norm from each data point in `rdd` to the centroids in `centers` ''' def _get_cost(p, centers): best = [0] * len(centers) closest = [np.inf] * len(centers) for idx in range(len(centers)): for j in range(len(centers[0])): temp_dist = norm(p - centers[idx][j]) if temp_dist < closest[idx]: closest[idx] = temp_dist best[idx] = j return np.array(closest)**2 cost = rdd.map(lambda (name, v): _get_cost(v, centroids)).collect() return np.array(cost).sum(axis=0)cost = get_cost(rdd, centroids)log2 = np.log2print \"Min Cost:\\t\"+str(log2(np.max(cost)))print \"Max Cost:\\t\"+str(log2(np.min(cost)))print \"Mean Cost:\\t\"+str(log2(np.mean(cost)))"
},
{
"code": null,
"e": 11140,
"s": 11069,
"text": "Min Cost: 33.7575332525Max Cost: 33.8254902123Mean Cost: 33.7790236109"
},
{
"code": null,
"e": 11166,
"s": 11140,
"text": "Here is the final result:"
}
] |
jMeter - JMS Test Plan | In this chapter, we will learn how to write a simple test plan to test Java Messaging Service (JMS). JMS supports two types of messaging −
Point-to-Point messaging − Queue messaging is generally used for transactions where the sender expects a response. Messaging systems are quite different from normal HTTP requests. In HTTP, a single user sends a request and gets a response.
Point-to-Point messaging − Queue messaging is generally used for transactions where the sender expects a response. Messaging systems are quite different from normal HTTP requests. In HTTP, a single user sends a request and gets a response.
Topic messaging − Topic messages are commonly known as pub/sub messaging. Topic messaging is generally used in cases where a message is published by a producer and consumed by multiple subscribers.
Topic messaging − Topic messages are commonly known as pub/sub messaging. Topic messaging is generally used in cases where a message is published by a producer and consumed by multiple subscribers.
Let us see a test example for each of these. The pre-requisites for testing JMS are −
We use Apache ActiveMQ in the example. There are various JMS servers like IBM WebSphere MQ (formerly MQSeries), Tibco, etc. Download it from the binaries from the Apache ActiveMQ website.
We use Apache ActiveMQ in the example. There are various JMS servers like IBM WebSphere MQ (formerly MQSeries), Tibco, etc. Download it from the binaries from the Apache ActiveMQ website.
Unzip the archive, go to the decompressed directory, and run the following command from the command console to start the ActiveMQ server −
Unzip the archive, go to the decompressed directory, and run the following command from the command console to start the ActiveMQ server −
.\bin\activemq start
You can verify if the ActiveMQ server has started by visiting the admin interface at the following address http://localhost:8161/admin/. If it asks for authentication, then enter the userid and password as admin. The screen is similar as shown below −
Now copy the activemq-all-x.x.x.jar (XXX depending on the version) from the ActiveMQ unzipped directory to /home/manisha/apache-jmeter-2.9/lib.
Now copy the activemq-all-x.x.x.jar (XXX depending on the version) from the ActiveMQ unzipped directory to /home/manisha/apache-jmeter-2.9/lib.
With the above setup, let us build the test plan for −
JMS Point-to-Point Test Plan
JMS Point-to-Point Test Plan
JMS Topic Test Plan
JMS Topic Test Plan
59 Lectures
9.5 hours
Rahul Shetty
54 Lectures
13.5 hours
Wallace Tauriac
23 Lectures
1.5 hours
Anuja Jain
12 Lectures
1 hours
Spotle Learn
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2044,
"s": 1905,
"text": "In this chapter, we will learn how to write a simple test plan to test Java Messaging Service (JMS). JMS supports two types of messaging −"
},
{
"code": null,
"e": 2284,
"s": 2044,
"text": "Point-to-Point messaging − Queue messaging is generally used for transactions where the sender expects a response. Messaging systems are quite different from normal HTTP requests. In HTTP, a single user sends a request and gets a response."
},
{
"code": null,
"e": 2524,
"s": 2284,
"text": "Point-to-Point messaging − Queue messaging is generally used for transactions where the sender expects a response. Messaging systems are quite different from normal HTTP requests. In HTTP, a single user sends a request and gets a response."
},
{
"code": null,
"e": 2722,
"s": 2524,
"text": "Topic messaging − Topic messages are commonly known as pub/sub messaging. Topic messaging is generally used in cases where a message is published by a producer and consumed by multiple subscribers."
},
{
"code": null,
"e": 2920,
"s": 2722,
"text": "Topic messaging − Topic messages are commonly known as pub/sub messaging. Topic messaging is generally used in cases where a message is published by a producer and consumed by multiple subscribers."
},
{
"code": null,
"e": 3006,
"s": 2920,
"text": "Let us see a test example for each of these. The pre-requisites for testing JMS are −"
},
{
"code": null,
"e": 3195,
"s": 3006,
"text": "We use Apache ActiveMQ in the example. There are various JMS servers like IBM WebSphere MQ (formerly MQSeries), Tibco, etc. Download it from the binaries from the Apache ActiveMQ website."
},
{
"code": null,
"e": 3384,
"s": 3195,
"text": "We use Apache ActiveMQ in the example. There are various JMS servers like IBM WebSphere MQ (formerly MQSeries), Tibco, etc. Download it from the binaries from the Apache ActiveMQ website."
},
{
"code": null,
"e": 3523,
"s": 3384,
"text": "Unzip the archive, go to the decompressed directory, and run the following command from the command console to start the ActiveMQ server −"
},
{
"code": null,
"e": 3662,
"s": 3523,
"text": "Unzip the archive, go to the decompressed directory, and run the following command from the command console to start the ActiveMQ server −"
},
{
"code": null,
"e": 3685,
"s": 3662,
"text": ".\\bin\\activemq start\n"
},
{
"code": null,
"e": 3937,
"s": 3685,
"text": "You can verify if the ActiveMQ server has started by visiting the admin interface at the following address http://localhost:8161/admin/. If it asks for authentication, then enter the userid and password as admin. The screen is similar as shown below −"
},
{
"code": null,
"e": 4081,
"s": 3937,
"text": "Now copy the activemq-all-x.x.x.jar (XXX depending on the version) from the ActiveMQ unzipped directory to /home/manisha/apache-jmeter-2.9/lib."
},
{
"code": null,
"e": 4225,
"s": 4081,
"text": "Now copy the activemq-all-x.x.x.jar (XXX depending on the version) from the ActiveMQ unzipped directory to /home/manisha/apache-jmeter-2.9/lib."
},
{
"code": null,
"e": 4280,
"s": 4225,
"text": "With the above setup, let us build the test plan for −"
},
{
"code": null,
"e": 4309,
"s": 4280,
"text": "JMS Point-to-Point Test Plan"
},
{
"code": null,
"e": 4338,
"s": 4309,
"text": "JMS Point-to-Point Test Plan"
},
{
"code": null,
"e": 4358,
"s": 4338,
"text": "JMS Topic Test Plan"
},
{
"code": null,
"e": 4378,
"s": 4358,
"text": "JMS Topic Test Plan"
},
{
"code": null,
"e": 4413,
"s": 4378,
"text": "\n 59 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 4427,
"s": 4413,
"text": " Rahul Shetty"
},
{
"code": null,
"e": 4463,
"s": 4427,
"text": "\n 54 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 4480,
"s": 4463,
"text": " Wallace Tauriac"
},
{
"code": null,
"e": 4515,
"s": 4480,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4527,
"s": 4515,
"text": " Anuja Jain"
},
{
"code": null,
"e": 4560,
"s": 4527,
"text": "\n 12 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4574,
"s": 4560,
"text": " Spotle Learn"
},
{
"code": null,
"e": 4581,
"s": 4574,
"text": " Print"
},
{
"code": null,
"e": 4592,
"s": 4581,
"text": " Add Notes"
}
] |
Realtime prediction using Spark Structured Streaming, XGBoost and Scala | by Bogdan Cojocar | Towards Data Science | In this article we will discuss about building a complete machine learning pipeline. The first part will be focused on training a binary classifier in a standard batch mode and in the second part we will do some realtime prediction.
We will use data from the Titanic: Machine learning from disaster one of the many Kaggle competitions.
Before getting started please know that you should be familiar with Scala, Apache Spark and Xgboost.
All the source code will also be available on Github. Cool, now let’s get started!
We will train a XGBoost classifier using a ML pipeline in Spark. The classifier will be saved as an output and will be used in a Spark Structured Streaming realtime app to predict new test data.
Step 1: starting the spark session
We are creating a spark app that will run locally and will use as many threads as there are cores using local[*] :
val spark = SparkSession.builder() .appName("Spark XGBOOST Titanic Training") .master("local[*]") .getOrCreate()
Step 2: defining a schema
Next we define a schema of the data we read from the csv. This is usually a better practice than letting spark to infer the schema because it consumes less resources and we have total control over the fields.
val schema = StructType( Array(StructField("PassengerId", DoubleType), StructField("Survival", DoubleType), StructField("Pclass", DoubleType), StructField("Name", StringType), StructField("Sex", StringType), StructField("Age", DoubleType), StructField("SibSp", DoubleType), StructField("Parch", DoubleType), StructField("Ticket", StringType), StructField("Fare", DoubleType), StructField("Cabin", StringType), StructField("Embarked", StringType) ))
Step 3: reading the data
We read the csv into a DataFrame, making sure we mention we have a header.
val df_raw = spark .read .option("header", "true") .schema(schema) .csv(filePath)
Step 4: removing null values
All the null values are replaced with 0. This is not ideal, but for the purpose of this tutorial it’s ok.
val df = df_raw.na.fill(0)
Step 5: convert the nominal values to numeric
Before walking through the code on this step let’s go briefly through some Spark ML concepts. They introduce the concept of ML pipelines, which is a set of high level APIs build on top of the DataFrameswhich make it easier to combine multiple algorithms into a single process. The main elements of a pipeline are the Transformer and the Estimator. The first can represent an algorithm that can transform a DataFrame into another DataFrame, and the latter is an algorithm that can fit on a DataFrame to produce a Transformer .
In order to convert the nominal values into numeric ones we need to define aTransformer for each column:
val sexIndexer = new StringIndexer() .setInputCol("Sex") .setOutputCol("SexIndex") .setHandleInvalid("keep")val cabinIndexer = new StringIndexer() .setInputCol("Cabin") .setOutputCol("CabinIndex") .setHandleInvalid("keep")val embarkedIndexer = new StringIndexer() .setInputCol("Embarked") .setOutputCol("EmbarkedIndex") .setHandleInvalid("keep")
We are using the StringIndexer to transform the values. For each Transformer we are defining the input column and the output column that will contain the modified value.
Step 6: assemble the columns into a feature vector
We will use another Transformer to assemble the columns used in the classification by the XGBoost Estimatorinto a vector:
val vectorAssembler = new VectorAssembler() .setInputCols(Array("Pclass", "SexIndex", "Age", "SibSp", "Parch", "Fare", "CabinIndex", "EmbarkedIndex")) .setOutputCol("features")
Step 7: add the XGBoost estimator
Defining the Estimator that will produce the model. The settings of the estimator can be defined in a map. We can also set up the features and the label columns:
val xgbEstimator = new XGBoostEstimator(Map[String, Any]("num_rounds" -> 100)) .setFeaturesCol("features") .setLabelCol("Survival")
Step 8: building the pipeline and the classifier
After we created all the individual steps we can define the actual pipeline and the order of the operations:
val pipeline = new Pipeline().setStages(Array(sexIndexer, cabinIndexer, embarkedIndexer, vectorAssembler, xgbEstimator))
The input DataFrame will be transformed multiple times and in the end will produce the model trained with our data. We will save the output in order to use it in the second realtime app.
val cvModel = pipeline.fit(df)cvModel.write.overwrite.save(modelPath)
We will use Spark Structured Streaming to basically stream the data from a file. In a real world application we read the data from dedicated distributed queues such as Apache Kafka or AWS Kinesis, but for this demo we will just use a simple file.
Briefly described Spark Structured Streaming is a stream processing engine build on top of Spark SQL. It uses the same concept of DataFrames and the data is stored in an unbounded table that grows with new rows as data is streamed in.
Step 1: create the input read stream
Once again we create a spark session and define a schema for the data. Please notice that the test csv does not contain the label Survival . Finally we can create the input streaming DataFrame, df. The input path has to be a directory where we store the csv file. It can contain one or more files that have the same schema.
val spark: SparkSession = SparkSession.builder() .appName("Spark Structured Streaming XGBOOST") .master("local[*]") .getOrCreate()val schema = StructType( Array(StructField("PassengerId", DoubleType), StructField("Pclass", DoubleType), StructField("Name", StringType), StructField("Sex", StringType), StructField("Age", DoubleType), StructField("SibSp", DoubleType), StructField("Parch", DoubleType), StructField("Ticket", StringType), StructField("Fare", DoubleType), StructField("Cabin", StringType), StructField("Embarked", StringType) )) val df = spark .readStream .option("header", "true") .schema(schema) .csv(fileDir)
Step 2: load the XGBoost model
In the object XGBoostModel we load the pre trained model that will be applied for each new batch of rows we read in the stream.
object XGBoostModel { private val modelPath = "your_path" private val model = PipelineModel.read.load(modelPath) def transform(df: DataFrame) = { // replace nan values with 0 val df_clean = df.na.fill(0) // run the model on new data val result = model.transform(df_clean) // display the results result.show() }}
Step 3: define custom ML sink
In order to be able to apply our classifier to new data we need to create a new sink (the interface between the stream and the output, which in our case is the XGBoost model). For this we need a custom sink ( MLSink ), an abstract sink provider ( MLSinkProvider ) and an implementation of the provider ( XGBoostMLSinkProvider ).
abstract class MLSinkProvider extends StreamSinkProvider { def process(df: DataFrame): Unit def createSink( sqlContext: SQLContext, parameters: Map[String, String], partitionColumns: Seq[String], outputMode: OutputMode): MLSink = { new MLSink(process) }}case class MLSink(process: DataFrame => Unit) extends Sink { override def addBatch(batchId: Long, data: DataFrame): Unit = { process(data) }}class XGBoostMLSinkProvider extends MLSinkProvider { override def process(df: DataFrame) { XGBoostModel.transform(df) }}
Step 4: write the data in our custom sink
The last step is to define a query that writes the data in our custom sink. A checkpoint location also has to be defined so that the application “remembers” the latest rows read in the stream in case of a failure. If we run the program each new batch of data will be displayed on the console containing also the predicted labels.
df.writeStream .format("titanic.XGBoostMLSinkProvider") .queryName("XGBoostQuery") .option("checkpointLocation", checkpoint_location) .start() | [
{
"code": null,
"e": 405,
"s": 172,
"text": "In this article we will discuss about building a complete machine learning pipeline. The first part will be focused on training a binary classifier in a standard batch mode and in the second part we will do some realtime prediction."
},
{
"code": null,
"e": 508,
"s": 405,
"text": "We will use data from the Titanic: Machine learning from disaster one of the many Kaggle competitions."
},
{
"code": null,
"e": 609,
"s": 508,
"text": "Before getting started please know that you should be familiar with Scala, Apache Spark and Xgboost."
},
{
"code": null,
"e": 692,
"s": 609,
"text": "All the source code will also be available on Github. Cool, now let’s get started!"
},
{
"code": null,
"e": 887,
"s": 692,
"text": "We will train a XGBoost classifier using a ML pipeline in Spark. The classifier will be saved as an output and will be used in a Spark Structured Streaming realtime app to predict new test data."
},
{
"code": null,
"e": 922,
"s": 887,
"text": "Step 1: starting the spark session"
},
{
"code": null,
"e": 1037,
"s": 922,
"text": "We are creating a spark app that will run locally and will use as many threads as there are cores using local[*] :"
},
{
"code": null,
"e": 1154,
"s": 1037,
"text": "val spark = SparkSession.builder() .appName(\"Spark XGBOOST Titanic Training\") .master(\"local[*]\") .getOrCreate()"
},
{
"code": null,
"e": 1180,
"s": 1154,
"text": "Step 2: defining a schema"
},
{
"code": null,
"e": 1389,
"s": 1180,
"text": "Next we define a schema of the data we read from the csv. This is usually a better practice than letting spark to infer the schema because it consumes less resources and we have total control over the fields."
},
{
"code": null,
"e": 1873,
"s": 1389,
"text": "val schema = StructType( Array(StructField(\"PassengerId\", DoubleType), StructField(\"Survival\", DoubleType), StructField(\"Pclass\", DoubleType), StructField(\"Name\", StringType), StructField(\"Sex\", StringType), StructField(\"Age\", DoubleType), StructField(\"SibSp\", DoubleType), StructField(\"Parch\", DoubleType), StructField(\"Ticket\", StringType), StructField(\"Fare\", DoubleType), StructField(\"Cabin\", StringType), StructField(\"Embarked\", StringType) ))"
},
{
"code": null,
"e": 1898,
"s": 1873,
"text": "Step 3: reading the data"
},
{
"code": null,
"e": 1973,
"s": 1898,
"text": "We read the csv into a DataFrame, making sure we mention we have a header."
},
{
"code": null,
"e": 2059,
"s": 1973,
"text": "val df_raw = spark .read .option(\"header\", \"true\") .schema(schema) .csv(filePath)"
},
{
"code": null,
"e": 2088,
"s": 2059,
"text": "Step 4: removing null values"
},
{
"code": null,
"e": 2194,
"s": 2088,
"text": "All the null values are replaced with 0. This is not ideal, but for the purpose of this tutorial it’s ok."
},
{
"code": null,
"e": 2221,
"s": 2194,
"text": "val df = df_raw.na.fill(0)"
},
{
"code": null,
"e": 2267,
"s": 2221,
"text": "Step 5: convert the nominal values to numeric"
},
{
"code": null,
"e": 2793,
"s": 2267,
"text": "Before walking through the code on this step let’s go briefly through some Spark ML concepts. They introduce the concept of ML pipelines, which is a set of high level APIs build on top of the DataFrameswhich make it easier to combine multiple algorithms into a single process. The main elements of a pipeline are the Transformer and the Estimator. The first can represent an algorithm that can transform a DataFrame into another DataFrame, and the latter is an algorithm that can fit on a DataFrame to produce a Transformer ."
},
{
"code": null,
"e": 2898,
"s": 2793,
"text": "In order to convert the nominal values into numeric ones we need to define aTransformer for each column:"
},
{
"code": null,
"e": 3253,
"s": 2898,
"text": "val sexIndexer = new StringIndexer() .setInputCol(\"Sex\") .setOutputCol(\"SexIndex\") .setHandleInvalid(\"keep\")val cabinIndexer = new StringIndexer() .setInputCol(\"Cabin\") .setOutputCol(\"CabinIndex\") .setHandleInvalid(\"keep\")val embarkedIndexer = new StringIndexer() .setInputCol(\"Embarked\") .setOutputCol(\"EmbarkedIndex\") .setHandleInvalid(\"keep\")"
},
{
"code": null,
"e": 3423,
"s": 3253,
"text": "We are using the StringIndexer to transform the values. For each Transformer we are defining the input column and the output column that will contain the modified value."
},
{
"code": null,
"e": 3474,
"s": 3423,
"text": "Step 6: assemble the columns into a feature vector"
},
{
"code": null,
"e": 3596,
"s": 3474,
"text": "We will use another Transformer to assemble the columns used in the classification by the XGBoost Estimatorinto a vector:"
},
{
"code": null,
"e": 3775,
"s": 3596,
"text": "val vectorAssembler = new VectorAssembler() .setInputCols(Array(\"Pclass\", \"SexIndex\", \"Age\", \"SibSp\", \"Parch\", \"Fare\", \"CabinIndex\", \"EmbarkedIndex\")) .setOutputCol(\"features\")"
},
{
"code": null,
"e": 3809,
"s": 3775,
"text": "Step 7: add the XGBoost estimator"
},
{
"code": null,
"e": 3971,
"s": 3809,
"text": "Defining the Estimator that will produce the model. The settings of the estimator can be defined in a map. We can also set up the features and the label columns:"
},
{
"code": null,
"e": 4105,
"s": 3971,
"text": "val xgbEstimator = new XGBoostEstimator(Map[String, Any](\"num_rounds\" -> 100)) .setFeaturesCol(\"features\") .setLabelCol(\"Survival\")"
},
{
"code": null,
"e": 4154,
"s": 4105,
"text": "Step 8: building the pipeline and the classifier"
},
{
"code": null,
"e": 4263,
"s": 4154,
"text": "After we created all the individual steps we can define the actual pipeline and the order of the operations:"
},
{
"code": null,
"e": 4384,
"s": 4263,
"text": "val pipeline = new Pipeline().setStages(Array(sexIndexer, cabinIndexer, embarkedIndexer, vectorAssembler, xgbEstimator))"
},
{
"code": null,
"e": 4571,
"s": 4384,
"text": "The input DataFrame will be transformed multiple times and in the end will produce the model trained with our data. We will save the output in order to use it in the second realtime app."
},
{
"code": null,
"e": 4641,
"s": 4571,
"text": "val cvModel = pipeline.fit(df)cvModel.write.overwrite.save(modelPath)"
},
{
"code": null,
"e": 4888,
"s": 4641,
"text": "We will use Spark Structured Streaming to basically stream the data from a file. In a real world application we read the data from dedicated distributed queues such as Apache Kafka or AWS Kinesis, but for this demo we will just use a simple file."
},
{
"code": null,
"e": 5123,
"s": 4888,
"text": "Briefly described Spark Structured Streaming is a stream processing engine build on top of Spark SQL. It uses the same concept of DataFrames and the data is stored in an unbounded table that grows with new rows as data is streamed in."
},
{
"code": null,
"e": 5160,
"s": 5123,
"text": "Step 1: create the input read stream"
},
{
"code": null,
"e": 5484,
"s": 5160,
"text": "Once again we create a spark session and define a schema for the data. Please notice that the test csv does not contain the label Survival . Finally we can create the input streaming DataFrame, df. The input path has to be a directory where we store the csv file. It can contain one or more files that have the same schema."
},
{
"code": null,
"e": 6157,
"s": 5484,
"text": "val spark: SparkSession = SparkSession.builder() .appName(\"Spark Structured Streaming XGBOOST\") .master(\"local[*]\") .getOrCreate()val schema = StructType( Array(StructField(\"PassengerId\", DoubleType), StructField(\"Pclass\", DoubleType), StructField(\"Name\", StringType), StructField(\"Sex\", StringType), StructField(\"Age\", DoubleType), StructField(\"SibSp\", DoubleType), StructField(\"Parch\", DoubleType), StructField(\"Ticket\", StringType), StructField(\"Fare\", DoubleType), StructField(\"Cabin\", StringType), StructField(\"Embarked\", StringType) )) val df = spark .readStream .option(\"header\", \"true\") .schema(schema) .csv(fileDir)"
},
{
"code": null,
"e": 6188,
"s": 6157,
"text": "Step 2: load the XGBoost model"
},
{
"code": null,
"e": 6316,
"s": 6188,
"text": "In the object XGBoostModel we load the pre trained model that will be applied for each new batch of rows we read in the stream."
},
{
"code": null,
"e": 6650,
"s": 6316,
"text": "object XGBoostModel { private val modelPath = \"your_path\" private val model = PipelineModel.read.load(modelPath) def transform(df: DataFrame) = { // replace nan values with 0 val df_clean = df.na.fill(0) // run the model on new data val result = model.transform(df_clean) // display the results result.show() }}"
},
{
"code": null,
"e": 6680,
"s": 6650,
"text": "Step 3: define custom ML sink"
},
{
"code": null,
"e": 7009,
"s": 6680,
"text": "In order to be able to apply our classifier to new data we need to create a new sink (the interface between the stream and the output, which in our case is the XGBoost model). For this we need a custom sink ( MLSink ), an abstract sink provider ( MLSinkProvider ) and an implementation of the provider ( XGBoostMLSinkProvider )."
},
{
"code": null,
"e": 7609,
"s": 7009,
"text": "abstract class MLSinkProvider extends StreamSinkProvider { def process(df: DataFrame): Unit def createSink( sqlContext: SQLContext, parameters: Map[String, String], partitionColumns: Seq[String], outputMode: OutputMode): MLSink = { new MLSink(process) }}case class MLSink(process: DataFrame => Unit) extends Sink { override def addBatch(batchId: Long, data: DataFrame): Unit = { process(data) }}class XGBoostMLSinkProvider extends MLSinkProvider { override def process(df: DataFrame) { XGBoostModel.transform(df) }}"
},
{
"code": null,
"e": 7651,
"s": 7609,
"text": "Step 4: write the data in our custom sink"
},
{
"code": null,
"e": 7981,
"s": 7651,
"text": "The last step is to define a query that writes the data in our custom sink. A checkpoint location also has to be defined so that the application “remembers” the latest rows read in the stream in case of a failure. If we run the program each new batch of data will be displayed on the console containing also the predicted labels."
}
] |
Particular field as result in MongoDB? | To get particular field as a result in MongoDB, you can use findOne(). Following is the syntax −
db.yourCollectionName.findOne({"yourFieldName1":yourValue},{yourFieldName2:1});
Let us first create a collection with documents −
> db.particularFieldDemo.insertOne({"EmployeeName":"John Smith","EmployeeAge":26,"EmployeeTechnology":"MongoDB"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd9b4abb50a6c6dd317ada2")
}
> db.particularFieldDemo.insertOne({"EmployeeName":"Chris Brown","EmployeeAge":28,"EmployeeTechnology":"Java"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd9b4d2b50a6c6dd317ada3")
}
> db.particularFieldDemo.insertOne({"EmployeeName":"David Miller","EmployeeAge":30,"EmployeeTechnology":"MySQL"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd9b4e8b50a6c6dd317ada4")
}
> db.particularFieldDemo.insertOne({"EmployeeName":"John Doe","EmployeeAge":31,"EmployeeTechnology":"C++"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd9b527b50a6c6dd317ada5")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.particularFieldDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd9b4abb50a6c6dd317ada2"),
"EmployeeName" : "John Smith",
"EmployeeAge" : 26,
"EmployeeTechnology" : "MongoDB"
}
{
"_id" : ObjectId("5cd9b4d2b50a6c6dd317ada3"),
"EmployeeName" : "Chris Brown",
"EmployeeAge" : 28,
"EmployeeTechnology" : "Java"
}
{
"_id" : ObjectId("5cd9b4e8b50a6c6dd317ada4"),
"EmployeeName" : "David Miller",
"EmployeeAge" : 30,
"EmployeeTechnology" : "MySQL"
}
{
"_id" : ObjectId("5cd9b527b50a6c6dd317ada5"),
"EmployeeName" : "John Doe",
"EmployeeAge" : 31,
"EmployeeTechnology" : "C++"
}
Following is the query to find particular field as result in MongoDB −
> db.particularFieldDemo.findOne({"EmployeeTechnology":"Java"},{EmployeeName:1});
This will produce the following output −
{
"_id" : ObjectId("5cd9b4d2b50a6c6dd317ada3"),
"EmployeeName" : "Chris Brown"
} | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To get particular field as a result in MongoDB, you can use findOne(). Following is the syntax −"
},
{
"code": null,
"e": 1239,
"s": 1159,
"text": "db.yourCollectionName.findOne({\"yourFieldName1\":yourValue},{yourFieldName2:1});"
},
{
"code": null,
"e": 1289,
"s": 1239,
"text": "Let us first create a collection with documents −"
},
{
"code": null,
"e": 2081,
"s": 1289,
"text": "> db.particularFieldDemo.insertOne({\"EmployeeName\":\"John Smith\",\"EmployeeAge\":26,\"EmployeeTechnology\":\"MongoDB\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd9b4abb50a6c6dd317ada2\")\n}\n> db.particularFieldDemo.insertOne({\"EmployeeName\":\"Chris Brown\",\"EmployeeAge\":28,\"EmployeeTechnology\":\"Java\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd9b4d2b50a6c6dd317ada3\")\n}\n> db.particularFieldDemo.insertOne({\"EmployeeName\":\"David Miller\",\"EmployeeAge\":30,\"EmployeeTechnology\":\"MySQL\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd9b4e8b50a6c6dd317ada4\")\n}\n> db.particularFieldDemo.insertOne({\"EmployeeName\":\"John Doe\",\"EmployeeAge\":31,\"EmployeeTechnology\":\"C++\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd9b527b50a6c6dd317ada5\")\n}"
},
{
"code": null,
"e": 2180,
"s": 2081,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2222,
"s": 2180,
"text": "> db.particularFieldDemo.find().pretty();"
},
{
"code": null,
"e": 2263,
"s": 2222,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2839,
"s": 2263,
"text": "{\n \"_id\" : ObjectId(\"5cd9b4abb50a6c6dd317ada2\"),\n \"EmployeeName\" : \"John Smith\",\n \"EmployeeAge\" : 26,\n \"EmployeeTechnology\" : \"MongoDB\"\n}\n{\n \"_id\" : ObjectId(\"5cd9b4d2b50a6c6dd317ada3\"),\n \"EmployeeName\" : \"Chris Brown\",\n \"EmployeeAge\" : 28,\n \"EmployeeTechnology\" : \"Java\"\n}\n{\n \"_id\" : ObjectId(\"5cd9b4e8b50a6c6dd317ada4\"),\n \"EmployeeName\" : \"David Miller\",\n \"EmployeeAge\" : 30,\n \"EmployeeTechnology\" : \"MySQL\"\n}\n{\n \"_id\" : ObjectId(\"5cd9b527b50a6c6dd317ada5\"),\n \"EmployeeName\" : \"John Doe\",\n \"EmployeeAge\" : 31,\n \"EmployeeTechnology\" : \"C++\"\n}"
},
{
"code": null,
"e": 2910,
"s": 2839,
"text": "Following is the query to find particular field as result in MongoDB −"
},
{
"code": null,
"e": 2992,
"s": 2910,
"text": "> db.particularFieldDemo.findOne({\"EmployeeTechnology\":\"Java\"},{EmployeeName:1});"
},
{
"code": null,
"e": 3033,
"s": 2992,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3120,
"s": 3033,
"text": "{\n \"_id\" : ObjectId(\"5cd9b4d2b50a6c6dd317ada3\"),\n \"EmployeeName\" : \"Chris Brown\"\n}"
}
] |
How to properly enable ffmpeg for matplotlib.animation? | To enable ffmpeg for matplotlib.animation, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Set the ffmpeg directory.
Set the ffmpeg directory.
Create a new figure or activate an existing figure, using figure() method.
Create a new figure or activate an existing figure, using figure() method.
Add an 'ax1' to the figure as part of a subplot arrangement.
Add an 'ax1' to the figure as part of a subplot arrangement.
Plot the divider based on the pre-existing axes.
Plot the divider based on the pre-existing axes.
Create random data to be plotted, to display the data as an image, i.e., on a 2D regular raster.
Create random data to be plotted, to display the data as an image, i.e., on a 2D regular raster.
Create a colorbar for a ScalarMappable instance, cb.
Create a colorbar for a ScalarMappable instance, cb.
Set the title as the current frame.
Set the title as the current frame.
Make a list of colormaps.
Make a list of colormaps.
Make an animation by repeatedly calling a function, animate. The function creates new random data, then use imshow() method to display the data as an image.
Make an animation by repeatedly calling a function, animate. The function creates new random data, then use imshow() method to display the data as an image.
Get an instance of Pipe-based ffmpeg writer.
Get an instance of Pipe-based ffmpeg writer.
Save the current animated figure.
Save the current animated figure.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.axes_grid1 import make_axes_locatable
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.rcParams['animation.ffmpeg_path'] = 'ffmpeg'
fig = plt.figure()
ax = fig.add_subplot(111)
div = make_axes_locatable(ax)
cax = div.append_axes('right', '5%', '5%')
data = np.random.rand(5, 5)
im = ax.imshow(data)
cb = fig.colorbar(im, cax=cax)
tx = ax.set_title('Frame 0')
cmap = ["copper", 'RdBu_r', 'Oranges', 'cividis', 'hot', 'plasma']
def animate(i):
cax.cla()
data = np.random.rand(5, 5)
im = ax.imshow(data, cmap=cmap[i%len(cmap)])
fig.colorbar(im, cax=cax)
tx.set_text('Frame {0}'.format(i))
ani = animation.FuncAnimation(fig, animate, frames=10)
FFwriter = animation.FFMpegWriter()
ani.save('plot.mp4', writer=FFwriter)
When we execute the code, it will create an mp4 file with the name 'plot.mp4' and save it in the Project Directory.
Your browser does not support HTML5 video. | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To enable ffmpeg for matplotlib.animation, we can take the following steps −"
},
{
"code": null,
"e": 1215,
"s": 1139,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1291,
"s": 1215,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1317,
"s": 1291,
"text": "Set the ffmpeg directory."
},
{
"code": null,
"e": 1343,
"s": 1317,
"text": "Set the ffmpeg directory."
},
{
"code": null,
"e": 1418,
"s": 1343,
"text": "Create a new figure or activate an existing figure, using figure() method."
},
{
"code": null,
"e": 1493,
"s": 1418,
"text": "Create a new figure or activate an existing figure, using figure() method."
},
{
"code": null,
"e": 1554,
"s": 1493,
"text": "Add an 'ax1' to the figure as part of a subplot arrangement."
},
{
"code": null,
"e": 1615,
"s": 1554,
"text": "Add an 'ax1' to the figure as part of a subplot arrangement."
},
{
"code": null,
"e": 1664,
"s": 1615,
"text": "Plot the divider based on the pre-existing axes."
},
{
"code": null,
"e": 1713,
"s": 1664,
"text": "Plot the divider based on the pre-existing axes."
},
{
"code": null,
"e": 1810,
"s": 1713,
"text": "Create random data to be plotted, to display the data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1907,
"s": 1810,
"text": "Create random data to be plotted, to display the data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1960,
"s": 1907,
"text": "Create a colorbar for a ScalarMappable instance, cb."
},
{
"code": null,
"e": 2013,
"s": 1960,
"text": "Create a colorbar for a ScalarMappable instance, cb."
},
{
"code": null,
"e": 2049,
"s": 2013,
"text": "Set the title as the current frame."
},
{
"code": null,
"e": 2085,
"s": 2049,
"text": "Set the title as the current frame."
},
{
"code": null,
"e": 2111,
"s": 2085,
"text": "Make a list of colormaps."
},
{
"code": null,
"e": 2137,
"s": 2111,
"text": "Make a list of colormaps."
},
{
"code": null,
"e": 2294,
"s": 2137,
"text": "Make an animation by repeatedly calling a function, animate. The function creates new random data, then use imshow() method to display the data as an image."
},
{
"code": null,
"e": 2451,
"s": 2294,
"text": "Make an animation by repeatedly calling a function, animate. The function creates new random data, then use imshow() method to display the data as an image."
},
{
"code": null,
"e": 2496,
"s": 2451,
"text": "Get an instance of Pipe-based ffmpeg writer."
},
{
"code": null,
"e": 2541,
"s": 2496,
"text": "Get an instance of Pipe-based ffmpeg writer."
},
{
"code": null,
"e": 2575,
"s": 2541,
"text": "Save the current animated figure."
},
{
"code": null,
"e": 2609,
"s": 2575,
"text": "Save the current animated figure."
},
{
"code": null,
"e": 3496,
"s": 2609,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nplt.rcParams['animation.ffmpeg_path'] = 'ffmpeg'\n\nfig = plt.figure()\nax = fig.add_subplot(111)\ndiv = make_axes_locatable(ax)\ncax = div.append_axes('right', '5%', '5%')\ndata = np.random.rand(5, 5)\nim = ax.imshow(data)\ncb = fig.colorbar(im, cax=cax)\ntx = ax.set_title('Frame 0')\n\ncmap = [\"copper\", 'RdBu_r', 'Oranges', 'cividis', 'hot', 'plasma']\n\ndef animate(i):\n cax.cla()\n data = np.random.rand(5, 5)\n im = ax.imshow(data, cmap=cmap[i%len(cmap)])\n fig.colorbar(im, cax=cax)\n tx.set_text('Frame {0}'.format(i))\n\nani = animation.FuncAnimation(fig, animate, frames=10)\nFFwriter = animation.FFMpegWriter()\nani.save('plot.mp4', writer=FFwriter)"
},
{
"code": null,
"e": 3612,
"s": 3496,
"text": "When we execute the code, it will create an mp4 file with the name 'plot.mp4' and save it in the Project Directory."
},
{
"code": null,
"e": 3655,
"s": 3612,
"text": "Your browser does not support HTML5 video."
}
] |
UInt32 Struct in C# | The UInt32 struct represents a 32-bit unsigned integer. The UInt32 value type represents unsigned integers with values ranging from 0 to 4,294,967,295.
Let us now see some examples of UInt32 Struct methods −
The UInt32.CompareTo() method in C# is used to compare the current instance to a specified object or UInt32 and returns an indication of their relative values.
Following is the syntax −
public int CompareTo (object val);
public int CompareTo (uint val;
Above, the value for the 1st syntax is an object to compare. The value for 2nd syntax is an unsigned integer to compare.
The return value is 0 if the current instance is equal to value. It’s less than zero if the current instance is less than Val. The return value is more than zero if the current instance is greater than the value.
Let us now see an example to implement the UInt32.CompareTo() method −
using System;
public class Demo {
public static void Main(){
uint val1 = 25;
uint val2 = 55;
int res = val1.CompareTo(val2);
Console.WriteLine("Return value (comparison) = "+res);
if (res > 0)
Console.WriteLine("val1 > val2");
else if (res < 0)
Console.WriteLine("val1 < val2");
else
Console.WriteLine("val=val2");
}
}
This will produce the following output −
Return value (comparison) = -30
val1 < val2
Let us now see another example to implement the UInt32.CompareTo() method −
using System;
public class Demo {
public static void Main(){
uint val1 = 25;
object val2 = (uint)2;
int res = val1.CompareTo(val2);
Console.WriteLine("Return value (comparison) = "+res);
if (res > 0)
Console.WriteLine("val1 > val2");
else if (res < 0)
Console.WriteLine("val1 < val2");
else
Console.WriteLine("val=val2");
}
}
This will produce the following output −
Return value (comparison) = 23
val1 > val2
The UInt32.Equals() method in C# returns a value indicating whether this instance is equal to a specified object or UInt32.
Following is the syntax −
public override bool Equals (object ob);
public bool Equals (uint ob);
Above, the parameter ob for the 1st syntax is an object to compare to this instance and the parameter ob for the 2nd syntax is the 32-bit unsigned integer to compare to this instance.
Let us now see an example to implement the UInt32.Equals() method −
using System;
public class Demo {
public static void Main(){
uint val1 = 52;
uint val2 = 10;
bool res = val1.Equals(val2);
Console.WriteLine("Return value (comparison) = "+res);
if (res)
Console.WriteLine("val1 = val2");
else
Console.WriteLine("val1 != val2");
}
}
This will produce the following output −
Return value (comparison) = False
val1 != val2
Let us now see another example to implement the UInt32.Equals() method −
using System;
public class Demo {
public static void Main(){
uint val1 = 100;
uint val2 = 100;
bool res = val1.Equals(val2);
Console.WriteLine("Return value (comparison) = "+res);
if (res)
Console.WriteLine("val1 = val2");
else
Console.WriteLine("val1 != val2");
}
}
This will produce the following output −
Return value (comparison) = True
val1 = val2 | [
{
"code": null,
"e": 1214,
"s": 1062,
"text": "The UInt32 struct represents a 32-bit unsigned integer. The UInt32 value type represents unsigned integers with values ranging from 0 to 4,294,967,295."
},
{
"code": null,
"e": 1270,
"s": 1214,
"text": "Let us now see some examples of UInt32 Struct methods −"
},
{
"code": null,
"e": 1430,
"s": 1270,
"text": "The UInt32.CompareTo() method in C# is used to compare the current instance to a specified object or UInt32 and returns an indication of their relative values."
},
{
"code": null,
"e": 1456,
"s": 1430,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1523,
"s": 1456,
"text": "public int CompareTo (object val);\npublic int CompareTo (uint val;"
},
{
"code": null,
"e": 1644,
"s": 1523,
"text": "Above, the value for the 1st syntax is an object to compare. The value for 2nd syntax is an unsigned integer to compare."
},
{
"code": null,
"e": 1857,
"s": 1644,
"text": "The return value is 0 if the current instance is equal to value. It’s less than zero if the current instance is less than Val. The return value is more than zero if the current instance is greater than the value."
},
{
"code": null,
"e": 1928,
"s": 1857,
"text": "Let us now see an example to implement the UInt32.CompareTo() method −"
},
{
"code": null,
"e": 2322,
"s": 1928,
"text": "using System;\npublic class Demo {\n public static void Main(){\n uint val1 = 25;\n uint val2 = 55;\n int res = val1.CompareTo(val2);\n Console.WriteLine(\"Return value (comparison) = \"+res);\n if (res > 0)\n Console.WriteLine(\"val1 > val2\");\n else if (res < 0)\n Console.WriteLine(\"val1 < val2\");\n else\n Console.WriteLine(\"val=val2\");\n }\n}"
},
{
"code": null,
"e": 2363,
"s": 2322,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2407,
"s": 2363,
"text": "Return value (comparison) = -30\nval1 < val2"
},
{
"code": null,
"e": 2483,
"s": 2407,
"text": "Let us now see another example to implement the UInt32.CompareTo() method −"
},
{
"code": null,
"e": 2884,
"s": 2483,
"text": "using System;\npublic class Demo {\n public static void Main(){\n uint val1 = 25;\n object val2 = (uint)2;\n int res = val1.CompareTo(val2);\n Console.WriteLine(\"Return value (comparison) = \"+res);\n if (res > 0)\n Console.WriteLine(\"val1 > val2\");\n else if (res < 0)\n Console.WriteLine(\"val1 < val2\");\n else\n Console.WriteLine(\"val=val2\");\n }\n}"
},
{
"code": null,
"e": 2925,
"s": 2884,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2968,
"s": 2925,
"text": "Return value (comparison) = 23\nval1 > val2"
},
{
"code": null,
"e": 3092,
"s": 2968,
"text": "The UInt32.Equals() method in C# returns a value indicating whether this instance is equal to a specified object or UInt32."
},
{
"code": null,
"e": 3118,
"s": 3092,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 3189,
"s": 3118,
"text": "public override bool Equals (object ob);\npublic bool Equals (uint ob);"
},
{
"code": null,
"e": 3373,
"s": 3189,
"text": "Above, the parameter ob for the 1st syntax is an object to compare to this instance and the parameter ob for the 2nd syntax is the 32-bit unsigned integer to compare to this instance."
},
{
"code": null,
"e": 3441,
"s": 3373,
"text": "Let us now see an example to implement the UInt32.Equals() method −"
},
{
"code": null,
"e": 3766,
"s": 3441,
"text": "using System;\npublic class Demo {\n public static void Main(){\n uint val1 = 52;\n uint val2 = 10;\n bool res = val1.Equals(val2);\n Console.WriteLine(\"Return value (comparison) = \"+res);\n if (res)\n Console.WriteLine(\"val1 = val2\");\n else\n Console.WriteLine(\"val1 != val2\");\n }\n}"
},
{
"code": null,
"e": 3807,
"s": 3766,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3854,
"s": 3807,
"text": "Return value (comparison) = False\nval1 != val2"
},
{
"code": null,
"e": 3927,
"s": 3854,
"text": "Let us now see another example to implement the UInt32.Equals() method −"
},
{
"code": null,
"e": 4254,
"s": 3927,
"text": "using System;\npublic class Demo {\n public static void Main(){\n uint val1 = 100;\n uint val2 = 100;\n bool res = val1.Equals(val2);\n Console.WriteLine(\"Return value (comparison) = \"+res);\n if (res)\n Console.WriteLine(\"val1 = val2\");\n else\n Console.WriteLine(\"val1 != val2\");\n }\n}"
},
{
"code": null,
"e": 4295,
"s": 4254,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 4340,
"s": 4295,
"text": "Return value (comparison) = True\nval1 = val2"
}
] |
Node.js fs.realpathSync() Method - GeeksforGeeks | 11 Oct, 2021
The fs.realpathSync() method is used to synchronously compute the canonical pathname of a given path. It does so by resolving the ., .. and the symbolic links in the path and returning the resolved path.Syntax:
fs.realpathSync( path, options )
Parameters: This method accept two parameters as mentioned above and described below:
path: It holds the path of the directory that has to be resolved. It can be a String, Buffer or URL.
options: It is an string or object that can be used to specify optional parameters that will affect the operation. It has one optional parameter:encoding: It is a string which defines the encoding of the resolved path.
encoding: It is a string which defines the encoding of the resolved path.
Returns: It returns a String or a Buffer that represents the resolved path.Below examples illustrate the fs.realpathSync() method in Node.js:Example 1:
javascript
// Node.js program to demonstrate the// fs.realpathSync() method // Import the filesystem moduleconst fs = require('fs'); console.log("Current Directory Path:", __dirname); // Finding the canonical path// one directory uppath1 = __dirname + "\\.."; resolvedPath = fs.realpathSync(path1);console.log("One directory up resolved path is: ", resolvedPath); // Finding the canonical path// two directories uppath2 = __dirname + "\\..\\.."; resolvedPath = fs.realpathSync(path2);console.log("Two directories up resolved path is: ", resolvedPath);
Output:
Current Directory Path: G:\tutorials\nodejs-fs-realPathSync
One directory up resolved path is: G:\tutorials
Two directories up resolved path is: G:\
Example 2:
javascript
// Node.js program to demonstrate the// fs.realpathSync() method // Import the filesystem moduleconst fs = require('fs'); path = __dirname + "\\.."; // Getting the canonical path is utf8 encodingresolvedPath = fs.realpathSync(path, { encoding: "utf8" });console.log("The resolved path is: ", resolvedPath); // Getting the canonical path is hex encodingresolvedPath = fs.realpathSync(path, { encoding: "hex" });console.log("The resolved path is: ", resolvedPath); // Getting the canonical path is base64 encodingresolvedPath = fs.realpathSync(path, { encoding: "base64" });console.log("The resolved path is: ", resolvedPath);
Output:
The resolved path is: G:\tutorials
The resolved path is: 473a5c7475746f7269616c73
The resolved path is: RzpcdHV0b3JpYWxz
Reference: https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options
surindertarika1234
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
Express.js req.params Property
JWT Authentication with Node.js
Difference between npm i and npm ci in Node.js
Mongoose Populate() Method
Roadmap to Become a Web Developer in 2022
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25002,
"s": 24974,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 25214,
"s": 25002,
"text": "The fs.realpathSync() method is used to synchronously compute the canonical pathname of a given path. It does so by resolving the ., .. and the symbolic links in the path and returning the resolved path.Syntax: "
},
{
"code": null,
"e": 25247,
"s": 25214,
"text": "fs.realpathSync( path, options )"
},
{
"code": null,
"e": 25335,
"s": 25247,
"text": "Parameters: This method accept two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 25436,
"s": 25335,
"text": "path: It holds the path of the directory that has to be resolved. It can be a String, Buffer or URL."
},
{
"code": null,
"e": 25655,
"s": 25436,
"text": "options: It is an string or object that can be used to specify optional parameters that will affect the operation. It has one optional parameter:encoding: It is a string which defines the encoding of the resolved path."
},
{
"code": null,
"e": 25729,
"s": 25655,
"text": "encoding: It is a string which defines the encoding of the resolved path."
},
{
"code": null,
"e": 25882,
"s": 25729,
"text": "Returns: It returns a String or a Buffer that represents the resolved path.Below examples illustrate the fs.realpathSync() method in Node.js:Example 1: "
},
{
"code": null,
"e": 25893,
"s": 25882,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the// fs.realpathSync() method // Import the filesystem moduleconst fs = require('fs'); console.log(\"Current Directory Path:\", __dirname); // Finding the canonical path// one directory uppath1 = __dirname + \"\\\\..\"; resolvedPath = fs.realpathSync(path1);console.log(\"One directory up resolved path is: \", resolvedPath); // Finding the canonical path// two directories uppath2 = __dirname + \"\\\\..\\\\..\"; resolvedPath = fs.realpathSync(path2);console.log(\"Two directories up resolved path is: \", resolvedPath);",
"e": 26464,
"s": 25893,
"text": null
},
{
"code": null,
"e": 26472,
"s": 26464,
"text": "Output:"
},
{
"code": null,
"e": 26623,
"s": 26472,
"text": "Current Directory Path: G:\\tutorials\\nodejs-fs-realPathSync\nOne directory up resolved path is: G:\\tutorials\nTwo directories up resolved path is: G:\\"
},
{
"code": null,
"e": 26635,
"s": 26623,
"text": "Example 2: "
},
{
"code": null,
"e": 26646,
"s": 26635,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the// fs.realpathSync() method // Import the filesystem moduleconst fs = require('fs'); path = __dirname + \"\\\\..\"; // Getting the canonical path is utf8 encodingresolvedPath = fs.realpathSync(path, { encoding: \"utf8\" });console.log(\"The resolved path is: \", resolvedPath); // Getting the canonical path is hex encodingresolvedPath = fs.realpathSync(path, { encoding: \"hex\" });console.log(\"The resolved path is: \", resolvedPath); // Getting the canonical path is base64 encodingresolvedPath = fs.realpathSync(path, { encoding: \"base64\" });console.log(\"The resolved path is: \", resolvedPath);",
"e": 27276,
"s": 26646,
"text": null
},
{
"code": null,
"e": 27284,
"s": 27276,
"text": "Output:"
},
{
"code": null,
"e": 27408,
"s": 27284,
"text": "The resolved path is: G:\\tutorials\nThe resolved path is: 473a5c7475746f7269616c73\nThe resolved path is: RzpcdHV0b3JpYWxz"
},
{
"code": null,
"e": 27483,
"s": 27408,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options "
},
{
"code": null,
"e": 27502,
"s": 27483,
"text": "surindertarika1234"
},
{
"code": null,
"e": 27520,
"s": 27502,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 27527,
"s": 27520,
"text": "Picked"
},
{
"code": null,
"e": 27535,
"s": 27527,
"text": "Node.js"
},
{
"code": null,
"e": 27552,
"s": 27535,
"text": "Web Technologies"
},
{
"code": null,
"e": 27650,
"s": 27552,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27659,
"s": 27650,
"text": "Comments"
},
{
"code": null,
"e": 27672,
"s": 27659,
"text": "Old Comments"
},
{
"code": null,
"e": 27709,
"s": 27672,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 27740,
"s": 27709,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 27772,
"s": 27740,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 27819,
"s": 27772,
"text": "Difference between npm i and npm ci in Node.js"
},
{
"code": null,
"e": 27846,
"s": 27819,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 27888,
"s": 27846,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27938,
"s": 27888,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28000,
"s": 27938,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28043,
"s": 28000,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to get the differences between two dates in iOS? | Getting difference between two dates is easy. You should know how to play between the dates.
We will be using DateFormatter class for formatting the dates.
Instances of DateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.
You can read more about it here
https://developer.apple.com/documentation/foundation/dateformatter
We will also be using Calendar structure, apple has provided beautiful documentation of it,
https://developer.apple.com/documentation/foundation/calendar
So let’s get started.
Open Xcode, New Playground.
Copy the below code
import UIKit
// create object of DateFormatter and Calendar
let formatter = DateFormatter()
let calendar = Calendar.current
// specify the format,
formatter.dateFormat = "dd-MM-yyyy"
// specify the start date
let startDate = formatter.date(from: "10-08-2018")
// specify the end date
let endDate = formatter.date(from: "23-09-2019")
print(startDate!)
print(endDate!)
let diff = calendar.dateComponents([.day], from: startDate!, to: endDate!)
// print the diff between the two dates
print(diff) | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "Getting difference between two dates is easy. You should know how to play between the dates."
},
{
"code": null,
"e": 1218,
"s": 1155,
"text": "We will be using DateFormatter class for formatting the dates."
},
{
"code": null,
"e": 1372,
"s": 1218,
"text": "Instances of DateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects."
},
{
"code": null,
"e": 1404,
"s": 1372,
"text": "You can read more about it here"
},
{
"code": null,
"e": 1472,
"s": 1404,
"text": " https://developer.apple.com/documentation/foundation/dateformatter"
},
{
"code": null,
"e": 1564,
"s": 1472,
"text": "We will also be using Calendar structure, apple has provided beautiful documentation of it,"
},
{
"code": null,
"e": 1627,
"s": 1564,
"text": " https://developer.apple.com/documentation/foundation/calendar"
},
{
"code": null,
"e": 1649,
"s": 1627,
"text": "So let’s get started."
},
{
"code": null,
"e": 1677,
"s": 1649,
"text": "Open Xcode, New Playground."
},
{
"code": null,
"e": 1697,
"s": 1677,
"text": "Copy the below code"
},
{
"code": null,
"e": 2191,
"s": 1697,
"text": "import UIKit\n// create object of DateFormatter and Calendar\nlet formatter = DateFormatter()\nlet calendar = Calendar.current\n// specify the format,\nformatter.dateFormat = \"dd-MM-yyyy\"\n// specify the start date\nlet startDate = formatter.date(from: \"10-08-2018\")\n// specify the end date\nlet endDate = formatter.date(from: \"23-09-2019\")\nprint(startDate!)\nprint(endDate!)\nlet diff = calendar.dateComponents([.day], from: startDate!, to: endDate!)\n// print the diff between the two dates\nprint(diff)"
}
] |
Introduction of K-Map (Karnaugh Map) - GeeksforGeeks | 22 Nov, 2021
In many digital circuits and practical problems we need to find expression with minimum variables. We can minimize Boolean expressions of 3, 4 variables very easily using K-map without using any Boolean algebra theorems. K-map can take two forms Sum of Product (SOP) and Product of Sum (POS) according to the need of problem. K-map is table like representation but it gives more information than TRUTH TABLE. We fill grid of K-map with 0’s and 1’s then solve it by making groups.
Steps to solve expression using K-map-
Select K-map according to the number of variables.Identify minterms or maxterms as given in problem.For SOP put 1’s in blocks of K-map respective to the minterms (0’s elsewhere).For POS put 0’s in blocks of K-map respective to the maxterms(1’s elsewhere).Make rectangular groups containing total terms in power of two like 2,4,8 ..(except 1) and try to cover as many elements as you can in one group.From the groups made in step 5 find the product terms and sum them up for SOP form.
Select K-map according to the number of variables.
Identify minterms or maxterms as given in problem.
For SOP put 1’s in blocks of K-map respective to the minterms (0’s elsewhere).
For POS put 0’s in blocks of K-map respective to the maxterms(1’s elsewhere).
Make rectangular groups containing total terms in power of two like 2,4,8 ..(except 1) and try to cover as many elements as you can in one group.
From the groups made in step 5 find the product terms and sum them up for SOP form.
SOP FORM :
1. K-map of 3 variables –
Z= ∑A,B,C(1,3,6,7)
From red group we get product term—
A’C
From green group we get product term—
AB
Summing these product terms we get- Final expression (A’C+AB)
2. K-map for 4 variables –
F(P,Q,R,S)=∑(0,2,5,7,8,10,13,15)
From red group we get product term—
QS
From green group we get product term—
Q’S’
Summing these product terms we get- Final expression (QS+Q’S’)
POS FORM :
1. K-map of 3 variables –
F(A,B,C)=π(0,3,6,7)
From red group we find terms
A B
Taking complement of these two
A' B'
Now sum up them
(A' + B')
From brown group we find terms
B C
Taking complement of these two terms
B’ C’
Now sum up them
(B’+C’)
From yellow group we find terms
A' B' C’
Taking complement of these two
A B C
Now sum up them
(A + B + C)
We will take product of these three terms : Final expression –
(A' + B’) (B’ + C’) (A + B + C)
2. K-map of 4 variables –
F(A,B,C,D)=π(3,5,7,8,10,11,12,13)
From green group we find terms
C’ D B
Taking their complement and summing them
(C+D’+B’)
From red group we find terms
C D A’
Taking their complement and summing them
(C’+D’+A)
From blue group we find terms
A C’ D’
Taking their complement and summing them
(A’+C+D)
From brown group we find terms
A B’ C
Taking their complement and summing them
(A’+B+C’)
Finally we express these as product –
(C+D’+B’).(C’+D’+A).(A’+C+D).(A’+B+C’)
PITFALL– *Always remember POS ≠ (SOP)’
*The correct form is (POS of F)=(SOP of F’)’
Quiz on K-MAP
This article is contributed by Anuj Bhatam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
pdabre18
nitupandel001
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
IEEE Standard 754 Floating Point Numbers
4-bit binary Adder-Subtractor
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Shift Micro-Operations in Computer Architecture
Difference between RAM and ROM
Difference between Half adder and full adder
Analog to Digital Conversion
Difference between Flip-flop and Latch
Transmission Impairment in Data Communication
Latches in Digital Logic | [
{
"code": null,
"e": 26834,
"s": 26806,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 27314,
"s": 26834,
"text": "In many digital circuits and practical problems we need to find expression with minimum variables. We can minimize Boolean expressions of 3, 4 variables very easily using K-map without using any Boolean algebra theorems. K-map can take two forms Sum of Product (SOP) and Product of Sum (POS) according to the need of problem. K-map is table like representation but it gives more information than TRUTH TABLE. We fill grid of K-map with 0’s and 1’s then solve it by making groups."
},
{
"code": null,
"e": 27354,
"s": 27314,
"text": "Steps to solve expression using K-map- "
},
{
"code": null,
"e": 27838,
"s": 27354,
"text": "Select K-map according to the number of variables.Identify minterms or maxterms as given in problem.For SOP put 1’s in blocks of K-map respective to the minterms (0’s elsewhere).For POS put 0’s in blocks of K-map respective to the maxterms(1’s elsewhere).Make rectangular groups containing total terms in power of two like 2,4,8 ..(except 1) and try to cover as many elements as you can in one group.From the groups made in step 5 find the product terms and sum them up for SOP form."
},
{
"code": null,
"e": 27889,
"s": 27838,
"text": "Select K-map according to the number of variables."
},
{
"code": null,
"e": 27940,
"s": 27889,
"text": "Identify minterms or maxterms as given in problem."
},
{
"code": null,
"e": 28019,
"s": 27940,
"text": "For SOP put 1’s in blocks of K-map respective to the minterms (0’s elsewhere)."
},
{
"code": null,
"e": 28097,
"s": 28019,
"text": "For POS put 0’s in blocks of K-map respective to the maxterms(1’s elsewhere)."
},
{
"code": null,
"e": 28243,
"s": 28097,
"text": "Make rectangular groups containing total terms in power of two like 2,4,8 ..(except 1) and try to cover as many elements as you can in one group."
},
{
"code": null,
"e": 28327,
"s": 28243,
"text": "From the groups made in step 5 find the product terms and sum them up for SOP form."
},
{
"code": null,
"e": 28338,
"s": 28327,
"text": "SOP FORM :"
},
{
"code": null,
"e": 28364,
"s": 28338,
"text": "1. K-map of 3 variables –"
},
{
"code": null,
"e": 28385,
"s": 28364,
"text": "Z= ∑A,B,C(1,3,6,7) "
},
{
"code": null,
"e": 28422,
"s": 28385,
"text": "From red group we get product term— "
},
{
"code": null,
"e": 28427,
"s": 28422,
"text": "A’C "
},
{
"code": null,
"e": 28466,
"s": 28427,
"text": "From green group we get product term— "
},
{
"code": null,
"e": 28470,
"s": 28466,
"text": "AB "
},
{
"code": null,
"e": 28535,
"s": 28470,
"text": "Summing these product terms we get- Final expression (A’C+AB) "
},
{
"code": null,
"e": 28562,
"s": 28535,
"text": "2. K-map for 4 variables –"
},
{
"code": null,
"e": 28597,
"s": 28562,
"text": "F(P,Q,R,S)=∑(0,2,5,7,8,10,13,15) "
},
{
"code": null,
"e": 28634,
"s": 28597,
"text": "From red group we get product term— "
},
{
"code": null,
"e": 28638,
"s": 28634,
"text": "QS "
},
{
"code": null,
"e": 28677,
"s": 28638,
"text": "From green group we get product term— "
},
{
"code": null,
"e": 28683,
"s": 28677,
"text": "Q’S’ "
},
{
"code": null,
"e": 28749,
"s": 28683,
"text": "Summing these product terms we get- Final expression (QS+Q’S’) "
},
{
"code": null,
"e": 28762,
"s": 28751,
"text": "POS FORM :"
},
{
"code": null,
"e": 28788,
"s": 28762,
"text": "1. K-map of 3 variables –"
},
{
"code": null,
"e": 28808,
"s": 28788,
"text": "F(A,B,C)=π(0,3,6,7)"
},
{
"code": null,
"e": 28840,
"s": 28810,
"text": "From red group we find terms "
},
{
"code": null,
"e": 28850,
"s": 28840,
"text": "A B "
},
{
"code": null,
"e": 28882,
"s": 28850,
"text": "Taking complement of these two "
},
{
"code": null,
"e": 28896,
"s": 28882,
"text": "A' B' "
},
{
"code": null,
"e": 28913,
"s": 28896,
"text": "Now sum up them "
},
{
"code": null,
"e": 28924,
"s": 28913,
"text": "(A' + B') "
},
{
"code": null,
"e": 28956,
"s": 28924,
"text": "From brown group we find terms "
},
{
"code": null,
"e": 28963,
"s": 28956,
"text": "B C "
},
{
"code": null,
"e": 29001,
"s": 28963,
"text": "Taking complement of these two terms "
},
{
"code": null,
"e": 29009,
"s": 29001,
"text": "B’ C’ "
},
{
"code": null,
"e": 29026,
"s": 29009,
"text": "Now sum up them "
},
{
"code": null,
"e": 29035,
"s": 29026,
"text": "(B’+C’) "
},
{
"code": null,
"e": 29068,
"s": 29035,
"text": "From yellow group we find terms "
},
{
"code": null,
"e": 29078,
"s": 29068,
"text": "A' B' C’ "
},
{
"code": null,
"e": 29110,
"s": 29078,
"text": "Taking complement of these two "
},
{
"code": null,
"e": 29117,
"s": 29110,
"text": "A B C "
},
{
"code": null,
"e": 29134,
"s": 29117,
"text": "Now sum up them "
},
{
"code": null,
"e": 29147,
"s": 29134,
"text": "(A + B + C) "
},
{
"code": null,
"e": 29210,
"s": 29147,
"text": "We will take product of these three terms : Final expression –"
},
{
"code": null,
"e": 29243,
"s": 29210,
"text": "(A' + B’) (B’ + C’) (A + B + C) "
},
{
"code": null,
"e": 29271,
"s": 29243,
"text": "2. K-map of 4 variables – "
},
{
"code": null,
"e": 29306,
"s": 29271,
"text": "F(A,B,C,D)=π(3,5,7,8,10,11,12,13) "
},
{
"code": null,
"e": 29341,
"s": 29309,
"text": "From green group we find terms "
},
{
"code": null,
"e": 29351,
"s": 29341,
"text": "C’ D B "
},
{
"code": null,
"e": 29393,
"s": 29351,
"text": "Taking their complement and summing them "
},
{
"code": null,
"e": 29404,
"s": 29393,
"text": "(C+D’+B’) "
},
{
"code": null,
"e": 29434,
"s": 29404,
"text": "From red group we find terms "
},
{
"code": null,
"e": 29444,
"s": 29434,
"text": "C D A’ "
},
{
"code": null,
"e": 29486,
"s": 29444,
"text": "Taking their complement and summing them "
},
{
"code": null,
"e": 29497,
"s": 29486,
"text": "(C’+D’+A) "
},
{
"code": null,
"e": 29528,
"s": 29497,
"text": "From blue group we find terms"
},
{
"code": null,
"e": 29539,
"s": 29528,
"text": "A C’ D’ "
},
{
"code": null,
"e": 29581,
"s": 29539,
"text": "Taking their complement and summing them "
},
{
"code": null,
"e": 29591,
"s": 29581,
"text": "(A’+C+D) "
},
{
"code": null,
"e": 29623,
"s": 29591,
"text": "From brown group we find terms"
},
{
"code": null,
"e": 29633,
"s": 29623,
"text": "A B’ C "
},
{
"code": null,
"e": 29675,
"s": 29633,
"text": "Taking their complement and summing them "
},
{
"code": null,
"e": 29686,
"s": 29675,
"text": "(A’+B+C’) "
},
{
"code": null,
"e": 29724,
"s": 29686,
"text": "Finally we express these as product –"
},
{
"code": null,
"e": 29764,
"s": 29724,
"text": "(C+D’+B’).(C’+D’+A).(A’+C+D).(A’+B+C’) "
},
{
"code": null,
"e": 29806,
"s": 29764,
"text": "PITFALL– *Always remember POS ≠ (SOP)’ "
},
{
"code": null,
"e": 29852,
"s": 29806,
"text": "*The correct form is (POS of F)=(SOP of F’)’ "
},
{
"code": null,
"e": 29867,
"s": 29852,
"text": "Quiz on K-MAP "
},
{
"code": null,
"e": 30036,
"s": 29867,
"text": "This article is contributed by Anuj Bhatam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 30045,
"s": 30036,
"text": "pdabre18"
},
{
"code": null,
"e": 30059,
"s": 30045,
"text": "nitupandel001"
},
{
"code": null,
"e": 30094,
"s": 30059,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 30192,
"s": 30094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30233,
"s": 30192,
"text": "IEEE Standard 754 Floating Point Numbers"
},
{
"code": null,
"e": 30263,
"s": 30233,
"text": "4-bit binary Adder-Subtractor"
},
{
"code": null,
"e": 30330,
"s": 30263,
"text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes"
},
{
"code": null,
"e": 30378,
"s": 30330,
"text": "Shift Micro-Operations in Computer Architecture"
},
{
"code": null,
"e": 30409,
"s": 30378,
"text": "Difference between RAM and ROM"
},
{
"code": null,
"e": 30454,
"s": 30409,
"text": "Difference between Half adder and full adder"
},
{
"code": null,
"e": 30483,
"s": 30454,
"text": "Analog to Digital Conversion"
},
{
"code": null,
"e": 30522,
"s": 30483,
"text": "Difference between Flip-flop and Latch"
},
{
"code": null,
"e": 30568,
"s": 30522,
"text": "Transmission Impairment in Data Communication"
}
] |
How to design a custom alert box using JavaScript? | To design a custom alert box, try to run the following code. The code uses a JavaScript library jQuery and CSS to create an alert box different from the standard alert box −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function functionAlert(msg, myYes) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes").unbind().click(function() {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.show();
}
</script>
<style>
#confirm {
display: none;
background-color: #91FF00;
border: 1px solid #aaa;
position: fixed;
width: 250px;
left: 50%;
margin-left: -100px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
}
#confirm button {
background-color: #48E5DA;
display: inline-block;
border-radius: 5px;
border: 1px solid #aaa;
padding: 5px;
text-align: center;
width: 80px;
cursor: pointer;
}
#confirm .message {
text-align: left;
}
</style>
</head>
<body>
<div id = "confirm">
<div class = "message">This is a warning message.</div>
<button class = "yes">OK</button>
</div>
<input type = "button" value = "Click Me" onclick = "functionAlert();" />
</body>
</html> | [
{
"code": null,
"e": 1236,
"s": 1062,
"text": "To design a custom alert box, try to run the following code. The code uses a JavaScript library jQuery and CSS to create an alert box different from the standard alert box −"
},
{
"code": null,
"e": 1246,
"s": 1236,
"text": "Live Demo"
},
{
"code": null,
"e": 2759,
"s": 1246,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n function functionAlert(msg, myYes) {\n var confirmBox = $(\"#confirm\");\n confirmBox.find(\".message\").text(msg);\n confirmBox.find(\".yes\").unbind().click(function() {\n confirmBox.hide();\n });\n confirmBox.find(\".yes\").click(myYes);\n confirmBox.show();\n }\n </script>\n <style>\n #confirm {\n display: none;\n background-color: #91FF00;\n border: 1px solid #aaa;\n position: fixed;\n width: 250px;\n left: 50%;\n margin-left: -100px;\n padding: 6px 8px 8px;\n box-sizing: border-box;\n text-align: center;\n }\n #confirm button {\n background-color: #48E5DA;\n display: inline-block;\n border-radius: 5px;\n border: 1px solid #aaa;\n padding: 5px;\n text-align: center;\n width: 80px;\n cursor: pointer;\n }\n #confirm .message {\n text-align: left;\n }\n </style>\n </head>\n <body>\n <div id = \"confirm\">\n <div class = \"message\">This is a warning message.</div>\n <button class = \"yes\">OK</button>\n </div>\n <input type = \"button\" value = \"Click Me\" onclick = \"functionAlert();\" />\n </body>\n</html>"
}
] |
OpenNLP - Quick Guide | NLP is a set of tools used to derive meaningful and useful information from natural language sources such as web pages and text documents.
Apache OpenNLP is an open-source Java library which is used to process natural language text. You can build an efficient text processing service using this library.
OpenNLP provides services such as tokenization, sentence segmentation, part-of-speech tagging, named entity extraction, chunking, parsing, and co-reference resolution, etc.
Following are the notable features of OpenNLP −
Named Entity Recognition (NER) − Open NLP supports NER, using which you can extract names of locations, people and things even while processing queries.
Named Entity Recognition (NER) − Open NLP supports NER, using which you can extract names of locations, people and things even while processing queries.
Summarize − Using the summarize feature, you can summarize Paragraphs, articles, documents or their collection in NLP.
Summarize − Using the summarize feature, you can summarize Paragraphs, articles, documents or their collection in NLP.
Searching − In OpenNLP, a given search string or its synonyms can be identified in given text, even though the given word is altered or misspelled.
Searching − In OpenNLP, a given search string or its synonyms can be identified in given text, even though the given word is altered or misspelled.
Tagging (POS) − Tagging in NLP is used to divide the text into various grammatical elements for further analysis.
Tagging (POS) − Tagging in NLP is used to divide the text into various grammatical elements for further analysis.
Translation − In NLP, Translation helps in translating one language into another.
Translation − In NLP, Translation helps in translating one language into another.
Information grouping − This option in NLP groups the textual information in the content of the document, just like Parts of speech.
Information grouping − This option in NLP groups the textual information in the content of the document, just like Parts of speech.
Natural Language Generation − It is used for generating information from a database and automating the information reports such as weather analysis or medical reports.
Natural Language Generation − It is used for generating information from a database and automating the information reports such as weather analysis or medical reports.
Feedback Analysis − As the name implies, various types of feedbacks from people are collected, regarding the products, by NLP to analyze how well the product is successful in winning their hearts.
Feedback Analysis − As the name implies, various types of feedbacks from people are collected, regarding the products, by NLP to analyze how well the product is successful in winning their hearts.
Speech recognition − Though it is difficult to analyze human speech, NLP has some builtin features for this requirement.
Speech recognition − Though it is difficult to analyze human speech, NLP has some builtin features for this requirement.
The Apache OpenNLP library provides classes and interfaces to perform various tasks of natural language processing such as sentence detection, tokenization, finding a name, tagging the parts of speech, chunking a sentence, parsing, co-reference resolution, and document categorization.
In addition to these tasks, we can also train and evaluate our own models for any of these tasks.
In addition to the library, OpenNLP also provides a Command Line Interface (CLI), where we can train and evaluate models. We will discuss this topic in detail in the last chapter of this tutorial.
To perform various NLP tasks, OpenNLP provides a set of predefined models. This set includes models for different languages.
You can follow the steps given below to download the predefined models provided by OpenNLP.
Step 1 − Open the index page of OpenNLP models by clicking the following link − http://opennlp.sourceforge.net/models-1.5/.
Step 2 − On visiting the given link, you will get to see a list of components of various languages and the links to download them. Here, you can get the list of all the predefined models provided by OpenNLP.
Download all these models to the folder C:/OpenNLP_models/>, by clicking on their respective links. All these models are language dependent and while using these, you have to make sure that the model language matches with the language of the input text.
In 2010, OpenNLP entered the Apache incubation.
In 2010, OpenNLP entered the Apache incubation.
In 2011, Apache OpenNLP 1.5.2 Incubating was released, and in the same year, it graduated as a top-level Apache project.
In 2011, Apache OpenNLP 1.5.2 Incubating was released, and in the same year, it graduated as a top-level Apache project.
In 2015, OpenNLP was 1.6.0 released.
In 2015, OpenNLP was 1.6.0 released.
In this chapter, we will discuss how you can setup OpenNLP environment in your system. Let’s start with the installation process.
Following are the steps to download Apache OpenNLP library in your system.
Step 1 − Open the homepage of Apache OpenNLP by clicking the following link − https://opennlp.apache.org/.
Step 2 − Now, click on the Downloads link. On clicking, you will be directed to a page where you can find various mirrors which will redirect you to the Apache Software Foundation Distribution directory.
Step 3 − In this page you can find links to download various Apache distributions. Browse through them and find the OpenNLP distribution and click it.
Step 4 − On clicking, you will be redirected to the directory where you can see the index of the OpenNLP distribution, as shown below.
Click on the latest version from the available distributions.
Step 5 − Each distribution provides Source and Binary files of OpenNLP library in various formats. Download the source and binary files, apache-opennlp-1.6.0-bin.zip and apache-opennlp1.6.0-src.zip (for Windows).
After downloading the OpenNLP library, you need to set its path to the bin directory. Assume that you have downloaded the OpenNLP library to the E drive of your system.
Now, follow the steps that are given below −
Step 1 − Right-click on 'My Computer' and select 'Properties'.
Step 2 − Click on the 'Environment Variables' button under the 'Advanced' tab.
Step 3 − Select the path variable and click the Edit button, as shown in the following screenshot.
Step 4 − In the Edit Environment Variable window, click the New button and add the path for OpenNLP directory E:\apache-opennlp-1.6.0\bin and click the OK button, as shown in the following screenshot.
You can set the Eclipse environment for OpenNLP library, either by setting the Build path to the JAR files or by using pom.xml.
Follow the steps given below to install OpenNLP in Eclipse −
Step 1 − Make sure that you have Eclipse environment installed in your system.
Step 2 − Open Eclipse. Click File → New → Open a new project, as shown below.
Step 3 − You will get the New Project wizard. In this wizard, select Java project and proceed by clicking the Next button.
Step 4 − Next, you will get the New Java Project wizard. Here, you need to create a new project and click the Next button, as shown below.
Step 5 − After creating a new project, right-click on it, select Build Path and click Configure Build Path.
Step 6 − Next, you will get the Java Build Path wizard. Here, click the Add External JARs button, as shown below.
Step 7 − Select the jar files opennlp-tools-1.6.0.jar and opennlp-uima-1.6.0.jar located in the lib folder of apache-opennlp-1.6.0 folder.
On clicking the Open button in the above screen, the selected files will be added to your library.
On clicking OK, you will successfully add the required JAR files to the current project and you can verify these added libraries by expanding the Referenced Libraries, as shown below.
Convert the project into a Maven project and add the following code to its pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>myproject</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.opennlp</groupId>
<artifactId>opennlp-tools</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.opennlp</groupId>
<artifactId>opennlp-uima</artifactId>
<version>1.6.0</version>
</dependency>
</dependencies>
</project>
In this chapter, we will discuss about the classes and methods that we will be using in the subsequent chapters of this tutorial.
This class represents the predefined model which is used to detect the sentences in the given raw text. This class belongs to the package opennlp.tools.sentdetect.
The constructor of this class accepts an InputStream object of the sentence detector model file (en-sent.bin).
This class belongs to the package opennlp.tools.sentdetect and it contains methods to split the raw text into sentences. This class uses a maximum entropy model to evaluate end-ofsentence characters in a string to determine if they signify the end of a sentence.
Following are the important methods of this class.
sentDetect()
This method is used to detect the sentences in the raw text passed to it. It accepts a String variable as a parameter and returns a String array which holds the sentences from the given raw text.
sentPosDetect()
This method is used to detect the positions of the sentences in the given text. This method accepts a string variable, representing the sentence and returns an array of objects of the type Span.
The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets.
getSentenceProbabilities()
This method returns the probabilities associated with the most recent calls to sentDetect() method.
This class represents the predefined model which is used to tokenize the given sentence. This class belongs to the package opennlp.tools.tokenizer.
The constructor of this class accepts a InputStream object of the tokenizer model file (entoken.bin).
To perform tokenization, the OpenNLP library provides three main classes. All the three classes implement the interface called Tokenizer.
SimpleTokenizer
This class tokenizes the given raw text using character classes.
WhitespaceTokenizer
This class uses whitespaces to tokenize the given text.
TokenizerME
This class converts raw text in to separate tokens. It uses Maximum Entropy to make its decisions.
These classes contain the following methods.
tokenize()
This method is used to tokenize the raw text. This method accepts a String variable as a parameter, and returns an array of Strings (tokens).
sentPosDetect()
This method is used to get the positions or spans of the tokens. It accepts the sentence (or) raw text in the form of the string and returns an array of objects of the type Span.
In addition to the above two methods, the TokenizerME class has the getTokenProbabilities() method.
getTokenProbabilities()
This method is used to get the probabilities associated with the most recent calls to the tokenizePos() method.
This class represents the predefined model which is used to find the named entities in the given sentence. This class belongs to the package opennlp.tools.namefind.
The constructor of this class accepts a InputStream object of the name finder model file (enner-person.bin).
The class belongs to the package opennlp.tools.namefind and it contains methods to perform the NER tasks. This class uses a maximum entropy model to find the named entities in the given raw text.
find()
This method is used to detect the names in the raw text. It accepts a String variable representing the raw text as a parameter and, returns an array of objects of the type Span.
probs()
This method is used to get the probabilities of the last decoded sequence.
This class represents the predefined model which is used to tag the parts of speech of the given sentence. This class belongs to the package opennlp.tools.postag.
The constructor of this class accepts a InputStream object of the pos-tagger model file (enpos-maxent.bin).
This class belongs to the package opennlp.tools.postag and it is used to predict the parts of speech of the given raw text. It uses Maximum Entropy to make its decisions.
tag()
This method is used to assign the sentence of tokens POS tags. This method accepts an array of tokens (String) as a parameter, and returns a tags (array).
getSentenceProbabilities()
This method is used to get the probabilities for each tag of the recently tagged sentence.
This class represents the predefined model which is used to parse the given sentence. This class belongs to the package opennlp.tools.parser.
The constructor of this class accepts a InputStream object of the parser model file (en-parserchunking.bin).
This class belongs to the package opennlp.tools.parser and it is used to create parsers.
create()
This is a static method and it is used to create a parser object. This method accepts the Filestream object of the parser model file.
This class belongs to the opennlp.tools.cmdline.parser package and, it is used to parse the content.
parseLine()
This method of the ParserTool class is used to parse the raw text in OpenNLP. This method accepts −
A String variable representing the text to be parsed.
A parser object.
An integer representing the no.of parses to be carried out.
This class represents the predefined model which is used to divide a sentence into smaller chunks. This class belongs to the package opennlp.tools.chunker.
The constructor of this class accepts a InputStream object of the chunker model file (enchunker.bin).
This class belongs to the package named opennlp.tools.chunker and it is used to divide the given sentence in to smaller chunks.
chunk()
This method is used to divide the given sentence in to smaller chunks. It accepts tokens of a sentence and Parts Of Speech tags as parameters.
probs()
This method returns the probabilities of the last decoded sequence.
While processing a natural language, deciding the beginning and end of the sentences is one of the problems to be addressed. This process is known as Sentence Boundary Disambiguation (SBD) or simply sentence breaking.
The techniques we use to detect the sentences in the given text, depends on the language of the text.
We can detect the sentences in the given text in Java using, Regular Expressions, and a set of simple rules.
For example, let us assume a period, a question mark, or an exclamation mark ends a sentence in the given text, then we can split the sentence using the split() method of the String class. Here, we have to pass a regular expression in String format.
Following is the program which determines the sentences in a given text using Java regular expressions (split method). Save this program in a file with the name SentenceDetection_RE.java.
public class SentenceDetection_RE {
public static void main(String args[]){
String sentence = " Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
String simple = "[.?!]";
String[] splitString = (sentence.split(simple));
for (String string : splitString)
System.out.println(string);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac SentenceDetection_RE.java
java SentenceDetection_RE
On executing, the above program creates a PDF document displaying the following message.
Hi
How are you
Welcome to Tutorialspoint
We provide free tutorials on various technologies
To detect sentences, OpenNLP uses a predefined model, a file named en-sent.bin. This predefined model is trained to detect sentences in a given raw text.
The opennlp.tools.sentdetect package contains the classes and interfaces that are used to perform the sentence detection task.
To detect a sentence using OpenNLP library, you need to −
Load the en-sent.bin model using the SentenceModel class
Load the en-sent.bin model using the SentenceModel class
Instantiate the SentenceDetectorME class.
Instantiate the SentenceDetectorME class.
Detect the sentences using the sentDetect() method of this class.
Detect the sentences using the sentDetect() method of this class.
Following are the steps to be followed to write a program which detects the sentences from the given raw text.
The model for sentence detection is represented by the class named SentenceModel, which belongs to the package opennlp.tools.sentdetect.
To load a sentence detection model −
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor as shown in the following code block −
Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor as shown in the following code block −
//Loading sentence detector model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/ensent.bin");
SentenceModel model = new SentenceModel(inputStream);
The SentenceDetectorME class of the package opennlp.tools.sentdetect contains methods to split the raw text into sentences. This class uses the Maximum Entropy model to evaluate end-of-sentence characters in a string to determine if they signify the end of a sentence.
Instantiate this class and pass the model object created in the previous step, as shown below.
//Instantiating the SentenceDetectorME class
SentenceDetectorME detector = new SentenceDetectorME(model);
The sentDetect() method of the SentenceDetectorME class is used to detect the sentences in the raw text passed to it. This method accepts a String variable as a parameter.
Invoke this method by passing the String format of the sentence to this method.
//Detecting the sentence
String sentences[] = detector.sentDetect(sentence);
Example
Following is the program which detects the sentences in a given raw text. Save this program in a file with named SentenceDetectionME.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
public class SentenceDetectionME {
public static void main(String args[]) throws Exception {
String sentence = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Loading sentence detector model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-sent.bin");
SentenceModel model = new SentenceModel(inputStream);
//Instantiating the SentenceDetectorME class
SentenceDetectorME detector = new SentenceDetectorME(model);
//Detecting the sentence
String sentences[] = detector.sentDetect(sentence);
//Printing the sentences
for(String sent : sentences)
System.out.println(sent);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac SentenceDetectorME.java
java SentenceDetectorME
On executing, the above program reads the given String and detects the sentences in it and displays the following output.
Hi. How are you?
Welcome to Tutorialspoint.
We provide free tutorials on various technologies
We can also detect the positions of the sentences using the sentPosDetect() method of the SentenceDetectorME class.
Following are the steps to be followed to write a program which detects the positions of the sentences from the given raw text.
The model for sentence detection is represented by the class named SentenceModel, which belongs to the package opennlp.tools.sentdetect.
To load a sentence detection model −
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block.
Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block.
//Loading sentence detector model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-sent.bin");
SentenceModel model = new SentenceModel(inputStream);
The SentenceDetectorME class of the package opennlp.tools.sentdetect contains methods to split the raw text into sentences. This class uses the Maximum Entropy model to evaluate end-of-sentence characters in a string to determine if they signify the end of a sentence.
Instantiate this class and pass the model object created in the previous step.
//Instantiating the SentenceDetectorME class
SentenceDetectorME detector = new SentenceDetectorME(model);
The sentPosDetect() method of the SentenceDetectorME class is used to detect the positions of the sentences in the raw text passed to it. This method accepts a String variable as a parameter.
Invoke this method by passing the String format of the sentence as a parameter to this method.
//Detecting the position of the sentences in the paragraph
Span[] spans = detector.sentPosDetect(sentence);
The sentPosDetect() method of the SentenceDetectorME class returns an array of objects of the type Span. The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets.
You can store the spans returned by the sentPosDetect() method in the Span array and print them, as shown in the following code block.
//Printing the sentences and their spans of a sentence
for (Span span : spans)
System.out.println(paragraph.substring(span);
Example
Following is the program which detects the sentences in the given raw text. Save this program in a file with named SentenceDetectionME.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.util.Span;
public class SentencePosDetection {
public static void main(String args[]) throws Exception {
String paragraph = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Loading sentence detector model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-sent.bin");
SentenceModel model = new SentenceModel(inputStream);
//Instantiating the SentenceDetectorME class
SentenceDetectorME detector = new SentenceDetectorME(model);
//Detecting the position of the sentences in the raw text
Span spans[] = detector.sentPosDetect(paragraph);
//Printing the spans of the sentences in the paragraph
for (Span span : spans)
System.out.println(span);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac SentencePosDetection.java
java SentencePosDetection
On executing, the above program reads the given String and detects the sentences in it and displays the following output.
[0..16)
[17..43)
[44..93)
The substring() method of the String class accepts the begin and the end offsets and returns the respective string. We can use this method to print the sentences and their spans (positions) together, as shown in the following code block.
for (Span span : spans)
System.out.println(sen.substring(span.getStart(), span.getEnd())+" "+ span);
Following is the program to detect the sentences from the given raw text and display them along with their positions. Save this program in a file with name SentencesAndPosDetection.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.util.Span;
public class SentencesAndPosDetection {
public static void main(String args[]) throws Exception {
String sen = "Hi. How are you? Welcome to Tutorialspoint."
+ " We provide free tutorials on various technologies";
//Loading a sentence model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-sent.bin");
SentenceModel model = new SentenceModel(inputStream);
//Instantiating the SentenceDetectorME class
SentenceDetectorME detector = new SentenceDetectorME(model);
//Detecting the position of the sentences in the paragraph
Span[] spans = detector.sentPosDetect(sen);
//Printing the sentences and their spans of a paragraph
for (Span span : spans)
System.out.println(sen.substring(span.getStart(), span.getEnd())+" "+ span);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac SentencesAndPosDetection.java
java SentencesAndPosDetection
On executing, the above program reads the given String and detects the sentences along with their positions and displays the following output.
Hi. How are you? [0..16)
Welcome to Tutorialspoint. [17..43)
We provide free tutorials on various technologies [44..93)
The getSentenceProbabilities() method of the SentenceDetectorME class returns the probabilities associated with the most recent calls to the sentDetect() method.
//Getting the probabilities of the last decoded sequence
double[] probs = detector.getSentenceProbabilities();
Following is the program to print the probabilities associated with the calls to the sentDetect() method. Save this program in a file with the name SentenceDetectionMEProbs.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
public class SentenceDetectionMEProbs {
public static void main(String args[]) throws Exception {
String sentence = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Loading sentence detector model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-sent.bin");
SentenceModel model = new SentenceModel(inputStream);
//Instantiating the SentenceDetectorME class
SentenceDetectorME detector = new SentenceDetectorME(model);
//Detecting the sentence
String sentences[] = detector.sentDetect(sentence);
//Printing the sentences
for(String sent : sentences)
System.out.println(sent);
//Getting the probabilities of the last decoded sequence
double[] probs = detector.getSentenceProbabilities();
System.out.println(" ");
for(int i = 0; i<probs.length; i++)
System.out.println(probs[i]);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac SentenceDetectionMEProbs.java
java SentenceDetectionMEProbs
On executing, the above program reads the given String and detects the sentences and prints them. In addition, it also returns the probabilities associated with the most recent calls to the sentDetect() method, as shown below.
Hi. How are you?
Welcome to Tutorialspoint.
We provide free tutorials on various technologies
0.9240246995179983
0.9957680129995953
1.0
The process of chopping the given sentence into smaller parts (tokens) is known as tokenization. In general, the given raw text is tokenized based on a set of delimiters (mostly whitespaces).
Tokenization is used in tasks such as spell-checking, processing searches, identifying parts of speech, sentence detection, document classification of documents, etc.
The opennlp.tools.tokenize package contains the classes and interfaces that are used to perform tokenization.
To tokenize the given sentences into simpler fragments, the OpenNLP library provides three different classes −
SimpleTokenizer − This class tokenizes the given raw text using character classes.
SimpleTokenizer − This class tokenizes the given raw text using character classes.
WhitespaceTokenizer − This class uses whitespaces to tokenize the given text.
WhitespaceTokenizer − This class uses whitespaces to tokenize the given text.
TokenizerME − This class converts raw text into separate tokens. It uses Maximum Entropy to make its decisions.
TokenizerME − This class converts raw text into separate tokens. It uses Maximum Entropy to make its decisions.
To tokenize a sentence using the SimpleTokenizer class, you need to −
Create an object of the respective class.
Create an object of the respective class.
Tokenize the sentence using the tokenize() method.
Tokenize the sentence using the tokenize() method.
Print the tokens.
Print the tokens.
Following are the steps to be followed to write a program which tokenizes the given raw text.
Step 1 − Instantiating the respective class
In both the classes, there are no constructors available to instantiate them. Therefore, we need to create objects of these classes using the static variable INSTANCE.
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
Step 2 − Tokenize the sentences
Both these classes contain a method called tokenize(). This method accepts a raw text in String format. On invoking, it tokenizes the given String and returns an array of Strings (tokens).
Tokenize the sentence using the tokenizer() method as shown below.
//Tokenizing the given sentence
String tokens[] = tokenizer.tokenize(sentence);
Step 3 − Print the tokens
After tokenizing the sentence, you can print the tokens using for loop, as shown below.
//Printing the tokens
for(String token : tokens)
System.out.println(token);
Example
Following is the program which tokenizes the given sentence using the SimpleTokenizer class. Save this program in a file with the name SimpleTokenizerExample.java.
import opennlp.tools.tokenize.SimpleTokenizer;
public class SimpleTokenizerExample {
public static void main(String args[]){
String sentence = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Instantiating SimpleTokenizer class
SimpleTokenizer simpleTokenizer = SimpleTokenizer.INSTANCE;
//Tokenizing the given sentence
String tokens[] = simpleTokenizer.tokenize(sentence);
//Printing the tokens
for(String token : tokens) {
System.out.println(token);
}
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac SimpleTokenizerExample.java
java SimpleTokenizerExample
On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −
Hi
.
How
are
you
?
Welcome
to
Tutorialspoint
.
We
provide
free
tutorials
on
various
technologies
To tokenize a sentence using the WhitespaceTokenizer class, you need to −
Create an object of the respective class.
Create an object of the respective class.
Tokenize the sentence using the tokenize() method.
Tokenize the sentence using the tokenize() method.
Print the tokens.
Print the tokens.
Following are the steps to be followed to write a program which tokenizes the given raw text.
Step 1 − Instantiating the respective class
In both the classes, there are no constructors available to instantiate them. Therefore, we need to create objects of these classes using the static variable INSTANCE.
WhitespaceTokenizer tokenizer = WhitespaceTokenizer.INSTANCE;
Step 2 − Tokenize the sentences
Both these classes contain a method called tokenize(). This method accepts a raw text in String format. On invoking, it tokenizes the given String and returns an array of Strings (tokens).
Tokenize the sentence using the tokenizer() method as shown below.
//Tokenizing the given sentence
String tokens[] = tokenizer.tokenize(sentence);
Step 3 − Print the tokens
After tokenizing the sentence, you can print the tokens using for loop, as shown below.
//Printing the tokens
for(String token : tokens)
System.out.println(token);
Example
Following is the program which tokenizes the given sentence using the WhitespaceTokenizer class. Save this program in a file with the name WhitespaceTokenizerExample.java.
import opennlp.tools.tokenize.WhitespaceTokenizer;
public class WhitespaceTokenizerExample {
public static void main(String args[]){
String sentence = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Instantiating whitespaceTokenizer class
WhitespaceTokenizer whitespaceTokenizer = WhitespaceTokenizer.INSTANCE;
//Tokenizing the given paragraph
String tokens[] = whitespaceTokenizer.tokenize(sentence);
//Printing the tokens
for(String token : tokens)
System.out.println(token);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac WhitespaceTokenizerExample.java
java WhitespaceTokenizerExample
On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output.
Hi.
How
are
you?
Welcome
to
Tutorialspoint.
We
provide
free
tutorials
on
various
technologies
OpenNLP also uses a predefined model, a file named de-token.bin, to tokenize the sentences. It is trained to tokenize the sentences in a given raw text.
The TokenizerME class of the opennlp.tools.tokenizer package is used to load this model, and tokenize the given raw text using OpenNLP library. To do so, you need to −
Load the en-token.bin model using the TokenizerModel class.
Load the en-token.bin model using the TokenizerModel class.
Instantiate the TokenizerME class.
Instantiate the TokenizerME class.
Tokenize the sentences using the tokenize() method of this class.
Tokenize the sentences using the tokenize() method of this class.
Following are the steps to be followed to write a program which tokenizes the sentences from the given raw text using the TokenizerME class.
Step 1 − Loading the model
The model for tokenization is represented by the class named TokenizerModel, which belongs to the package opennlp.tools.tokenize.
To load a tokenizer model −
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Instantiate the TokenizerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block.
Instantiate the TokenizerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block.
//Loading the Tokenizer model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-token.bin");
TokenizerModel tokenModel = new TokenizerModel(inputStream);
Step 2 − Instantiating the TokenizerME class
The TokenizerME class of the package opennlp.tools.tokenize contains methods to chop the raw text into smaller parts (tokens). It uses Maximum Entropy to make its decisions.
Instantiate this class and pass the model object created in the previous step as shown below.
//Instantiating the TokenizerME class
TokenizerME tokenizer = new TokenizerME(tokenModel);
Step 3 − Tokenizing the sentence
The tokenize() method of the TokenizerME class is used to tokenize the raw text passed to it. This method accepts a String variable as a parameter, and returns an array of Strings (tokens).
Invoke this method by passing the String format of the sentence to this method, as follows.
//Tokenizing the given raw text
String tokens[] = tokenizer.tokenize(paragraph);
Example
Following is the program which tokenizes the given raw text. Save this program in a file with the name TokenizerMEExample.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
public class TokenizerMEExample {
public static void main(String args[]) throws Exception{
String sentence = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Loading the Tokenizer model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-token.bin");
TokenizerModel tokenModel = new TokenizerModel(inputStream);
//Instantiating the TokenizerME class
TokenizerME tokenizer = new TokenizerME(tokenModel);
//Tokenizing the given raw text
String tokens[] = tokenizer.tokenize(sentence);
//Printing the tokens
for (String a : tokens)
System.out.println(a);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac TokenizerMEExample.java
java TokenizerMEExample
On executing, the above program reads the given String and detects the sentences in it and displays the following output −
Hi
.
How
are
you
?
Welcome
to
Tutorialspoint
.
We
provide
free
tutorials
on
various
technologie
We can also get the positions or spans of the tokens using the tokenizePos() method. This is the method of the Tokenizer interface of the package opennlp.tools.tokenize. Since all the (three) Tokenizer classes implement this interface, you can find this method in all of them.
This method accepts the sentence or raw text in the form of a string and returns an array of objects of the type Span.
You can get the positions of the tokens using the tokenizePos() method, as follows −
//Retrieving the tokens
tokenizer.tokenizePos(sentence);
The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets.
You can store the spans returned by the tokenizePos() method in the Span array and print them, as shown in the following code block.
//Retrieving the tokens
Span[] tokens = tokenizer.tokenizePos(sentence);
//Printing the spans of tokens
for( Span token : tokens)
System.out.println(token);
The substring() method of the String class accepts the begin and the end offsets and returns the respective string. We can use this method to print the tokens and their spans (positions) together, as shown in the following code block.
//Printing the spans of tokens
for(Span token : tokens)
System.out.println(token +" "+sent.substring(token.getStart(), token.getEnd()));
Example(SimpleTokenizer)
Following is the program which retrieves the token spans of the raw text using the SimpleTokenizer class. It also prints the tokens along with their positions. Save this program in a file with named SimpleTokenizerSpans.java.
import opennlp.tools.tokenize.SimpleTokenizer;
import opennlp.tools.util.Span;
public class SimpleTokenizerSpans {
public static void main(String args[]){
String sent = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Instantiating SimpleTokenizer class
SimpleTokenizer simpleTokenizer = SimpleTokenizer.INSTANCE;
//Retrieving the boundaries of the tokens
Span[] tokens = simpleTokenizer.tokenizePos(sent);
//Printing the spans of tokens
for( Span token : tokens)
System.out.println(token +" "+sent.substring(token.getStart(), token.getEnd()));
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac SimpleTokenizerSpans.java
java SimpleTokenizerSpans
On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −
[0..2) Hi
[2..3) .
[4..7) How
[8..11) are
[12..15) you
[15..16) ?
[17..24) Welcome
[25..27) to
[28..42) Tutorialspoint
[42..43) .
[44..46) We
[47..54) provide
[55..59) free
[60..69) tutorials
[70..72) on
[73..80) various
[81..93) technologies
Example (WhitespaceTokenizer)
Following is the program which retrieves the token spans of the raw text using the WhitespaceTokenizer class. It also prints the tokens along with their positions. Save this program in a file with the name WhitespaceTokenizerSpans.java.
import opennlp.tools.tokenize.WhitespaceTokenizer;
import opennlp.tools.util.Span;
public class WhitespaceTokenizerSpans {
public static void main(String args[]){
String sent = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Instantiating SimpleTokenizer class
WhitespaceTokenizer whitespaceTokenizer = WhitespaceTokenizer.INSTANCE;
//Retrieving the tokens
Span[] tokens = whitespaceTokenizer.tokenizePos(sent);
//Printing the spans of tokens
for( Span token : tokens)
System.out.println(token +"
"+sent.substring(token.getStart(), token.getEnd()));
}
}
Compile and execute the saved java file from the command prompt using the following commands
javac WhitespaceTokenizerSpans.java
java WhitespaceTokenizerSpans
On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output.
[0..3) Hi.
[4..7) How
[8..11) are
[12..16) you?
[17..24) Welcome
[25..27) to
[28..43) Tutorialspoint.
[44..46) We
[47..54) provide
[55..59) free
[60..69) tutorials
[70..72) on
[73..80) various
[81..93) technologies
Example (TokenizerME)
Following is the program which retrieves the token spans of the raw text using the TokenizerME class. It also prints the tokens along with their positions. Save this program in a file with the name TokenizerMESpans.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.Span;
public class TokenizerMESpans {
public static void main(String args[]) throws Exception{
String sent = "Hello John how are you welcome to Tutorialspoint";
//Loading the Tokenizer model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-token.bin");
TokenizerModel tokenModel = new TokenizerModel(inputStream);
//Instantiating the TokenizerME class
TokenizerME tokenizer = new TokenizerME(tokenModel);
//Retrieving the positions of the tokens
Span tokens[] = tokenizer.tokenizePos(sent);
//Printing the spans of tokens
for(Span token : tokens)
System.out.println(token +" "+sent.substring(token.getStart(), token.getEnd()));
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac TokenizerMESpans.java
java TokenizerMESpans
On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −
[0..5) Hello
[6..10) John
[11..14) how
[15..18) are
[19..22) you
[23..30) welcome
[31..33) to
[34..48) Tutorialspoint
The getTokenProbabilities() method of the TokenizerME class is used to get the probabilities associated with the most recent calls to the tokenizePos() method.
//Getting the probabilities of the recent calls to tokenizePos() method
double[] probs = detector.getSentenceProbabilities();
Following is the program to print the probabilities associated with the calls to tokenizePos() method. Save this program in a file with the name TokenizerMEProbs.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.Span;
public class TokenizerMEProbs {
public static void main(String args[]) throws Exception{
String sent = "Hello John how are you welcome to Tutorialspoint";
//Loading the Tokenizer model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-token.bin");
TokenizerModel tokenModel = new TokenizerModel(inputStream);
//Instantiating the TokenizerME class
TokenizerME tokenizer = new TokenizerME(tokenModel);
//Retrieving the positions of the tokens
Span tokens[] = tokenizer.tokenizePos(sent);
//Getting the probabilities of the recent calls to tokenizePos() method
double[] probs = tokenizer.getTokenProbabilities();
//Printing the spans of tokens
for(Span token : tokens)
System.out.println(token +" "+sent.substring(token.getStart(), token.getEnd()));
System.out.println(" ");
for(int i = 0; i<probs.length; i++)
System.out.println(probs[i]);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac TokenizerMEProbs.java
java TokenizerMEProbs
On executing, the above program reads the given String and tokenizes the sentences and prints them. In addition, it also returns the probabilities associated with the most recent calls to the tokenizerPos() method.
[0..5) Hello
[6..10) John
[11..14) how
[15..18) are
[19..22) you
[23..30) welcome
[31..33) to
[34..48) Tutorialspoint
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
The process of finding names, people, places, and other entities, from a given text is known as Named Entity Recognition (NER). In this chapter, we will discuss how to carry out NER through Java program using OpenNLP library.
To perform various NER tasks, OpenNLP uses different predefined models namely, en-nerdate.bn, en-ner-location.bin, en-ner-organization.bin, en-ner-person.bin, and en-ner-time.bin. All these files are predefined models which are trained to detect the respective entities in a given raw text.
The opennlp.tools.namefind package contains the classes and interfaces that are used to perform the NER task. To perform NER task using OpenNLP library, you need to −
Load the respective model using the TokenNameFinderModel class.
Load the respective model using the TokenNameFinderModel class.
Instantiate the NameFinder class.
Instantiate the NameFinder class.
Find the names and print them.
Find the names and print them.
Following are the steps to be followed to write a program which detects the name entities from a given raw text.
The model for sentence detection is represented by the class named TokenNameFinderModel, which belongs to the package opennlp.tools.namefind.
To load an NER model −
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the appropriate NER model in String format to its constructor).
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the appropriate NER model in String format to its constructor).
Instantiate the TokenNameFinderModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block.
Instantiate the TokenNameFinderModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block.
//Loading the NER-person model
InputStream inputStreamNameFinder = new FileInputStream(".../en-nerperson.bin");
TokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder);
The NameFinderME class of the package opennlp.tools.namefind contains methods to perform the NER tasks. This class uses the Maximum Entropy model to find the named entities in the given raw text.
Instantiate this class and pass the model object created in the previous step as shown below −
//Instantiating the NameFinderME class
NameFinderME nameFinder = new NameFinderME(model);
The find() method of the NameFinderME class is used to detect the names in the raw text passed to it. This method accepts a String variable as a parameter.
Invoke this method by passing the String format of the sentence to this method.
//Finding the names in the sentence
Span nameSpans[] = nameFinder.find(sentence);
The find() method of the NameFinderME class returns an array of objects of the type Span. The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets.
You can store the spans returned by the find() method in the Span array and print them, as shown in the following code block.
//Printing the sentences and their spans of a sentence
for (Span span : spans)
System.out.println(paragraph.substring(span);
NER Example
Following is the program which reads the given sentence and recognizes the spans of the names of the persons in it. Save this program in a file with the name NameFinderME_Example.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.util.Span;
public class NameFinderME_Example {
public static void main(String args[]) throws Exception{
/Loading the NER - Person model InputStream inputStream = new
FileInputStream("C:/OpenNLP_models/en-ner-person.bin");
TokenNameFinderModel model = new TokenNameFinderModel(inputStream);
//Instantiating the NameFinder class
NameFinderME nameFinder = new NameFinderME(model);
//Getting the sentence in the form of String array
String [] sentence = new String[]{
"Mike",
"and",
"Smith",
"are",
"good",
"friends"
};
//Finding the names in the sentence
Span nameSpans[] = nameFinder.find(sentence);
//Printing the spans of the names in the sentence
for(Span s: nameSpans)
System.out.println(s.toString());
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac NameFinderME_Example.java
java NameFinderME_Example
On executing, the above program reads the given String (raw text), detects the names of the persons in it, and displays their positions (spans), as shown below.
[0..1) person
[2..3) person
The substring() method of the String class accepts the begin and the end offsets and returns the respective string. We can use this method to print the names and their spans (positions) together, as shown in the following code block.
for(Span s: nameSpans)
System.out.println(s.toString()+" "+tokens[s.getStart()]);
Following is the program to detect the names from the given raw text and display them along with their positions. Save this program in a file with the name NameFinderSentences.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.Span;
public class NameFinderSentences {
public static void main(String args[]) throws Exception{
//Loading the tokenizer model
InputStream inputStreamTokenizer = new
FileInputStream("C:/OpenNLP_models/entoken.bin");
TokenizerModel tokenModel = new TokenizerModel(inputStreamTokenizer);
//Instantiating the TokenizerME class
TokenizerME tokenizer = new TokenizerME(tokenModel);
//Tokenizing the sentence in to a string array
String sentence = "Mike is senior programming
manager and Rama is a clerk both are working at
Tutorialspoint";
String tokens[] = tokenizer.tokenize(sentence);
//Loading the NER-person model
InputStream inputStreamNameFinder = new
FileInputStream("C:/OpenNLP_models/enner-person.bin");
TokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder);
//Instantiating the NameFinderME class
NameFinderME nameFinder = new NameFinderME(model);
//Finding the names in the sentence
Span nameSpans[] = nameFinder.find(tokens);
//Printing the names and their spans in a sentence
for(Span s: nameSpans)
System.out.println(s.toString()+" "+tokens[s.getStart()]);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac NameFinderSentences.java
java NameFinderSentences
On executing, the above program reads the given String (raw text), detects the names of the persons in it, and displays their positions (spans) as shown below.
[0..1) person Mike
By loading various models, you can detect various named entities. Following is a Java program which loads the en-ner-location.bin model and detects the location names in the given sentence. Save this program in a file with the name LocationFinder.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.Span;
public class LocationFinder {
public static void main(String args[]) throws Exception{
InputStream inputStreamTokenizer = new
FileInputStream("C:/OpenNLP_models/entoken.bin");
TokenizerModel tokenModel = new TokenizerModel(inputStreamTokenizer);
//String paragraph = "Mike and Smith are classmates";
String paragraph = "Tutorialspoint is located in Hyderabad";
//Instantiating the TokenizerME class
TokenizerME tokenizer = new TokenizerME(tokenModel);
String tokens[] = tokenizer.tokenize(paragraph);
//Loading the NER-location moodel
InputStream inputStreamNameFinder = new
FileInputStream("C:/OpenNLP_models/en- ner-location.bin");
TokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder);
//Instantiating the NameFinderME class
NameFinderME nameFinder = new NameFinderME(model);
//Finding the names of a location
Span nameSpans[] = nameFinder.find(tokens);
//Printing the spans of the locations in the sentence
for(Span s: nameSpans)
System.out.println(s.toString()+" "+tokens[s.getStart()]);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac LocationFinder.java
java LocationFinder
On executing, the above program reads the given String (raw text), detects the names of the persons in it, and displays their positions (spans), as shown below.
[4..5) location Hyderabad
The probs()method of the NameFinderME class is used to get the probabilities of the last decoded sequence.
double[] probs = nameFinder.probs();
Following is the program to print the probabilities. Save this program in a file with the name TokenizerMEProbs.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.Span;
public class TokenizerMEProbs {
public static void main(String args[]) throws Exception{
String sent = "Hello John how are you welcome to Tutorialspoint";
//Loading the Tokenizer model
InputStream inputStream = new
FileInputStream("C:/OpenNLP_models/en-token.bin");
TokenizerModel tokenModel = new TokenizerModel(inputStream);
//Instantiating the TokenizerME class
TokenizerME tokenizer = new TokenizerME(tokenModel);
//Retrieving the positions of the tokens
Span tokens[] = tokenizer.tokenizePos(sent);
//Getting the probabilities of the recent calls to tokenizePos() method
double[] probs = tokenizer.getTokenProbabilities();
//Printing the spans of tokens
for( Span token : tokens)
System.out.println(token +"
"+sent.substring(token.getStart(), token.getEnd()));
System.out.println(" ");
for(int i = 0; i<probs.length; i++)
System.out.println(probs[i]);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac TokenizerMEProbs.java
java TokenizerMEProbs
On executing, the above program reads the given String, tokenizes the sentences, and prints them. In addition, it also returns the probabilities of the last decoded sequence, as shown below.
[0..5) Hello
[6..10) John
[11..14) how
[15..18) are
[19..22) you
[23..30) welcome
[31..33) to
[34..48) Tutorialspoint
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
Using OpenNLP, you can also detect the Parts of Speech of a given sentence and print them. Instead of full name of the parts of speech, OpenNLP uses short forms of each parts of speech. The following table indicates the various parts of speeches detected by OpenNLP and their meanings.
To tag the parts of speech of a sentence, OpenNLP uses a model, a file named en-posmaxent.bin. This is a predefined model which is trained to tag the parts of speech of the given raw text.
The POSTaggerME class of the opennlp.tools.postag package is used to load this model, and tag the parts of speech of the given raw text using OpenNLP library. To do so, you need to −
Load the en-pos-maxent.bin model using the POSModel class.
Load the en-pos-maxent.bin model using the POSModel class.
Instantiate the POSTaggerME class.
Instantiate the POSTaggerME class.
Tokenize the sentence.
Tokenize the sentence.
Generate the tags using tag() method.
Generate the tags using tag() method.
Print the tokens and tags using POSSample class.
Print the tokens and tags using POSSample class.
Following are the steps to be followed to write a program which tags the parts of the speech in the given raw text using the POSTaggerME class.
The model for POS tagging is represented by the class named POSModel, which belongs to the package opennlp.tools.postag.
To load a tokenizer model −
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Instantiate the POSModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block −
Instantiate the POSModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block −
//Loading Parts of speech-maxent model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-pos-maxent.bin");
POSModel model = new POSModel(inputStream);
The POSTaggerME class of the package opennlp.tools.postag is used to predict the parts of speech of the given raw text. It uses Maximum Entropy to make its decisions.
Instantiate this class and pass the model object created in the previous step, as shown below −
//Instantiating POSTaggerME class
POSTaggerME tagger = new POSTaggerME(model);
The tokenize() method of the whitespaceTokenizer class is used to tokenize the raw text passed to it. This method accepts a String variable as a parameter, and returns an array of Strings (tokens).
Instantiate the whitespaceTokenizer class and the invoke this method by passing the String format of the sentence to this method.
//Tokenizing the sentence using WhitespaceTokenizer class
WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE;
String[] tokens = whitespaceTokenizer.tokenize(sentence);
The tag() method of the whitespaceTokenizer class assigns POS tags to the sentence of tokens. This method accepts an array of tokens (String) as a parameter and returns tag (array).
Invoke the tag() method by passing the tokens generated in the previous step to it.
//Generating tags
String[] tags = tagger.tag(tokens);
The POSSample class represents the POS-tagged sentence. To instantiate this class, we would require an array of tokens (of the text) and an array of tags.
The toString() method of this class returns the tagged sentence. Instantiate this class by passing the token and the tag arrays created in the previous steps and invoke its toString() method, as shown in the following code block.
//Instantiating the POSSample class
POSSample sample = new POSSample(tokens, tags);
System.out.println(sample.toString());
Example
Following is the program which tags the parts of speech in a given raw text. Save this program in a file with the name PosTaggerExample.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSSample;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.tokenize.WhitespaceTokenizer;
public class PosTaggerExample {
public static void main(String args[]) throws Exception{
//Loading Parts of speech-maxent model
InputStream inputStream = new
FileInputStream("C:/OpenNLP_models/en-pos-maxent.bin");
POSModel model = new POSModel(inputStream);
//Instantiating POSTaggerME class
POSTaggerME tagger = new POSTaggerME(model);
String sentence = "Hi welcome to Tutorialspoint";
//Tokenizing the sentence using WhitespaceTokenizer class
WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE;
String[] tokens = whitespaceTokenizer.tokenize(sentence);
//Generating tags
String[] tags = tagger.tag(tokens);
//Instantiating the POSSample class
POSSample sample = new POSSample(tokens, tags);
System.out.println(sample.toString());
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac PosTaggerExample.java
java PosTaggerExample
On executing, the above program reads the given text and detects the parts of speech of these sentences and displays them, as shown below.
Hi_NNP welcome_JJ to_TO Tutorialspoint_VB
Following is the program which tags the parts of speech of a given raw text. It also monitors the performance and displays the performance of the tagger. Save this program in a file with the name PosTagger_Performance.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.cmdline.PerformanceMonitor;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSSample;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.tokenize.WhitespaceTokenizer;
public class PosTagger_Performance {
public static void main(String args[]) throws Exception{
//Loading Parts of speech-maxent model
InputStream inputStream = new
FileInputStream("C:/OpenNLP_models/en-pos-maxent.bin");
POSModel model = new POSModel(inputStream);
//Creating an object of WhitespaceTokenizer class
WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE;
//Tokenizing the sentence
String sentence = "Hi welcome to Tutorialspoint";
String[] tokens = whitespaceTokenizer.tokenize(sentence);
//Instantiating POSTaggerME class
POSTaggerME tagger = new POSTaggerME(model);
//Generating tags
String[] tags = tagger.tag(tokens);
//Instantiating POSSample class
POSSample sample = new POSSample(tokens, tags);
System.out.println(sample.toString());
//Monitoring the performance of POS tagger
PerformanceMonitor perfMon = new PerformanceMonitor(System.err, "sent");
perfMon.start();
perfMon.incrementCounter();
perfMon.stopAndPrintFinalResult();
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac PosTaggerExample.java
java PosTaggerExample
On executing, the above program reads the given text and tags the parts of speech of these sentences and displays them. In addition, it also monitors the performance of the POS tagger and displays it.
Hi_NNP welcome_JJ to_TO Tutorialspoint_VB
Average: 0.0 sent/s
Total: 1 sent
Runtime: 0.0s
The probs() method of the POSTaggerME class is used to find the probabilities for each tag of the recently tagged sentence.
//Getting the probabilities of the recent calls to tokenizePos() method
double[] probs = detector.getSentenceProbabilities();
Following is the program which displays the probabilities for each tag of the last tagged sentence. Save this program in a file with the name PosTaggerProbs.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSSample;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.tokenize.WhitespaceTokenizer;
public class PosTaggerProbs {
public static void main(String args[]) throws Exception{
//Loading Parts of speech-maxent model
InputStream inputStream = new FileInputStream("C:/OpenNLP_mdl/en-pos-maxent.bin");
POSModel model = new POSModel(inputStream);
//Creating an object of WhitespaceTokenizer class
WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE;
//Tokenizing the sentence
String sentence = "Hi welcome to Tutorialspoint";
String[] tokens = whitespaceTokenizer.tokenize(sentence);
//Instantiating POSTaggerME class
POSTaggerME tagger = new POSTaggerME(model);
//Generating tags
String[] tags = tagger.tag(tokens);
//Instantiating the POSSample class
POSSample sample = new POSSample(tokens, tags);
System.out.println(sample.toString());
//Probabilities for each tag of the last tagged sentence.
double [] probs = tagger.probs();
System.out.println(" ");
//Printing the probabilities
for(int i = 0; i<probs.length; i++)
System.out.println(probs[i]);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac TokenizerMEProbs.java
java TokenizerMEProbs
On executing, the above program reads the given raw text, tags the parts of speech of each token in it, and displays them. In addition, it also displays the probabilities for each parts of speech in the given sentence, as shown below.
Hi_NNP welcome_JJ to_TO Tutorialspoint_VB
0.6416834779738033
0.42983612874819177
0.8584513635863117
0.4394784478206072
Using OpenNLP API, you can parse the given sentences. In this chapter, we will discuss how to parse raw text using OpenNLP API.
To detect the sentences, OpenNLP uses a predefined model, a file named en-parserchunking.bin. This is a predefined model which is trained to parse the given raw text.
The Parser class of the opennlp.tools.Parser package is used to hold the parse constituents and the ParserTool class of the opennlp.tools.cmdline.parser package is used to parse the content.
Following are the steps to be followed to write a program which parses the given raw text using the ParserTool class.
The model for parsing text is represented by the class named ParserModel, which belongs to the package opennlp.tools.parser.
To load a tokenizer model −
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Instantiate the ParserModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block.
Instantiate the ParserModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block.
//Loading parser model
InputStream inputStream = new FileInputStream(".../en-parserchunking.bin");
ParserModel model = new ParserModel(inputStream);
The Parser class of the package opennlp.tools.parser represents a data structure for holding parse constituents. You can create an object of this class using the static create() method of the ParserFactory class.
Invoke the create() method of the ParserFactory by passing the model object created in the previous step, as shown below −
//Creating a parser Parser parser = ParserFactory.create(model);
The parseLine() method of the ParserTool class is used to parse the raw text in OpenNLP. This method accepts −
a String variable representing the text to be parsed.
a String variable representing the text to be parsed.
a parser object.
a parser object.
an integer representing the number of parses to be carried out.
an integer representing the number of parses to be carried out.
Invoke this method by passing the sentence the following parameters: the parse object created in the previous steps, and an integer representing the required number of parses to be carried out.
//Parsing the sentence
String sentence = "Tutorialspoint is the largest tutorial library.";
Parse topParses[] = ParserTool.parseLine(sentence, parser, 1);
Example
Following is the program which parses the given raw text. Save this program in a file with the name ParserExample.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserExample {
public static void main(String args[]) throws Exception{
//Loading parser model
InputStream inputStream = new FileInputStream(".../en-parserchunking.bin");
ParserModel model = new ParserModel(inputStream);
//Creating a parser
Parser parser = ParserFactory.create(model);
//Parsing the sentence
String sentence = "Tutorialspoint is the largest tutorial library.";
Parse topParses[] = ParserTool.parseLine(sentence, parser, 1);
for (Parse p : topParses)
p.show();
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac ParserExample.java
java ParserExample
On executing, the above program reads the given raw text, parses it, and displays the following output −
(TOP (S (NP (NN Tutorialspoint)) (VP (VBZ is) (NP (DT the) (JJS largest) (NN
tutorial) (NN library.)))))
Chunking a sentences refers to breaking/dividing a sentence into parts of words such as word groups and verb groups.
To detect the sentences, OpenNLP uses a model, a file named en-chunker.bin. This is a predefined model which is trained to chunk the sentences in the given raw text.
The opennlp.tools.chunker package contains the classes and interfaces that are used to find non-recursive syntactic annotation such as noun phrase chunks.
You can chunk a sentence using the method chunk() of the ChunkerME class. This method accepts tokens of a sentence and POS tags as parameters. Therefore, before starting the process of chunking, first of all you need to Tokenize the sentence and generate the parts POS tags of it.
To chunk a sentence using OpenNLP library, you need to −
Tokenize the sentence.
Tokenize the sentence.
Generate POS tags for it.
Generate POS tags for it.
Load the en-chunker.bin model using the ChunkerModel class
Load the en-chunker.bin model using the ChunkerModel class
Instantiate the ChunkerME class.
Instantiate the ChunkerME class.
Chunk the sentences using the chunk() method of this class.
Chunk the sentences using the chunk() method of this class.
Following are the steps to be followed to write a program to chunk sentences from the given raw text.
Tokenize the sentences using the tokenize() method of the whitespaceTokenizer class, as shown in the following code block.
//Tokenizing the sentence
String sentence = "Hi welcome to Tutorialspoint";
WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE;
String[] tokens = whitespaceTokenizer.tokenize(sentence);
Generate the POS tags of the sentence using the tag() method of the POSTaggerME class, as shown in the following code block.
//Generating the POS tags
File file = new File("C:/OpenNLP_models/en-pos-maxent.bin");
POSModel model = new POSModelLoader().load(file);
//Constructing the tagger
POSTaggerME tagger = new POSTaggerME(model);
//Generating tags from the tokens
String[] tags = tagger.tag(tokens);
The model for chunking a sentence is represented by the class named ChunkerModel, which belongs to the package opennlp.tools.chunker.
To load a sentence detection model −
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Instantiate the ChunkerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block −
Instantiate the ChunkerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block −
//Loading the chunker model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-chunker.bin");
ChunkerModel chunkerModel = new ChunkerModel(inputStream);
The chunkerME class of the package opennlp.tools.chunker contains methods to chunk the sentences. This is a maximum-entropy-based chunker.
Instantiate this class and pass the model object created in the previous step.
//Instantiate the ChunkerME class
ChunkerME chunkerME = new ChunkerME(chunkerModel);
The chunk() method of the ChunkerME class is used to chunk the sentences in the raw text passed to it. This method accepts two String arrays representing tokens and tags, as parameters.
Invoke this method by passing the token array and tag array created in the previous steps as parameters.
//Generating the chunks
String result[] = chunkerME.chunk(tokens, tags);
Example
Following is the program to chunk the sentences in the given raw text. Save this program in a file with the name ChunkerExample.java.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import opennlp.tools.chunker.ChunkerME;
import opennlp.tools.chunker.ChunkerModel;
import opennlp.tools.cmdline.postag.POSModelLoader;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.tokenize.WhitespaceTokenizer;
public class ChunkerExample{
public static void main(String args[]) throws IOException {
//Tokenizing the sentence
String sentence = "Hi welcome to Tutorialspoint";
WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE;
String[] tokens = whitespaceTokenizer.tokenize(sentence);
//Generating the POS tags
//Load the parts of speech model
File file = new File("C:/OpenNLP_models/en-pos-maxent.bin");
POSModel model = new POSModelLoader().load(file);
//Constructing the tagger
POSTaggerME tagger = new POSTaggerME(model);
//Generating tags from the tokens
String[] tags = tagger.tag(tokens);
//Loading the chunker model
InputStream inputStream = new
FileInputStream("C:/OpenNLP_models/en-chunker.bin");
ChunkerModel chunkerModel = new ChunkerModel(inputStream);
//Instantiate the ChunkerME class
ChunkerME chunkerME = new ChunkerME(chunkerModel);
//Generating the chunks
String result[] = chunkerME.chunk(tokens, tags);
for (String s : result)
System.out.println(s);
}
}
Compile and execute the saved Java file from the Command prompt using the following command −
javac ChunkerExample.java
java ChunkerExample
On executing, the above program reads the given String and chunks the sentences in it, and displays them as shown below.
Loading POS Tagger model ... done (1.040s)
B-NP
I-NP
B-VP
I-VP
We can also detect the positions or spans of the chunks using the chunkAsSpans() method of the ChunkerME class. This method returns an array of objects of the type Span. The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets.
You can store the spans returned by the chunkAsSpans() method in the Span array and print them, as shown in the following code block.
//Generating the tagged chunk spans
Span[] span = chunkerME.chunkAsSpans(tokens, tags);
for (Span s : span)
System.out.println(s.toString());
Example
Following is the program which detects the sentences in the given raw text. Save this program in a file with the name ChunkerSpansEample.java.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import opennlp.tools.chunker.ChunkerME;
import opennlp.tools.chunker.ChunkerModel;
import opennlp.tools.cmdline.postag.POSModelLoader;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.tokenize.WhitespaceTokenizer;
import opennlp.tools.util.Span;
public class ChunkerSpansEample{
public static void main(String args[]) throws IOException {
//Load the parts of speech model
File file = new File("C:/OpenNLP_models/en-pos-maxent.bin");
POSModel model = new POSModelLoader().load(file);
//Constructing the tagger
POSTaggerME tagger = new POSTaggerME(model);
//Tokenizing the sentence
String sentence = "Hi welcome to Tutorialspoint";
WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE;
String[] tokens = whitespaceTokenizer.tokenize(sentence);
//Generating tags from the tokens
String[] tags = tagger.tag(tokens);
//Loading the chunker model
InputStream inputStream = new
FileInputStream("C:/OpenNLP_models/en-chunker.bin");
ChunkerModel chunkerModel = new ChunkerModel(inputStream);
ChunkerME chunkerME = new ChunkerME(chunkerModel);
//Generating the tagged chunk spans
Span[] span = chunkerME.chunkAsSpans(tokens, tags);
for (Span s : span)
System.out.println(s.toString());
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac ChunkerSpansEample.java
java ChunkerSpansEample
On executing, the above program reads the given String and spans of the chunks in it, and displays the following output −
Loading POS Tagger model ... done (1.059s)
[0..2) NP
[2..4) VP
The probs() method of the ChunkerME class returns the probabilities of the last decoded sequence.
//Getting the probabilities of the last decoded sequence
double[] probs = chunkerME.probs();
Following is the program to print the probabilities of the last decoded sequence by the chunker. Save this program in a file with the name ChunkerProbsExample.java.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import opennlp.tools.chunker.ChunkerME;
import opennlp.tools.chunker.ChunkerModel;
import opennlp.tools.cmdline.postag.POSModelLoader;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.tokenize.WhitespaceTokenizer;
public class ChunkerProbsExample{
public static void main(String args[]) throws IOException {
//Load the parts of speech model
File file = new File("C:/OpenNLP_models/en-pos-maxent.bin");
POSModel model = new POSModelLoader().load(file);
//Constructing the tagger
POSTaggerME tagger = new POSTaggerME(model);
//Tokenizing the sentence
String sentence = "Hi welcome to Tutorialspoint";
WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE;
String[] tokens = whitespaceTokenizer.tokenize(sentence);
//Generating tags from the tokens
String[] tags = tagger.tag(tokens);
//Loading the chunker model
InputStream inputStream = new
FileInputStream("C:/OpenNLP_models/en-chunker.bin");
ChunkerModel cModel = new ChunkerModel(inputStream);
ChunkerME chunkerME = new ChunkerME(cModel);
//Generating the chunk tags
chunkerME.chunk(tokens, tags);
//Getting the probabilities of the last decoded sequence
double[] probs = chunkerME.probs();
for(int i = 0; i<probs.length; i++)
System.out.println(probs[i]);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac ChunkerProbsExample.java
java ChunkerProbsExample
On executing, the above program reads the given String, chunks it, and prints the probabilities of the last decoded sequence.
0.9592746040797778
0.6883933131241501
0.8830563473996004
0.8951150529746051
OpenNLP provides a Command Line Interface (CLI) to carry out different operations through the command line. In this chapter, we will take some examples to show how we can use the OpenNLP Command Line Interface.
Hi. How are you? Welcome to Tutorialspoint. We provide free tutorials on various technologies
> opennlp TokenizerME path_for_models../en-token.bin <inputfile..> outputfile..
C:\> opennlp TokenizerME C:\OpenNLP_models/en-token.bin <input.txt >output.txt
Loading Tokenizer model ... done (0.207s)
Average: 214.3 sent/s
Total: 3 sent
Runtime: 0.014s
Hi . How are you ? Welcome to Tutorialspoint . We provide free tutorials on various technologies
Hi. How are you? Welcome to Tutorialspoint. We provide free tutorials on various technologies
> opennlp SentenceDetector path_for_models../en-token.bin <inputfile..> outputfile..
C:\> opennlp SentenceDetector C:\OpenNLP_models/en-sent.bin <input.txt > output_sendet.txt
Loading Sentence Detector model ... done (0.067s)
Average: 750.0 sent/s
Total: 3 sent
Runtime: 0.004s
Hi. How are you?
Welcome to Tutorialspoint.
We provide free tutorials on various technologies
<START:person> <START:person> Mike <END> <END> is senior programming manager and
<START:person> Rama <END> is a clerk both are working at Tutorialspoint
> opennlp TokenNameFinder path_for_models../en-token.bin <inputfile..
C:\>opennlp TokenNameFinder C:\OpenNLP_models\en-ner-person.bin <input_namefinder.txt
Loading Token Name Finder model ... done (0.730s)
<START:person> <START:person> Mike <END> <END> is senior programming manager and
<START:person> Rama <END> is a clerk both are working at Tutorialspoint
Average: 55.6 sent/s
Total: 1 sent
Runtime: 0.018s
Hi. How are you? Welcome to Tutorialspoint. We provide free tutorials on various technologies
> opennlp POSTagger path_for_models../en-token.bin <inputfile..
C:\>opennlp POSTagger C:\OpenNLP_models/en-pos-maxent.bin < input.txt
Loading POS Tagger model ... done (1.315s)
Hi._NNP How_WRB are_VBP you?_JJ Welcome_NNP to_TO Tutorialspoint._NNP We_PRP
provide_VBP free_JJ tutorials_NNS on_IN various_JJ technologies_NNS
Average: 66.7 sent/s
Total: 1 sent
Runtime: 0.015s
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1991,
"s": 1852,
"text": "NLP is a set of tools used to derive meaningful and useful information from natural language sources such as web pages and text documents."
},
{
"code": null,
"e": 2156,
"s": 1991,
"text": "Apache OpenNLP is an open-source Java library which is used to process natural language text. You can build an efficient text processing service using this library."
},
{
"code": null,
"e": 2329,
"s": 2156,
"text": "OpenNLP provides services such as tokenization, sentence segmentation, part-of-speech tagging, named entity extraction, chunking, parsing, and co-reference resolution, etc."
},
{
"code": null,
"e": 2378,
"s": 2329,
"text": "Following are the notable features of OpenNLP −"
},
{
"code": null,
"e": 2531,
"s": 2378,
"text": "Named Entity Recognition (NER) − Open NLP supports NER, using which you can extract names of locations, people and things even while processing queries."
},
{
"code": null,
"e": 2684,
"s": 2531,
"text": "Named Entity Recognition (NER) − Open NLP supports NER, using which you can extract names of locations, people and things even while processing queries."
},
{
"code": null,
"e": 2803,
"s": 2684,
"text": "Summarize − Using the summarize feature, you can summarize Paragraphs, articles, documents or their collection in NLP."
},
{
"code": null,
"e": 2922,
"s": 2803,
"text": "Summarize − Using the summarize feature, you can summarize Paragraphs, articles, documents or their collection in NLP."
},
{
"code": null,
"e": 3070,
"s": 2922,
"text": "Searching − In OpenNLP, a given search string or its synonyms can be identified in given text, even though the given word is altered or misspelled."
},
{
"code": null,
"e": 3218,
"s": 3070,
"text": "Searching − In OpenNLP, a given search string or its synonyms can be identified in given text, even though the given word is altered or misspelled."
},
{
"code": null,
"e": 3332,
"s": 3218,
"text": "Tagging (POS) − Tagging in NLP is used to divide the text into various grammatical elements for further analysis."
},
{
"code": null,
"e": 3446,
"s": 3332,
"text": "Tagging (POS) − Tagging in NLP is used to divide the text into various grammatical elements for further analysis."
},
{
"code": null,
"e": 3528,
"s": 3446,
"text": "Translation − In NLP, Translation helps in translating one language into another."
},
{
"code": null,
"e": 3610,
"s": 3528,
"text": "Translation − In NLP, Translation helps in translating one language into another."
},
{
"code": null,
"e": 3742,
"s": 3610,
"text": "Information grouping − This option in NLP groups the textual information in the content of the document, just like Parts of speech."
},
{
"code": null,
"e": 3874,
"s": 3742,
"text": "Information grouping − This option in NLP groups the textual information in the content of the document, just like Parts of speech."
},
{
"code": null,
"e": 4042,
"s": 3874,
"text": "Natural Language Generation − It is used for generating information from a database and automating the information reports such as weather analysis or medical reports."
},
{
"code": null,
"e": 4210,
"s": 4042,
"text": "Natural Language Generation − It is used for generating information from a database and automating the information reports such as weather analysis or medical reports."
},
{
"code": null,
"e": 4407,
"s": 4210,
"text": "Feedback Analysis − As the name implies, various types of feedbacks from people are collected, regarding the products, by NLP to analyze how well the product is successful in winning their hearts."
},
{
"code": null,
"e": 4604,
"s": 4407,
"text": "Feedback Analysis − As the name implies, various types of feedbacks from people are collected, regarding the products, by NLP to analyze how well the product is successful in winning their hearts."
},
{
"code": null,
"e": 4725,
"s": 4604,
"text": "Speech recognition − Though it is difficult to analyze human speech, NLP has some builtin features for this requirement."
},
{
"code": null,
"e": 4846,
"s": 4725,
"text": "Speech recognition − Though it is difficult to analyze human speech, NLP has some builtin features for this requirement."
},
{
"code": null,
"e": 5132,
"s": 4846,
"text": "The Apache OpenNLP library provides classes and interfaces to perform various tasks of natural language processing such as sentence detection, tokenization, finding a name, tagging the parts of speech, chunking a sentence, parsing, co-reference resolution, and document categorization."
},
{
"code": null,
"e": 5230,
"s": 5132,
"text": "In addition to these tasks, we can also train and evaluate our own models for any of these tasks."
},
{
"code": null,
"e": 5427,
"s": 5230,
"text": "In addition to the library, OpenNLP also provides a Command Line Interface (CLI), where we can train and evaluate models. We will discuss this topic in detail in the last chapter of this tutorial."
},
{
"code": null,
"e": 5552,
"s": 5427,
"text": "To perform various NLP tasks, OpenNLP provides a set of predefined models. This set includes models for different languages."
},
{
"code": null,
"e": 5644,
"s": 5552,
"text": "You can follow the steps given below to download the predefined models provided by OpenNLP."
},
{
"code": null,
"e": 5768,
"s": 5644,
"text": "Step 1 − Open the index page of OpenNLP models by clicking the following link − http://opennlp.sourceforge.net/models-1.5/."
},
{
"code": null,
"e": 5977,
"s": 5768,
"text": "Step 2 − On visiting the given link, you will get to see a list of components of various languages and the links to download them. Here, you can get the list of all the predefined models provided by OpenNLP."
},
{
"code": null,
"e": 6231,
"s": 5977,
"text": "Download all these models to the folder C:/OpenNLP_models/>, by clicking on their respective links. All these models are language dependent and while using these, you have to make sure that the model language matches with the language of the input text."
},
{
"code": null,
"e": 6279,
"s": 6231,
"text": "In 2010, OpenNLP entered the Apache incubation."
},
{
"code": null,
"e": 6327,
"s": 6279,
"text": "In 2010, OpenNLP entered the Apache incubation."
},
{
"code": null,
"e": 6448,
"s": 6327,
"text": "In 2011, Apache OpenNLP 1.5.2 Incubating was released, and in the same year, it graduated as a top-level Apache project."
},
{
"code": null,
"e": 6569,
"s": 6448,
"text": "In 2011, Apache OpenNLP 1.5.2 Incubating was released, and in the same year, it graduated as a top-level Apache project."
},
{
"code": null,
"e": 6606,
"s": 6569,
"text": "In 2015, OpenNLP was 1.6.0 released."
},
{
"code": null,
"e": 6643,
"s": 6606,
"text": "In 2015, OpenNLP was 1.6.0 released."
},
{
"code": null,
"e": 6773,
"s": 6643,
"text": "In this chapter, we will discuss how you can setup OpenNLP environment in your system. Let’s start with the installation process."
},
{
"code": null,
"e": 6848,
"s": 6773,
"text": "Following are the steps to download Apache OpenNLP library in your system."
},
{
"code": null,
"e": 6955,
"s": 6848,
"text": "Step 1 − Open the homepage of Apache OpenNLP by clicking the following link − https://opennlp.apache.org/."
},
{
"code": null,
"e": 7159,
"s": 6955,
"text": "Step 2 − Now, click on the Downloads link. On clicking, you will be directed to a page where you can find various mirrors which will redirect you to the Apache Software Foundation Distribution directory."
},
{
"code": null,
"e": 7310,
"s": 7159,
"text": "Step 3 − In this page you can find links to download various Apache distributions. Browse through them and find the OpenNLP distribution and click it."
},
{
"code": null,
"e": 7445,
"s": 7310,
"text": "Step 4 − On clicking, you will be redirected to the directory where you can see the index of the OpenNLP distribution, as shown below."
},
{
"code": null,
"e": 7507,
"s": 7445,
"text": "Click on the latest version from the available distributions."
},
{
"code": null,
"e": 7720,
"s": 7507,
"text": "Step 5 − Each distribution provides Source and Binary files of OpenNLP library in various formats. Download the source and binary files, apache-opennlp-1.6.0-bin.zip and apache-opennlp1.6.0-src.zip (for Windows)."
},
{
"code": null,
"e": 7889,
"s": 7720,
"text": "After downloading the OpenNLP library, you need to set its path to the bin directory. Assume that you have downloaded the OpenNLP library to the E drive of your system."
},
{
"code": null,
"e": 7934,
"s": 7889,
"text": "Now, follow the steps that are given below −"
},
{
"code": null,
"e": 7997,
"s": 7934,
"text": "Step 1 − Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 8076,
"s": 7997,
"text": "Step 2 − Click on the 'Environment Variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 8175,
"s": 8076,
"text": "Step 3 − Select the path variable and click the Edit button, as shown in the following screenshot."
},
{
"code": null,
"e": 8376,
"s": 8175,
"text": "Step 4 − In the Edit Environment Variable window, click the New button and add the path for OpenNLP directory E:\\apache-opennlp-1.6.0\\bin and click the OK button, as shown in the following screenshot."
},
{
"code": null,
"e": 8504,
"s": 8376,
"text": "You can set the Eclipse environment for OpenNLP library, either by setting the Build path to the JAR files or by using pom.xml."
},
{
"code": null,
"e": 8565,
"s": 8504,
"text": "Follow the steps given below to install OpenNLP in Eclipse −"
},
{
"code": null,
"e": 8644,
"s": 8565,
"text": "Step 1 − Make sure that you have Eclipse environment installed in your system."
},
{
"code": null,
"e": 8722,
"s": 8644,
"text": "Step 2 − Open Eclipse. Click File → New → Open a new project, as shown below."
},
{
"code": null,
"e": 8845,
"s": 8722,
"text": "Step 3 − You will get the New Project wizard. In this wizard, select Java project and proceed by clicking the Next button."
},
{
"code": null,
"e": 8984,
"s": 8845,
"text": "Step 4 − Next, you will get the New Java Project wizard. Here, you need to create a new project and click the Next button, as shown below."
},
{
"code": null,
"e": 9092,
"s": 8984,
"text": "Step 5 − After creating a new project, right-click on it, select Build Path and click Configure Build Path."
},
{
"code": null,
"e": 9206,
"s": 9092,
"text": "Step 6 − Next, you will get the Java Build Path wizard. Here, click the Add External JARs button, as shown below."
},
{
"code": null,
"e": 9345,
"s": 9206,
"text": "Step 7 − Select the jar files opennlp-tools-1.6.0.jar and opennlp-uima-1.6.0.jar located in the lib folder of apache-opennlp-1.6.0 folder."
},
{
"code": null,
"e": 9444,
"s": 9345,
"text": "On clicking the Open button in the above screen, the selected files will be added to your library."
},
{
"code": null,
"e": 9628,
"s": 9444,
"text": "On clicking OK, you will successfully add the required JAR files to the current project and you can verify these added libraries by expanding the Referenced Libraries, as shown below."
},
{
"code": null,
"e": 9712,
"s": 9628,
"text": "Convert the project into a Maven project and add the following code to its pom.xml."
},
{
"code": null,
"e": 10846,
"s": 9712,
"text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" \nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \nxsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \nhttp://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n <modelVersion>4.0.0</modelVersion> \n <groupId>myproject</groupId> \n <artifactId>myproject</artifactId> \n <version>0.0.1-SNAPSHOT</version> \n <build> \n <sourceDirectory>src</sourceDirectory> \n <plugins> \n <plugin> \n <artifactId>maven-compiler-plugin</artifactId> \n <version>3.5.1</version> \n <configuration> \n <source>1.8</source> \n <target>1.8</target> \n </configuration> \n </plugin> \n </plugins> \n </build> \n <dependencies> \n <dependency> \n <groupId>org.apache.opennlp</groupId> \n <artifactId>opennlp-tools</artifactId> \n <version>1.6.0</version> \n </dependency> \n <dependency> \n <groupId>org.apache.opennlp</groupId> \n <artifactId>opennlp-uima</artifactId> \n <version>1.6.0</version> \n </dependency> \n </dependencies> \n</project> "
},
{
"code": null,
"e": 10976,
"s": 10846,
"text": "In this chapter, we will discuss about the classes and methods that we will be using in the subsequent chapters of this tutorial."
},
{
"code": null,
"e": 11140,
"s": 10976,
"text": "This class represents the predefined model which is used to detect the sentences in the given raw text. This class belongs to the package opennlp.tools.sentdetect."
},
{
"code": null,
"e": 11251,
"s": 11140,
"text": "The constructor of this class accepts an InputStream object of the sentence detector model file (en-sent.bin)."
},
{
"code": null,
"e": 11514,
"s": 11251,
"text": "This class belongs to the package opennlp.tools.sentdetect and it contains methods to split the raw text into sentences. This class uses a maximum entropy model to evaluate end-ofsentence characters in a string to determine if they signify the end of a sentence."
},
{
"code": null,
"e": 11565,
"s": 11514,
"text": "Following are the important methods of this class."
},
{
"code": null,
"e": 11578,
"s": 11565,
"text": "sentDetect()"
},
{
"code": null,
"e": 11774,
"s": 11578,
"text": "This method is used to detect the sentences in the raw text passed to it. It accepts a String variable as a parameter and returns a String array which holds the sentences from the given raw text."
},
{
"code": null,
"e": 11790,
"s": 11774,
"text": "sentPosDetect()"
},
{
"code": null,
"e": 11985,
"s": 11790,
"text": "This method is used to detect the positions of the sentences in the given text. This method accepts a string variable, representing the sentence and returns an array of objects of the type Span."
},
{
"code": null,
"e": 12092,
"s": 11985,
"text": "The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets."
},
{
"code": null,
"e": 12119,
"s": 12092,
"text": "getSentenceProbabilities()"
},
{
"code": null,
"e": 12219,
"s": 12119,
"text": "This method returns the probabilities associated with the most recent calls to sentDetect() method."
},
{
"code": null,
"e": 12367,
"s": 12219,
"text": "This class represents the predefined model which is used to tokenize the given sentence. This class belongs to the package opennlp.tools.tokenizer."
},
{
"code": null,
"e": 12469,
"s": 12367,
"text": "The constructor of this class accepts a InputStream object of the tokenizer model file (entoken.bin)."
},
{
"code": null,
"e": 12607,
"s": 12469,
"text": "To perform tokenization, the OpenNLP library provides three main classes. All the three classes implement the interface called Tokenizer."
},
{
"code": null,
"e": 12623,
"s": 12607,
"text": "SimpleTokenizer"
},
{
"code": null,
"e": 12688,
"s": 12623,
"text": "This class tokenizes the given raw text using character classes."
},
{
"code": null,
"e": 12708,
"s": 12688,
"text": "WhitespaceTokenizer"
},
{
"code": null,
"e": 12764,
"s": 12708,
"text": "This class uses whitespaces to tokenize the given text."
},
{
"code": null,
"e": 12776,
"s": 12764,
"text": "TokenizerME"
},
{
"code": null,
"e": 12875,
"s": 12776,
"text": "This class converts raw text in to separate tokens. It uses Maximum Entropy to make its decisions."
},
{
"code": null,
"e": 12920,
"s": 12875,
"text": "These classes contain the following methods."
},
{
"code": null,
"e": 12931,
"s": 12920,
"text": "tokenize()"
},
{
"code": null,
"e": 13073,
"s": 12931,
"text": "This method is used to tokenize the raw text. This method accepts a String variable as a parameter, and returns an array of Strings (tokens)."
},
{
"code": null,
"e": 13089,
"s": 13073,
"text": "sentPosDetect()"
},
{
"code": null,
"e": 13268,
"s": 13089,
"text": "This method is used to get the positions or spans of the tokens. It accepts the sentence (or) raw text in the form of the string and returns an array of objects of the type Span."
},
{
"code": null,
"e": 13368,
"s": 13268,
"text": "In addition to the above two methods, the TokenizerME class has the getTokenProbabilities() method."
},
{
"code": null,
"e": 13392,
"s": 13368,
"text": "getTokenProbabilities()"
},
{
"code": null,
"e": 13504,
"s": 13392,
"text": "This method is used to get the probabilities associated with the most recent calls to the tokenizePos() method."
},
{
"code": null,
"e": 13669,
"s": 13504,
"text": "This class represents the predefined model which is used to find the named entities in the given sentence. This class belongs to the package opennlp.tools.namefind."
},
{
"code": null,
"e": 13778,
"s": 13669,
"text": "The constructor of this class accepts a InputStream object of the name finder model file (enner-person.bin)."
},
{
"code": null,
"e": 13974,
"s": 13778,
"text": "The class belongs to the package opennlp.tools.namefind and it contains methods to perform the NER tasks. This class uses a maximum entropy model to find the named entities in the given raw text."
},
{
"code": null,
"e": 13981,
"s": 13974,
"text": "find()"
},
{
"code": null,
"e": 14159,
"s": 13981,
"text": "This method is used to detect the names in the raw text. It accepts a String variable representing the raw text as a parameter and, returns an array of objects of the type Span."
},
{
"code": null,
"e": 14167,
"s": 14159,
"text": "probs()"
},
{
"code": null,
"e": 14242,
"s": 14167,
"text": "This method is used to get the probabilities of the last decoded sequence."
},
{
"code": null,
"e": 14405,
"s": 14242,
"text": "This class represents the predefined model which is used to tag the parts of speech of the given sentence. This class belongs to the package opennlp.tools.postag."
},
{
"code": null,
"e": 14513,
"s": 14405,
"text": "The constructor of this class accepts a InputStream object of the pos-tagger model file (enpos-maxent.bin)."
},
{
"code": null,
"e": 14684,
"s": 14513,
"text": "This class belongs to the package opennlp.tools.postag and it is used to predict the parts of speech of the given raw text. It uses Maximum Entropy to make its decisions."
},
{
"code": null,
"e": 14690,
"s": 14684,
"text": "tag()"
},
{
"code": null,
"e": 14845,
"s": 14690,
"text": "This method is used to assign the sentence of tokens POS tags. This method accepts an array of tokens (String) as a parameter, and returns a tags (array)."
},
{
"code": null,
"e": 14872,
"s": 14845,
"text": "getSentenceProbabilities()"
},
{
"code": null,
"e": 14963,
"s": 14872,
"text": "This method is used to get the probabilities for each tag of the recently tagged sentence."
},
{
"code": null,
"e": 15105,
"s": 14963,
"text": "This class represents the predefined model which is used to parse the given sentence. This class belongs to the package opennlp.tools.parser."
},
{
"code": null,
"e": 15214,
"s": 15105,
"text": "The constructor of this class accepts a InputStream object of the parser model file (en-parserchunking.bin)."
},
{
"code": null,
"e": 15303,
"s": 15214,
"text": "This class belongs to the package opennlp.tools.parser and it is used to create parsers."
},
{
"code": null,
"e": 15312,
"s": 15303,
"text": "create()"
},
{
"code": null,
"e": 15446,
"s": 15312,
"text": "This is a static method and it is used to create a parser object. This method accepts the Filestream object of the parser model file."
},
{
"code": null,
"e": 15547,
"s": 15446,
"text": "This class belongs to the opennlp.tools.cmdline.parser package and, it is used to parse the content."
},
{
"code": null,
"e": 15559,
"s": 15547,
"text": "parseLine()"
},
{
"code": null,
"e": 15660,
"s": 15559,
"text": "This method of the ParserTool class is used to parse the raw text in OpenNLP. This method accepts −"
},
{
"code": null,
"e": 15714,
"s": 15660,
"text": "A String variable representing the text to be parsed."
},
{
"code": null,
"e": 15731,
"s": 15714,
"text": "A parser object."
},
{
"code": null,
"e": 15791,
"s": 15731,
"text": "An integer representing the no.of parses to be carried out."
},
{
"code": null,
"e": 15947,
"s": 15791,
"text": "This class represents the predefined model which is used to divide a sentence into smaller chunks. This class belongs to the package opennlp.tools.chunker."
},
{
"code": null,
"e": 16049,
"s": 15947,
"text": "The constructor of this class accepts a InputStream object of the chunker model file (enchunker.bin)."
},
{
"code": null,
"e": 16177,
"s": 16049,
"text": "This class belongs to the package named opennlp.tools.chunker and it is used to divide the given sentence in to smaller chunks."
},
{
"code": null,
"e": 16185,
"s": 16177,
"text": "chunk()"
},
{
"code": null,
"e": 16328,
"s": 16185,
"text": "This method is used to divide the given sentence in to smaller chunks. It accepts tokens of a sentence and Parts Of Speech tags as parameters."
},
{
"code": null,
"e": 16336,
"s": 16328,
"text": "probs()"
},
{
"code": null,
"e": 16404,
"s": 16336,
"text": "This method returns the probabilities of the last decoded sequence."
},
{
"code": null,
"e": 16622,
"s": 16404,
"text": "While processing a natural language, deciding the beginning and end of the sentences is one of the problems to be addressed. This process is known as Sentence Boundary Disambiguation (SBD) or simply sentence breaking."
},
{
"code": null,
"e": 16724,
"s": 16622,
"text": "The techniques we use to detect the sentences in the given text, depends on the language of the text."
},
{
"code": null,
"e": 16833,
"s": 16724,
"text": "We can detect the sentences in the given text in Java using, Regular Expressions, and a set of simple rules."
},
{
"code": null,
"e": 17083,
"s": 16833,
"text": "For example, let us assume a period, a question mark, or an exclamation mark ends a sentence in the given text, then we can split the sentence using the split() method of the String class. Here, we have to pass a regular expression in String format."
},
{
"code": null,
"e": 17271,
"s": 17083,
"text": "Following is the program which determines the sentences in a given text using Java regular expressions (split method). Save this program in a file with the name SentenceDetection_RE.java."
},
{
"code": null,
"e": 17694,
"s": 17271,
"text": "public class SentenceDetection_RE { \n public static void main(String args[]){ \n \n String sentence = \" Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n String simple = \"[.?!]\"; \n String[] splitString = (sentence.split(simple)); \n for (String string : splitString) \n System.out.println(string); \n } \n}"
},
{
"code": null,
"e": 17788,
"s": 17694,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 17847,
"s": 17788,
"text": "javac SentenceDetection_RE.java \njava SentenceDetection_RE"
},
{
"code": null,
"e": 17936,
"s": 17847,
"text": "On executing, the above program creates a PDF document displaying the following message."
},
{
"code": null,
"e": 18031,
"s": 17936,
"text": "Hi \nHow are you \nWelcome to Tutorialspoint \nWe provide free tutorials on various technologies\n"
},
{
"code": null,
"e": 18185,
"s": 18031,
"text": "To detect sentences, OpenNLP uses a predefined model, a file named en-sent.bin. This predefined model is trained to detect sentences in a given raw text."
},
{
"code": null,
"e": 18312,
"s": 18185,
"text": "The opennlp.tools.sentdetect package contains the classes and interfaces that are used to perform the sentence detection task."
},
{
"code": null,
"e": 18370,
"s": 18312,
"text": "To detect a sentence using OpenNLP library, you need to −"
},
{
"code": null,
"e": 18427,
"s": 18370,
"text": "Load the en-sent.bin model using the SentenceModel class"
},
{
"code": null,
"e": 18484,
"s": 18427,
"text": "Load the en-sent.bin model using the SentenceModel class"
},
{
"code": null,
"e": 18526,
"s": 18484,
"text": "Instantiate the SentenceDetectorME class."
},
{
"code": null,
"e": 18568,
"s": 18526,
"text": "Instantiate the SentenceDetectorME class."
},
{
"code": null,
"e": 18634,
"s": 18568,
"text": "Detect the sentences using the sentDetect() method of this class."
},
{
"code": null,
"e": 18700,
"s": 18634,
"text": "Detect the sentences using the sentDetect() method of this class."
},
{
"code": null,
"e": 18811,
"s": 18700,
"text": "Following are the steps to be followed to write a program which detects the sentences from the given raw text."
},
{
"code": null,
"e": 18948,
"s": 18811,
"text": "The model for sentence detection is represented by the class named SentenceModel, which belongs to the package opennlp.tools.sentdetect."
},
{
"code": null,
"e": 18985,
"s": 18948,
"text": "To load a sentence detection model −"
},
{
"code": null,
"e": 19129,
"s": 18985,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 19273,
"s": 19129,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 19429,
"s": 19273,
"text": "Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor as shown in the following code block −"
},
{
"code": null,
"e": 19585,
"s": 19429,
"text": "Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor as shown in the following code block −"
},
{
"code": null,
"e": 19754,
"s": 19585,
"text": "//Loading sentence detector model \nInputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/ensent.bin\"); \nSentenceModel model = new SentenceModel(inputStream);"
},
{
"code": null,
"e": 20023,
"s": 19754,
"text": "The SentenceDetectorME class of the package opennlp.tools.sentdetect contains methods to split the raw text into sentences. This class uses the Maximum Entropy model to evaluate end-of-sentence characters in a string to determine if they signify the end of a sentence."
},
{
"code": null,
"e": 20118,
"s": 20023,
"text": "Instantiate this class and pass the model object created in the previous step, as shown below."
},
{
"code": null,
"e": 20225,
"s": 20118,
"text": "//Instantiating the SentenceDetectorME class \nSentenceDetectorME detector = new SentenceDetectorME(model);"
},
{
"code": null,
"e": 20397,
"s": 20225,
"text": "The sentDetect() method of the SentenceDetectorME class is used to detect the sentences in the raw text passed to it. This method accepts a String variable as a parameter."
},
{
"code": null,
"e": 20477,
"s": 20397,
"text": "Invoke this method by passing the String format of the sentence to this method."
},
{
"code": null,
"e": 20555,
"s": 20477,
"text": "//Detecting the sentence \nString sentences[] = detector.sentDetect(sentence);"
},
{
"code": null,
"e": 20563,
"s": 20555,
"text": "Example"
},
{
"code": null,
"e": 20702,
"s": 20563,
"text": "Following is the program which detects the sentences in a given raw text. Save this program in a file with named SentenceDetectionME.java."
},
{
"code": null,
"e": 21657,
"s": 20702,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.sentdetect.SentenceDetectorME; \nimport opennlp.tools.sentdetect.SentenceModel; \n\npublic class SentenceDetectionME { \n \n public static void main(String args[]) throws Exception { \n \n String sentence = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Loading sentence detector model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-sent.bin\"); \n SentenceModel model = new SentenceModel(inputStream); \n \n //Instantiating the SentenceDetectorME class \n SentenceDetectorME detector = new SentenceDetectorME(model); \n \n //Detecting the sentence\n String sentences[] = detector.sentDetect(sentence); \n \n //Printing the sentences \n for(String sent : sentences) \n System.out.println(sent); \n } \n}"
},
{
"code": null,
"e": 21752,
"s": 21657,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 21807,
"s": 21752,
"text": "javac SentenceDetectorME.java \njava SentenceDetectorME"
},
{
"code": null,
"e": 21929,
"s": 21807,
"text": "On executing, the above program reads the given String and detects the sentences in it and displays the following output."
},
{
"code": null,
"e": 22026,
"s": 21929,
"text": "Hi. How are you? \nWelcome to Tutorialspoint. \nWe provide free tutorials on various technologies\n"
},
{
"code": null,
"e": 22142,
"s": 22026,
"text": "We can also detect the positions of the sentences using the sentPosDetect() method of the SentenceDetectorME class."
},
{
"code": null,
"e": 22270,
"s": 22142,
"text": "Following are the steps to be followed to write a program which detects the positions of the sentences from the given raw text."
},
{
"code": null,
"e": 22407,
"s": 22270,
"text": "The model for sentence detection is represented by the class named SentenceModel, which belongs to the package opennlp.tools.sentdetect."
},
{
"code": null,
"e": 22444,
"s": 22407,
"text": "To load a sentence detection model −"
},
{
"code": null,
"e": 22588,
"s": 22444,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 22732,
"s": 22588,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 22888,
"s": 22732,
"text": "Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block."
},
{
"code": null,
"e": 23044,
"s": 22888,
"text": "Instantiate the SentenceModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block."
},
{
"code": null,
"e": 23214,
"s": 23044,
"text": "//Loading sentence detector model \nInputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-sent.bin\"); \nSentenceModel model = new SentenceModel(inputStream);"
},
{
"code": null,
"e": 23483,
"s": 23214,
"text": "The SentenceDetectorME class of the package opennlp.tools.sentdetect contains methods to split the raw text into sentences. This class uses the Maximum Entropy model to evaluate end-of-sentence characters in a string to determine if they signify the end of a sentence."
},
{
"code": null,
"e": 23562,
"s": 23483,
"text": "Instantiate this class and pass the model object created in the previous step."
},
{
"code": null,
"e": 23670,
"s": 23562,
"text": "//Instantiating the SentenceDetectorME class \nSentenceDetectorME detector = new SentenceDetectorME(model); "
},
{
"code": null,
"e": 23862,
"s": 23670,
"text": "The sentPosDetect() method of the SentenceDetectorME class is used to detect the positions of the sentences in the raw text passed to it. This method accepts a String variable as a parameter."
},
{
"code": null,
"e": 23957,
"s": 23862,
"text": "Invoke this method by passing the String format of the sentence as a parameter to this method."
},
{
"code": null,
"e": 24068,
"s": 23957,
"text": "//Detecting the position of the sentences in the paragraph \nSpan[] spans = detector.sentPosDetect(sentence); "
},
{
"code": null,
"e": 24280,
"s": 24068,
"text": "The sentPosDetect() method of the SentenceDetectorME class returns an array of objects of the type Span. The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets."
},
{
"code": null,
"e": 24415,
"s": 24280,
"text": "You can store the spans returned by the sentPosDetect() method in the Span array and print them, as shown in the following code block."
},
{
"code": null,
"e": 24551,
"s": 24415,
"text": "//Printing the sentences and their spans of a sentence \nfor (Span span : spans) \nSystem.out.println(paragraph.substring(span); "
},
{
"code": null,
"e": 24559,
"s": 24551,
"text": "Example"
},
{
"code": null,
"e": 24700,
"s": 24559,
"text": "Following is the program which detects the sentences in the given raw text. Save this program in a file with named SentenceDetectionME.java."
},
{
"code": null,
"e": 25753,
"s": 24700,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n \nimport opennlp.tools.sentdetect.SentenceDetectorME; \nimport opennlp.tools.sentdetect.SentenceModel; \nimport opennlp.tools.util.Span;\n\npublic class SentencePosDetection { \n \n public static void main(String args[]) throws Exception { \n \n String paragraph = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Loading sentence detector model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-sent.bin\"); \n SentenceModel model = new SentenceModel(inputStream); \n \n //Instantiating the SentenceDetectorME class \n SentenceDetectorME detector = new SentenceDetectorME(model); \n \n //Detecting the position of the sentences in the raw text \n Span spans[] = detector.sentPosDetect(paragraph); \n \n //Printing the spans of the sentences in the paragraph \n for (Span span : spans) \n System.out.println(span); \n } \n}"
},
{
"code": null,
"e": 25848,
"s": 25753,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 25907,
"s": 25848,
"text": "javac SentencePosDetection.java \njava SentencePosDetection"
},
{
"code": null,
"e": 26029,
"s": 25907,
"text": "On executing, the above program reads the given String and detects the sentences in it and displays the following output."
},
{
"code": null,
"e": 26058,
"s": 26029,
"text": "[0..16) \n[17..43) \n[44..93)\n"
},
{
"code": null,
"e": 26296,
"s": 26058,
"text": "The substring() method of the String class accepts the begin and the end offsets and returns the respective string. We can use this method to print the sentences and their spans (positions) together, as shown in the following code block."
},
{
"code": null,
"e": 26410,
"s": 26296,
"text": "for (Span span : spans) \n System.out.println(sen.substring(span.getStart(), span.getEnd())+\" \"+ span); "
},
{
"code": null,
"e": 26597,
"s": 26410,
"text": "Following is the program to detect the sentences from the given raw text and display them along with their positions. Save this program in a file with name SentencesAndPosDetection.java."
},
{
"code": null,
"e": 27688,
"s": 26597,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.sentdetect.SentenceDetectorME; \nimport opennlp.tools.sentdetect.SentenceModel; \nimport opennlp.tools.util.Span; \n \npublic class SentencesAndPosDetection { \n \n public static void main(String args[]) throws Exception { \n \n String sen = \"Hi. How are you? Welcome to Tutorialspoint.\" \n + \" We provide free tutorials on various technologies\"; \n //Loading a sentence model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-sent.bin\"); \n SentenceModel model = new SentenceModel(inputStream); \n \n //Instantiating the SentenceDetectorME class \n SentenceDetectorME detector = new SentenceDetectorME(model); \n \n //Detecting the position of the sentences in the paragraph \n Span[] spans = detector.sentPosDetect(sen); \n \n //Printing the sentences and their spans of a paragraph \n for (Span span : spans) \n System.out.println(sen.substring(span.getStart(), span.getEnd())+\" \"+ span); \n } \n} "
},
{
"code": null,
"e": 27783,
"s": 27688,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 27850,
"s": 27783,
"text": "javac SentencesAndPosDetection.java \njava SentencesAndPosDetection"
},
{
"code": null,
"e": 27993,
"s": 27850,
"text": "On executing, the above program reads the given String and detects the sentences along with their positions and displays the following output."
},
{
"code": null,
"e": 28117,
"s": 27993,
"text": "Hi. How are you? [0..16) \nWelcome to Tutorialspoint. [17..43) \nWe provide free tutorials on various technologies [44..93)\n"
},
{
"code": null,
"e": 28279,
"s": 28117,
"text": "The getSentenceProbabilities() method of the SentenceDetectorME class returns the probabilities associated with the most recent calls to the sentDetect() method."
},
{
"code": null,
"e": 28399,
"s": 28279,
"text": "//Getting the probabilities of the last decoded sequence \ndouble[] probs = detector.getSentenceProbabilities(); \n"
},
{
"code": null,
"e": 28578,
"s": 28399,
"text": "Following is the program to print the probabilities associated with the calls to the sentDetect() method. Save this program in a file with the name SentenceDetectionMEProbs.java."
},
{
"code": null,
"e": 29820,
"s": 28578,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.sentdetect.SentenceDetectorME; \nimport opennlp.tools.sentdetect.SentenceModel; \n\npublic class SentenceDetectionMEProbs { \n \n public static void main(String args[]) throws Exception { \n \n String sentence = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Loading sentence detector model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-sent.bin\");\n SentenceModel model = new SentenceModel(inputStream); \n \n //Instantiating the SentenceDetectorME class\n SentenceDetectorME detector = new SentenceDetectorME(model); \n \n //Detecting the sentence \n String sentences[] = detector.sentDetect(sentence); \n \n //Printing the sentences \n for(String sent : sentences) \n System.out.println(sent); \n \n //Getting the probabilities of the last decoded sequence \n double[] probs = detector.getSentenceProbabilities(); \n \n System.out.println(\" \"); \n \n for(int i = 0; i<probs.length; i++) \n System.out.println(probs[i]); \n } \n} "
},
{
"code": null,
"e": 29915,
"s": 29820,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 29983,
"s": 29915,
"text": "javac SentenceDetectionMEProbs.java \njava SentenceDetectionMEProbs\n"
},
{
"code": null,
"e": 30210,
"s": 29983,
"text": "On executing, the above program reads the given String and detects the sentences and prints them. In addition, it also returns the probabilities associated with the most recent calls to the sentDetect() method, as shown below."
},
{
"code": null,
"e": 30356,
"s": 30210,
"text": "Hi. How are you? \nWelcome to Tutorialspoint. \nWe provide free tutorials on various technologies \n \n0.9240246995179983 \n0.9957680129995953 \n1.0\n"
},
{
"code": null,
"e": 30548,
"s": 30356,
"text": "The process of chopping the given sentence into smaller parts (tokens) is known as tokenization. In general, the given raw text is tokenized based on a set of delimiters (mostly whitespaces)."
},
{
"code": null,
"e": 30715,
"s": 30548,
"text": "Tokenization is used in tasks such as spell-checking, processing searches, identifying parts of speech, sentence detection, document classification of documents, etc."
},
{
"code": null,
"e": 30825,
"s": 30715,
"text": "The opennlp.tools.tokenize package contains the classes and interfaces that are used to perform tokenization."
},
{
"code": null,
"e": 30936,
"s": 30825,
"text": "To tokenize the given sentences into simpler fragments, the OpenNLP library provides three different classes −"
},
{
"code": null,
"e": 31019,
"s": 30936,
"text": "SimpleTokenizer − This class tokenizes the given raw text using character classes."
},
{
"code": null,
"e": 31102,
"s": 31019,
"text": "SimpleTokenizer − This class tokenizes the given raw text using character classes."
},
{
"code": null,
"e": 31180,
"s": 31102,
"text": "WhitespaceTokenizer − This class uses whitespaces to tokenize the given text."
},
{
"code": null,
"e": 31258,
"s": 31180,
"text": "WhitespaceTokenizer − This class uses whitespaces to tokenize the given text."
},
{
"code": null,
"e": 31370,
"s": 31258,
"text": "TokenizerME − This class converts raw text into separate tokens. It uses Maximum Entropy to make its decisions."
},
{
"code": null,
"e": 31482,
"s": 31370,
"text": "TokenizerME − This class converts raw text into separate tokens. It uses Maximum Entropy to make its decisions."
},
{
"code": null,
"e": 31552,
"s": 31482,
"text": "To tokenize a sentence using the SimpleTokenizer class, you need to −"
},
{
"code": null,
"e": 31594,
"s": 31552,
"text": "Create an object of the respective class."
},
{
"code": null,
"e": 31636,
"s": 31594,
"text": "Create an object of the respective class."
},
{
"code": null,
"e": 31687,
"s": 31636,
"text": "Tokenize the sentence using the tokenize() method."
},
{
"code": null,
"e": 31738,
"s": 31687,
"text": "Tokenize the sentence using the tokenize() method."
},
{
"code": null,
"e": 31756,
"s": 31738,
"text": "Print the tokens."
},
{
"code": null,
"e": 31774,
"s": 31756,
"text": "Print the tokens."
},
{
"code": null,
"e": 31868,
"s": 31774,
"text": "Following are the steps to be followed to write a program which tokenizes the given raw text."
},
{
"code": null,
"e": 31912,
"s": 31868,
"text": "Step 1 − Instantiating the respective class"
},
{
"code": null,
"e": 32080,
"s": 31912,
"text": "In both the classes, there are no constructors available to instantiate them. Therefore, we need to create objects of these classes using the static variable INSTANCE."
},
{
"code": null,
"e": 32137,
"s": 32080,
"text": "SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; "
},
{
"code": null,
"e": 32169,
"s": 32137,
"text": "Step 2 − Tokenize the sentences"
},
{
"code": null,
"e": 32358,
"s": 32169,
"text": "Both these classes contain a method called tokenize(). This method accepts a raw text in String format. On invoking, it tokenizes the given String and returns an array of Strings (tokens)."
},
{
"code": null,
"e": 32425,
"s": 32358,
"text": "Tokenize the sentence using the tokenizer() method as shown below."
},
{
"code": null,
"e": 32508,
"s": 32425,
"text": "//Tokenizing the given sentence \n String tokens[] = tokenizer.tokenize(sentence); "
},
{
"code": null,
"e": 32534,
"s": 32508,
"text": "Step 3 − Print the tokens"
},
{
"code": null,
"e": 32622,
"s": 32534,
"text": "After tokenizing the sentence, you can print the tokens using for loop, as shown below."
},
{
"code": null,
"e": 32709,
"s": 32622,
"text": "//Printing the tokens \nfor(String token : tokens) \n System.out.println(token);"
},
{
"code": null,
"e": 32717,
"s": 32709,
"text": "Example"
},
{
"code": null,
"e": 32881,
"s": 32717,
"text": "Following is the program which tokenizes the given sentence using the SimpleTokenizer class. Save this program in a file with the name SimpleTokenizerExample.java."
},
{
"code": null,
"e": 33526,
"s": 32881,
"text": "import opennlp.tools.tokenize.SimpleTokenizer; \npublic class SimpleTokenizerExample { \n public static void main(String args[]){ \n \n String sentence = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Instantiating SimpleTokenizer class \n SimpleTokenizer simpleTokenizer = SimpleTokenizer.INSTANCE; \n \n //Tokenizing the given sentence \n String tokens[] = simpleTokenizer.tokenize(sentence); \n \n //Printing the tokens \n for(String token : tokens) { \n System.out.println(token); \n } \n } \n}"
},
{
"code": null,
"e": 33621,
"s": 33526,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 33684,
"s": 33621,
"text": "javac SimpleTokenizerExample.java \njava SimpleTokenizerExample"
},
{
"code": null,
"e": 33801,
"s": 33684,
"text": "On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −"
},
{
"code": null,
"e": 33916,
"s": 33801,
"text": "Hi \n. \nHow \nare \nyou \n? \nWelcome \nto \nTutorialspoint \n. \nWe \nprovide \nfree \ntutorials \non \nvarious \ntechnologies \n"
},
{
"code": null,
"e": 33990,
"s": 33916,
"text": "To tokenize a sentence using the WhitespaceTokenizer class, you need to −"
},
{
"code": null,
"e": 34032,
"s": 33990,
"text": "Create an object of the respective class."
},
{
"code": null,
"e": 34074,
"s": 34032,
"text": "Create an object of the respective class."
},
{
"code": null,
"e": 34125,
"s": 34074,
"text": "Tokenize the sentence using the tokenize() method."
},
{
"code": null,
"e": 34176,
"s": 34125,
"text": "Tokenize the sentence using the tokenize() method."
},
{
"code": null,
"e": 34194,
"s": 34176,
"text": "Print the tokens."
},
{
"code": null,
"e": 34212,
"s": 34194,
"text": "Print the tokens."
},
{
"code": null,
"e": 34306,
"s": 34212,
"text": "Following are the steps to be followed to write a program which tokenizes the given raw text."
},
{
"code": null,
"e": 34350,
"s": 34306,
"text": "Step 1 − Instantiating the respective class"
},
{
"code": null,
"e": 34518,
"s": 34350,
"text": "In both the classes, there are no constructors available to instantiate them. Therefore, we need to create objects of these classes using the static variable INSTANCE."
},
{
"code": null,
"e": 34581,
"s": 34518,
"text": "WhitespaceTokenizer tokenizer = WhitespaceTokenizer.INSTANCE; "
},
{
"code": null,
"e": 34613,
"s": 34581,
"text": "Step 2 − Tokenize the sentences"
},
{
"code": null,
"e": 34802,
"s": 34613,
"text": "Both these classes contain a method called tokenize(). This method accepts a raw text in String format. On invoking, it tokenizes the given String and returns an array of Strings (tokens)."
},
{
"code": null,
"e": 34869,
"s": 34802,
"text": "Tokenize the sentence using the tokenizer() method as shown below."
},
{
"code": null,
"e": 34952,
"s": 34869,
"text": "//Tokenizing the given sentence \n String tokens[] = tokenizer.tokenize(sentence); "
},
{
"code": null,
"e": 34978,
"s": 34952,
"text": "Step 3 − Print the tokens"
},
{
"code": null,
"e": 35066,
"s": 34978,
"text": "After tokenizing the sentence, you can print the tokens using for loop, as shown below."
},
{
"code": null,
"e": 35153,
"s": 35066,
"text": "//Printing the tokens \nfor(String token : tokens) \n System.out.println(token);"
},
{
"code": null,
"e": 35161,
"s": 35153,
"text": "Example"
},
{
"code": null,
"e": 35333,
"s": 35161,
"text": "Following is the program which tokenizes the given sentence using the WhitespaceTokenizer class. Save this program in a file with the name WhitespaceTokenizerExample.java."
},
{
"code": null,
"e": 35998,
"s": 35333,
"text": "import opennlp.tools.tokenize.WhitespaceTokenizer; \n\npublic class WhitespaceTokenizerExample { \n \n public static void main(String args[]){ \n \n String sentence = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Instantiating whitespaceTokenizer class \n WhitespaceTokenizer whitespaceTokenizer = WhitespaceTokenizer.INSTANCE; \n \n //Tokenizing the given paragraph \n String tokens[] = whitespaceTokenizer.tokenize(sentence); \n \n //Printing the tokens \n for(String token : tokens) \n System.out.println(token); \n } \n}"
},
{
"code": null,
"e": 36093,
"s": 35998,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 36165,
"s": 36093,
"text": "javac WhitespaceTokenizerExample.java \njava WhitespaceTokenizerExample "
},
{
"code": null,
"e": 36281,
"s": 36165,
"text": "On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output."
},
{
"code": null,
"e": 36389,
"s": 36281,
"text": "Hi. \nHow \nare \nyou? \nWelcome \nto \nTutorialspoint. \nWe \nprovide \nfree \ntutorials \non \nvarious \ntechnologies\n"
},
{
"code": null,
"e": 36542,
"s": 36389,
"text": "OpenNLP also uses a predefined model, a file named de-token.bin, to tokenize the sentences. It is trained to tokenize the sentences in a given raw text."
},
{
"code": null,
"e": 36710,
"s": 36542,
"text": "The TokenizerME class of the opennlp.tools.tokenizer package is used to load this model, and tokenize the given raw text using OpenNLP library. To do so, you need to −"
},
{
"code": null,
"e": 36770,
"s": 36710,
"text": "Load the en-token.bin model using the TokenizerModel class."
},
{
"code": null,
"e": 36830,
"s": 36770,
"text": "Load the en-token.bin model using the TokenizerModel class."
},
{
"code": null,
"e": 36865,
"s": 36830,
"text": "Instantiate the TokenizerME class."
},
{
"code": null,
"e": 36900,
"s": 36865,
"text": "Instantiate the TokenizerME class."
},
{
"code": null,
"e": 36966,
"s": 36900,
"text": "Tokenize the sentences using the tokenize() method of this class."
},
{
"code": null,
"e": 37032,
"s": 36966,
"text": "Tokenize the sentences using the tokenize() method of this class."
},
{
"code": null,
"e": 37173,
"s": 37032,
"text": "Following are the steps to be followed to write a program which tokenizes the sentences from the given raw text using the TokenizerME class."
},
{
"code": null,
"e": 37200,
"s": 37173,
"text": "Step 1 − Loading the model"
},
{
"code": null,
"e": 37330,
"s": 37200,
"text": "The model for tokenization is represented by the class named TokenizerModel, which belongs to the package opennlp.tools.tokenize."
},
{
"code": null,
"e": 37358,
"s": 37330,
"text": "To load a tokenizer model −"
},
{
"code": null,
"e": 37502,
"s": 37358,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 37646,
"s": 37502,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 37803,
"s": 37646,
"text": "Instantiate the TokenizerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block."
},
{
"code": null,
"e": 37960,
"s": 37803,
"text": "Instantiate the TokenizerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block."
},
{
"code": null,
"e": 38134,
"s": 37960,
"text": "//Loading the Tokenizer model \nInputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-token.bin\"); \nTokenizerModel tokenModel = new TokenizerModel(inputStream);"
},
{
"code": null,
"e": 38179,
"s": 38134,
"text": "Step 2 − Instantiating the TokenizerME class"
},
{
"code": null,
"e": 38353,
"s": 38179,
"text": "The TokenizerME class of the package opennlp.tools.tokenize contains methods to chop the raw text into smaller parts (tokens). It uses Maximum Entropy to make its decisions."
},
{
"code": null,
"e": 38447,
"s": 38353,
"text": "Instantiate this class and pass the model object created in the previous step as shown below."
},
{
"code": null,
"e": 38539,
"s": 38447,
"text": "//Instantiating the TokenizerME class \nTokenizerME tokenizer = new TokenizerME(tokenModel);"
},
{
"code": null,
"e": 38572,
"s": 38539,
"text": "Step 3 − Tokenizing the sentence"
},
{
"code": null,
"e": 38762,
"s": 38572,
"text": "The tokenize() method of the TokenizerME class is used to tokenize the raw text passed to it. This method accepts a String variable as a parameter, and returns an array of Strings (tokens)."
},
{
"code": null,
"e": 38854,
"s": 38762,
"text": "Invoke this method by passing the String format of the sentence to this method, as follows."
},
{
"code": null,
"e": 38936,
"s": 38854,
"text": "//Tokenizing the given raw text \nString tokens[] = tokenizer.tokenize(paragraph);"
},
{
"code": null,
"e": 38944,
"s": 38936,
"text": "Example"
},
{
"code": null,
"e": 39072,
"s": 38944,
"text": "Following is the program which tokenizes the given raw text. Save this program in a file with the name TokenizerMEExample.java."
},
{
"code": null,
"e": 40012,
"s": 39072,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \nimport opennlp.tools.tokenize.TokenizerME; \nimport opennlp.tools.tokenize.TokenizerModel; \n\npublic class TokenizerMEExample { \n \n public static void main(String args[]) throws Exception{ \n \n String sentence = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Loading the Tokenizer model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-token.bin\"); \n TokenizerModel tokenModel = new TokenizerModel(inputStream); \n \n //Instantiating the TokenizerME class \n TokenizerME tokenizer = new TokenizerME(tokenModel); \n \n //Tokenizing the given raw text \n String tokens[] = tokenizer.tokenize(sentence); \n \n //Printing the tokens \n for (String a : tokens) \n System.out.println(a); \n } \n} "
},
{
"code": null,
"e": 40107,
"s": 40012,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 40163,
"s": 40107,
"text": "javac TokenizerMEExample.java \njava TokenizerMEExample\n"
},
{
"code": null,
"e": 40286,
"s": 40163,
"text": "On executing, the above program reads the given String and detects the sentences in it and displays the following output −"
},
{
"code": null,
"e": 40399,
"s": 40286,
"text": "Hi \n. \nHow \nare \nyou \n? \nWelcome \nto \nTutorialspoint \n. \nWe \nprovide \nfree \ntutorials \non \nvarious \ntechnologie\n"
},
{
"code": null,
"e": 40676,
"s": 40399,
"text": "We can also get the positions or spans of the tokens using the tokenizePos() method. This is the method of the Tokenizer interface of the package opennlp.tools.tokenize. Since all the (three) Tokenizer classes implement this interface, you can find this method in all of them."
},
{
"code": null,
"e": 40795,
"s": 40676,
"text": "This method accepts the sentence or raw text in the form of a string and returns an array of objects of the type Span."
},
{
"code": null,
"e": 40880,
"s": 40795,
"text": "You can get the positions of the tokens using the tokenizePos() method, as follows −"
},
{
"code": null,
"e": 40939,
"s": 40880,
"text": "//Retrieving the tokens \ntokenizer.tokenizePos(sentence); "
},
{
"code": null,
"e": 41046,
"s": 40939,
"text": "The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets."
},
{
"code": null,
"e": 41179,
"s": 41046,
"text": "You can store the spans returned by the tokenizePos() method in the Span array and print them, as shown in the following code block."
},
{
"code": null,
"e": 41349,
"s": 41179,
"text": "//Retrieving the tokens \nSpan[] tokens = tokenizer.tokenizePos(sentence);\n//Printing the spans of tokens \nfor( Span token : tokens) \n System.out.println(token);"
},
{
"code": null,
"e": 41584,
"s": 41349,
"text": "The substring() method of the String class accepts the begin and the end offsets and returns the respective string. We can use this method to print the tokens and their spans (positions) together, as shown in the following code block."
},
{
"code": null,
"e": 41727,
"s": 41584,
"text": "//Printing the spans of tokens \nfor(Span token : tokens) \n System.out.println(token +\" \"+sent.substring(token.getStart(), token.getEnd()));"
},
{
"code": null,
"e": 41752,
"s": 41727,
"text": "Example(SimpleTokenizer)"
},
{
"code": null,
"e": 41978,
"s": 41752,
"text": "Following is the program which retrieves the token spans of the raw text using the SimpleTokenizer class. It also prints the tokens along with their positions. Save this program in a file with named SimpleTokenizerSpans.java."
},
{
"code": null,
"e": 42708,
"s": 41978,
"text": "import opennlp.tools.tokenize.SimpleTokenizer; \nimport opennlp.tools.util.Span; \n\npublic class SimpleTokenizerSpans { \n public static void main(String args[]){ \n \n String sent = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Instantiating SimpleTokenizer class \n SimpleTokenizer simpleTokenizer = SimpleTokenizer.INSTANCE; \n \n //Retrieving the boundaries of the tokens \n Span[] tokens = simpleTokenizer.tokenizePos(sent); \n \n //Printing the spans of tokens \n for( Span token : tokens)\n System.out.println(token +\" \"+sent.substring(token.getStart(), token.getEnd())); \n } \n} "
},
{
"code": null,
"e": 42803,
"s": 42708,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 42863,
"s": 42803,
"text": "javac SimpleTokenizerSpans.java \njava SimpleTokenizerSpans "
},
{
"code": null,
"e": 42980,
"s": 42863,
"text": "On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −"
},
{
"code": null,
"e": 43241,
"s": 42980,
"text": "[0..2) Hi \n[2..3) . \n[4..7) How \n[8..11) are \n[12..15) you \n[15..16) ? \n[17..24) Welcome \n[25..27) to \n[28..42) Tutorialspoint \n[42..43) . \n[44..46) We \n[47..54) provide \n[55..59) free \n[60..69) tutorials \n[70..72) on \n[73..80) various \n[81..93) technologies \n"
},
{
"code": null,
"e": 43271,
"s": 43241,
"text": "Example (WhitespaceTokenizer)"
},
{
"code": null,
"e": 43508,
"s": 43271,
"text": "Following is the program which retrieves the token spans of the raw text using the WhitespaceTokenizer class. It also prints the tokens along with their positions. Save this program in a file with the name WhitespaceTokenizerSpans.java."
},
{
"code": null,
"e": 44248,
"s": 43508,
"text": "import opennlp.tools.tokenize.WhitespaceTokenizer;\nimport opennlp.tools.util.Span; \npublic class WhitespaceTokenizerSpans { \n public static void main(String args[]){ \n \n String sent = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Instantiating SimpleTokenizer class \n WhitespaceTokenizer whitespaceTokenizer = WhitespaceTokenizer.INSTANCE; \n \n //Retrieving the tokens \n Span[] tokens = whitespaceTokenizer.tokenizePos(sent); \n \n //Printing the spans of tokens \n for( Span token : tokens) \n System.out.println(token +\" \n \"+sent.substring(token.getStart(), token.getEnd())); \n } \n} "
},
{
"code": null,
"e": 44341,
"s": 44248,
"text": "Compile and execute the saved java file from the command prompt using the following commands"
},
{
"code": null,
"e": 44408,
"s": 44341,
"text": "javac WhitespaceTokenizerSpans.java \njava WhitespaceTokenizerSpans"
},
{
"code": null,
"e": 44524,
"s": 44408,
"text": "On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output."
},
{
"code": null,
"e": 44752,
"s": 44524,
"text": "[0..3) Hi. \n[4..7) How \n[8..11) are \n[12..16) you? \n[17..24) Welcome \n[25..27) to \n[28..43) Tutorialspoint. \n[44..46) We \n[47..54) provide \n[55..59) free\n[60..69) tutorials \n[70..72) on \n[73..80) various \n[81..93) technologies\n"
},
{
"code": null,
"e": 44774,
"s": 44752,
"text": "Example (TokenizerME)"
},
{
"code": null,
"e": 44995,
"s": 44774,
"text": "Following is the program which retrieves the token spans of the raw text using the TokenizerME class. It also prints the tokens along with their positions. Save this program in a file with the name TokenizerMESpans.java."
},
{
"code": null,
"e": 45959,
"s": 44995,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \nimport opennlp.tools.tokenize.TokenizerME; \nimport opennlp.tools.tokenize.TokenizerModel; \nimport opennlp.tools.util.Span; \n\npublic class TokenizerMESpans { \n public static void main(String args[]) throws Exception{ \n String sent = \"Hello John how are you welcome to Tutorialspoint\"; \n \n //Loading the Tokenizer model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-token.bin\"); \n TokenizerModel tokenModel = new TokenizerModel(inputStream); \n \n //Instantiating the TokenizerME class \n TokenizerME tokenizer = new TokenizerME(tokenModel); \n \n //Retrieving the positions of the tokens \n Span tokens[] = tokenizer.tokenizePos(sent); \n \n //Printing the spans of tokens \n for(Span token : tokens) \n System.out.println(token +\" \"+sent.substring(token.getStart(), token.getEnd())); \n } \n} "
},
{
"code": null,
"e": 46054,
"s": 45959,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 46105,
"s": 46054,
"text": "javac TokenizerMESpans.java \njava TokenizerMESpans"
},
{
"code": null,
"e": 46222,
"s": 46105,
"text": "On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −"
},
{
"code": null,
"e": 46349,
"s": 46222,
"text": "[0..5) Hello \n[6..10) John \n[11..14) how \n[15..18) are \n[19..22) you \n[23..30) welcome \n[31..33) to \n[34..48) Tutorialspoint \n"
},
{
"code": null,
"e": 46509,
"s": 46349,
"text": "The getTokenProbabilities() method of the TokenizerME class is used to get the probabilities associated with the most recent calls to the tokenizePos() method."
},
{
"code": null,
"e": 46637,
"s": 46509,
"text": "//Getting the probabilities of the recent calls to tokenizePos() method \ndouble[] probs = detector.getSentenceProbabilities(); "
},
{
"code": null,
"e": 46805,
"s": 46637,
"text": "Following is the program to print the probabilities associated with the calls to tokenizePos() method. Save this program in a file with the name TokenizerMEProbs.java."
},
{
"code": null,
"e": 48054,
"s": 46805,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \nimport opennlp.tools.tokenize.TokenizerME; \nimport opennlp.tools.tokenize.TokenizerModel; \nimport opennlp.tools.util.Span; \n\npublic class TokenizerMEProbs { \n \n public static void main(String args[]) throws Exception{ \n String sent = \"Hello John how are you welcome to Tutorialspoint\"; \n \n //Loading the Tokenizer model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-token.bin\"); \n TokenizerModel tokenModel = new TokenizerModel(inputStream); \n \n //Instantiating the TokenizerME class \n TokenizerME tokenizer = new TokenizerME(tokenModel);\n \n //Retrieving the positions of the tokens \n Span tokens[] = tokenizer.tokenizePos(sent); \n \n //Getting the probabilities of the recent calls to tokenizePos() method \n double[] probs = tokenizer.getTokenProbabilities(); \n \n //Printing the spans of tokens \n for(Span token : tokens) \n System.out.println(token +\" \"+sent.substring(token.getStart(), token.getEnd())); \n System.out.println(\" \"); \n for(int i = 0; i<probs.length; i++) \n System.out.println(probs[i]); \n } \n} "
},
{
"code": null,
"e": 48149,
"s": 48054,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 48201,
"s": 48149,
"text": "javac TokenizerMEProbs.java \njava TokenizerMEProbs "
},
{
"code": null,
"e": 48416,
"s": 48201,
"text": "On executing, the above program reads the given String and tokenizes the sentences and prints them. In addition, it also returns the probabilities associated with the most recent calls to the tokenizerPos() method."
},
{
"code": null,
"e": 48586,
"s": 48416,
"text": "[0..5) Hello \n[6..10) John \n[11..14) how \n[15..18) are \n[19..22) you \n[23..30) welcome \n[31..33) to \n[34..48) Tutorialspoint \n \n1.0 \n1.0 \n1.0 \n1.0 \n1.0 \n1.0 \n1.0 \n1.0\n"
},
{
"code": null,
"e": 48812,
"s": 48586,
"text": "The process of finding names, people, places, and other entities, from a given text is known as Named Entity Recognition (NER). In this chapter, we will discuss how to carry out NER through Java program using OpenNLP library."
},
{
"code": null,
"e": 49104,
"s": 48812,
"text": "To perform various NER tasks, OpenNLP uses different predefined models namely, en-nerdate.bn, en-ner-location.bin, en-ner-organization.bin, en-ner-person.bin, and en-ner-time.bin. All these files are predefined models which are trained to detect the respective entities in a given raw text. "
},
{
"code": null,
"e": 49271,
"s": 49104,
"text": "The opennlp.tools.namefind package contains the classes and interfaces that are used to perform the NER task. To perform NER task using OpenNLP library, you need to −"
},
{
"code": null,
"e": 49335,
"s": 49271,
"text": "Load the respective model using the TokenNameFinderModel class."
},
{
"code": null,
"e": 49399,
"s": 49335,
"text": "Load the respective model using the TokenNameFinderModel class."
},
{
"code": null,
"e": 49433,
"s": 49399,
"text": "Instantiate the NameFinder class."
},
{
"code": null,
"e": 49467,
"s": 49433,
"text": "Instantiate the NameFinder class."
},
{
"code": null,
"e": 49498,
"s": 49467,
"text": "Find the names and print them."
},
{
"code": null,
"e": 49529,
"s": 49498,
"text": "Find the names and print them."
},
{
"code": null,
"e": 49642,
"s": 49529,
"text": "Following are the steps to be followed to write a program which detects the name entities from a given raw text."
},
{
"code": null,
"e": 49784,
"s": 49642,
"text": "The model for sentence detection is represented by the class named TokenNameFinderModel, which belongs to the package opennlp.tools.namefind."
},
{
"code": null,
"e": 49807,
"s": 49784,
"text": "To load an NER model −"
},
{
"code": null,
"e": 49967,
"s": 49807,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the appropriate NER model in String format to its constructor)."
},
{
"code": null,
"e": 50127,
"s": 49967,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the appropriate NER model in String format to its constructor)."
},
{
"code": null,
"e": 50290,
"s": 50127,
"text": "Instantiate the TokenNameFinderModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block."
},
{
"code": null,
"e": 50453,
"s": 50290,
"text": "Instantiate the TokenNameFinderModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block."
},
{
"code": null,
"e": 50651,
"s": 50453,
"text": "//Loading the NER-person model \nInputStream inputStreamNameFinder = new FileInputStream(\".../en-nerperson.bin\"); \nTokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder);"
},
{
"code": null,
"e": 50847,
"s": 50651,
"text": "The NameFinderME class of the package opennlp.tools.namefind contains methods to perform the NER tasks. This class uses the Maximum Entropy model to find the named entities in the given raw text."
},
{
"code": null,
"e": 50942,
"s": 50847,
"text": "Instantiate this class and pass the model object created in the previous step as shown below −"
},
{
"code": null,
"e": 51033,
"s": 50942,
"text": "//Instantiating the NameFinderME class \nNameFinderME nameFinder = new NameFinderME(model);"
},
{
"code": null,
"e": 51189,
"s": 51033,
"text": "The find() method of the NameFinderME class is used to detect the names in the raw text passed to it. This method accepts a String variable as a parameter."
},
{
"code": null,
"e": 51269,
"s": 51189,
"text": "Invoke this method by passing the String format of the sentence to this method."
},
{
"code": null,
"e": 51352,
"s": 51269,
"text": "//Finding the names in the sentence \nSpan nameSpans[] = nameFinder.find(sentence);"
},
{
"code": null,
"e": 51549,
"s": 51352,
"text": "The find() method of the NameFinderME class returns an array of objects of the type Span. The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets."
},
{
"code": null,
"e": 51675,
"s": 51549,
"text": "You can store the spans returned by the find() method in the Span array and print them, as shown in the following code block."
},
{
"code": null,
"e": 51810,
"s": 51675,
"text": "//Printing the sentences and their spans of a sentence \nfor (Span span : spans) \nSystem.out.println(paragraph.substring(span);"
},
{
"code": null,
"e": 51822,
"s": 51810,
"text": "NER Example"
},
{
"code": null,
"e": 52007,
"s": 51822,
"text": "Following is the program which reads the given sentence and recognizes the spans of the names of the persons in it. Save this program in a file with the name NameFinderME_Example.java."
},
{
"code": null,
"e": 53114,
"s": 52007,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.namefind.NameFinderME; \nimport opennlp.tools.namefind.TokenNameFinderModel; \nimport opennlp.tools.util.Span; \n\npublic class NameFinderME_Example { \n public static void main(String args[]) throws Exception{ \n /Loading the NER - Person model InputStream inputStream = new \n FileInputStream(\"C:/OpenNLP_models/en-ner-person.bin\"); \n TokenNameFinderModel model = new TokenNameFinderModel(inputStream);\n \n //Instantiating the NameFinder class \n NameFinderME nameFinder = new NameFinderME(model); \n \n //Getting the sentence in the form of String array \n String [] sentence = new String[]{ \n \"Mike\", \n \"and\", \n \"Smith\", \n \"are\", \n \"good\", \n \"friends\" \n }; \n \n //Finding the names in the sentence \n Span nameSpans[] = nameFinder.find(sentence); \n \n //Printing the spans of the names in the sentence \n for(Span s: nameSpans) \n System.out.println(s.toString()); \n } \n} "
},
{
"code": null,
"e": 53209,
"s": 53114,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 53268,
"s": 53209,
"text": "javac NameFinderME_Example.java \njava NameFinderME_Example"
},
{
"code": null,
"e": 53429,
"s": 53268,
"text": "On executing, the above program reads the given String (raw text), detects the names of the persons in it, and displays their positions (spans), as shown below."
},
{
"code": null,
"e": 53460,
"s": 53429,
"text": "[0..1) person \n[2..3) person \n"
},
{
"code": null,
"e": 53694,
"s": 53460,
"text": "The substring() method of the String class accepts the begin and the end offsets and returns the respective string. We can use this method to print the names and their spans (positions) together, as shown in the following code block."
},
{
"code": null,
"e": 53788,
"s": 53694,
"text": "for(Span s: nameSpans) \n System.out.println(s.toString()+\" \"+tokens[s.getStart()]);"
},
{
"code": null,
"e": 53970,
"s": 53788,
"text": "Following is the program to detect the names from the given raw text and display them along with their positions. Save this program in a file with the name NameFinderSentences.java."
},
{
"code": null,
"e": 55613,
"s": 53970,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.namefind.NameFinderME; \nimport opennlp.tools.namefind.TokenNameFinderModel; \nimport opennlp.tools.tokenize.TokenizerME; \nimport opennlp.tools.tokenize.TokenizerModel; \nimport opennlp.tools.util.Span; \n\npublic class NameFinderSentences { \n public static void main(String args[]) throws Exception{ \n \n //Loading the tokenizer model \n InputStream inputStreamTokenizer = new \n FileInputStream(\"C:/OpenNLP_models/entoken.bin\");\n TokenizerModel tokenModel = new TokenizerModel(inputStreamTokenizer); \n \n //Instantiating the TokenizerME class \n TokenizerME tokenizer = new TokenizerME(tokenModel); \n \n //Tokenizing the sentence in to a string array \n String sentence = \"Mike is senior programming \n manager and Rama is a clerk both are working at \n Tutorialspoint\"; \n String tokens[] = tokenizer.tokenize(sentence); \n \n //Loading the NER-person model \n InputStream inputStreamNameFinder = new \n FileInputStream(\"C:/OpenNLP_models/enner-person.bin\"); \n TokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder);\n \n //Instantiating the NameFinderME class \n NameFinderME nameFinder = new NameFinderME(model); \n \n //Finding the names in the sentence \n Span nameSpans[] = nameFinder.find(tokens); \n \n //Printing the names and their spans in a sentence \n for(Span s: nameSpans) \n System.out.println(s.toString()+\" \"+tokens[s.getStart()]); \n } \n} "
},
{
"code": null,
"e": 55708,
"s": 55613,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 55766,
"s": 55708,
"text": "javac NameFinderSentences.java \njava NameFinderSentences "
},
{
"code": null,
"e": 55926,
"s": 55766,
"text": "On executing, the above program reads the given String (raw text), detects the names of the persons in it, and displays their positions (spans) as shown below."
},
{
"code": null,
"e": 55947,
"s": 55926,
"text": "[0..1) person Mike\n"
},
{
"code": null,
"e": 56200,
"s": 55947,
"text": "By loading various models, you can detect various named entities. Following is a Java program which loads the en-ner-location.bin model and detects the location names in the given sentence. Save this program in a file with the name LocationFinder.java."
},
{
"code": null,
"e": 57735,
"s": 56200,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.namefind.NameFinderME; \nimport opennlp.tools.namefind.TokenNameFinderModel; \nimport opennlp.tools.tokenize.TokenizerME; \nimport opennlp.tools.tokenize.TokenizerModel; \nimport opennlp.tools.util.Span; \n\npublic class LocationFinder { \n public static void main(String args[]) throws Exception{\n \n InputStream inputStreamTokenizer = new \n FileInputStream(\"C:/OpenNLP_models/entoken.bin\"); \n TokenizerModel tokenModel = new TokenizerModel(inputStreamTokenizer); \n \n //String paragraph = \"Mike and Smith are classmates\"; \n String paragraph = \"Tutorialspoint is located in Hyderabad\"; \n \n //Instantiating the TokenizerME class \n TokenizerME tokenizer = new TokenizerME(tokenModel); \n String tokens[] = tokenizer.tokenize(paragraph); \n \n //Loading the NER-location moodel \n InputStream inputStreamNameFinder = new \n FileInputStream(\"C:/OpenNLP_models/en- ner-location.bin\"); \n TokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder); \n \n //Instantiating the NameFinderME class \n NameFinderME nameFinder = new NameFinderME(model); \n \n //Finding the names of a location \n Span nameSpans[] = nameFinder.find(tokens); \n //Printing the spans of the locations in the sentence \n for(Span s: nameSpans) \n System.out.println(s.toString()+\" \"+tokens[s.getStart()]); \n } \n} "
},
{
"code": null,
"e": 57830,
"s": 57735,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 57877,
"s": 57830,
"text": "javac LocationFinder.java \njava LocationFinder"
},
{
"code": null,
"e": 58038,
"s": 57877,
"text": "On executing, the above program reads the given String (raw text), detects the names of the persons in it, and displays their positions (spans), as shown below."
},
{
"code": null,
"e": 58066,
"s": 58038,
"text": "[4..5) location Hyderabad\n"
},
{
"code": null,
"e": 58173,
"s": 58066,
"text": "The probs()method of the NameFinderME class is used to get the probabilities of the last decoded sequence."
},
{
"code": null,
"e": 58211,
"s": 58173,
"text": "double[] probs = nameFinder.probs(); "
},
{
"code": null,
"e": 58329,
"s": 58211,
"text": "Following is the program to print the probabilities. Save this program in a file with the name TokenizerMEProbs.java."
},
{
"code": null,
"e": 59588,
"s": 58329,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \nimport opennlp.tools.tokenize.TokenizerME; \nimport opennlp.tools.tokenize.TokenizerModel; \nimport opennlp.tools.util.Span; \npublic class TokenizerMEProbs { \n public static void main(String args[]) throws Exception{ \n String sent = \"Hello John how are you welcome to Tutorialspoint\"; \n \n //Loading the Tokenizer model \n InputStream inputStream = new \n FileInputStream(\"C:/OpenNLP_models/en-token.bin\"); \n TokenizerModel tokenModel = new TokenizerModel(inputStream); \n \n //Instantiating the TokenizerME class \n TokenizerME tokenizer = new TokenizerME(tokenModel); \n \n //Retrieving the positions of the tokens \n Span tokens[] = tokenizer.tokenizePos(sent); \n \n //Getting the probabilities of the recent calls to tokenizePos() method \n double[] probs = tokenizer.getTokenProbabilities(); \n \n //Printing the spans of tokens \n for( Span token : tokens) \n System.out.println(token +\" \n \"+sent.substring(token.getStart(), token.getEnd())); \n System.out.println(\" \"); \n for(int i = 0; i<probs.length; i++) \n System.out.println(probs[i]); \n } \n}"
},
{
"code": null,
"e": 59683,
"s": 59588,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 59734,
"s": 59683,
"text": "javac TokenizerMEProbs.java \njava TokenizerMEProbs"
},
{
"code": null,
"e": 59925,
"s": 59734,
"text": "On executing, the above program reads the given String, tokenizes the sentences, and prints them. In addition, it also returns the probabilities of the last decoded sequence, as shown below."
},
{
"code": null,
"e": 60095,
"s": 59925,
"text": "[0..5) Hello \n[6..10) John \n[11..14) how \n[15..18) are \n[19..22) you \n[23..30) welcome \n[31..33) to \n[34..48) Tutorialspoint \n \n1.0 \n1.0 \n1.0 \n1.0 \n1.0 \n1.0 \n1.0 \n1.0\n"
},
{
"code": null,
"e": 60381,
"s": 60095,
"text": "Using OpenNLP, you can also detect the Parts of Speech of a given sentence and print them. Instead of full name of the parts of speech, OpenNLP uses short forms of each parts of speech. The following table indicates the various parts of speeches detected by OpenNLP and their meanings."
},
{
"code": null,
"e": 60570,
"s": 60381,
"text": "To tag the parts of speech of a sentence, OpenNLP uses a model, a file named en-posmaxent.bin. This is a predefined model which is trained to tag the parts of speech of the given raw text."
},
{
"code": null,
"e": 60753,
"s": 60570,
"text": "The POSTaggerME class of the opennlp.tools.postag package is used to load this model, and tag the parts of speech of the given raw text using OpenNLP library. To do so, you need to −"
},
{
"code": null,
"e": 60812,
"s": 60753,
"text": "Load the en-pos-maxent.bin model using the POSModel class."
},
{
"code": null,
"e": 60871,
"s": 60812,
"text": "Load the en-pos-maxent.bin model using the POSModel class."
},
{
"code": null,
"e": 60906,
"s": 60871,
"text": "Instantiate the POSTaggerME class."
},
{
"code": null,
"e": 60941,
"s": 60906,
"text": "Instantiate the POSTaggerME class."
},
{
"code": null,
"e": 60964,
"s": 60941,
"text": "Tokenize the sentence."
},
{
"code": null,
"e": 60987,
"s": 60964,
"text": "Tokenize the sentence."
},
{
"code": null,
"e": 61025,
"s": 60987,
"text": "Generate the tags using tag() method."
},
{
"code": null,
"e": 61063,
"s": 61025,
"text": "Generate the tags using tag() method."
},
{
"code": null,
"e": 61112,
"s": 61063,
"text": "Print the tokens and tags using POSSample class."
},
{
"code": null,
"e": 61161,
"s": 61112,
"text": "Print the tokens and tags using POSSample class."
},
{
"code": null,
"e": 61305,
"s": 61161,
"text": "Following are the steps to be followed to write a program which tags the parts of the speech in the given raw text using the POSTaggerME class."
},
{
"code": null,
"e": 61426,
"s": 61305,
"text": "The model for POS tagging is represented by the class named POSModel, which belongs to the package opennlp.tools.postag."
},
{
"code": null,
"e": 61454,
"s": 61426,
"text": "To load a tokenizer model −"
},
{
"code": null,
"e": 61598,
"s": 61454,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 61742,
"s": 61598,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 61895,
"s": 61742,
"text": "Instantiate the POSModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block −"
},
{
"code": null,
"e": 62048,
"s": 61895,
"text": "Instantiate the POSModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block −"
},
{
"code": null,
"e": 62220,
"s": 62048,
"text": "//Loading Parts of speech-maxent model \nInputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-pos-maxent.bin\"); \nPOSModel model = new POSModel(inputStream); "
},
{
"code": null,
"e": 62387,
"s": 62220,
"text": "The POSTaggerME class of the package opennlp.tools.postag is used to predict the parts of speech of the given raw text. It uses Maximum Entropy to make its decisions."
},
{
"code": null,
"e": 62483,
"s": 62387,
"text": "Instantiate this class and pass the model object created in the previous step, as shown below −"
},
{
"code": null,
"e": 62563,
"s": 62483,
"text": "//Instantiating POSTaggerME class \nPOSTaggerME tagger = new POSTaggerME(model);"
},
{
"code": null,
"e": 62761,
"s": 62563,
"text": "The tokenize() method of the whitespaceTokenizer class is used to tokenize the raw text passed to it. This method accepts a String variable as a parameter, and returns an array of Strings (tokens)."
},
{
"code": null,
"e": 62891,
"s": 62761,
"text": "Instantiate the whitespaceTokenizer class and the invoke this method by passing the String format of the sentence to this method."
},
{
"code": null,
"e": 63082,
"s": 62891,
"text": "//Tokenizing the sentence using WhitespaceTokenizer class \nWhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE; \nString[] tokens = whitespaceTokenizer.tokenize(sentence); "
},
{
"code": null,
"e": 63264,
"s": 63082,
"text": "The tag() method of the whitespaceTokenizer class assigns POS tags to the sentence of tokens. This method accepts an array of tokens (String) as a parameter and returns tag (array)."
},
{
"code": null,
"e": 63348,
"s": 63264,
"text": "Invoke the tag() method by passing the tokens generated in the previous step to it."
},
{
"code": null,
"e": 63404,
"s": 63348,
"text": "//Generating tags \nString[] tags = tagger.tag(tokens); "
},
{
"code": null,
"e": 63559,
"s": 63404,
"text": "The POSSample class represents the POS-tagged sentence. To instantiate this class, we would require an array of tokens (of the text) and an array of tags."
},
{
"code": null,
"e": 63789,
"s": 63559,
"text": "The toString() method of this class returns the tagged sentence. Instantiate this class by passing the token and the tag arrays created in the previous steps and invoke its toString() method, as shown in the following code block."
},
{
"code": null,
"e": 63914,
"s": 63789,
"text": "//Instantiating the POSSample class \nPOSSample sample = new POSSample(tokens, tags); \nSystem.out.println(sample.toString());"
},
{
"code": null,
"e": 63922,
"s": 63914,
"text": "Example"
},
{
"code": null,
"e": 64064,
"s": 63922,
"text": "Following is the program which tags the parts of speech in a given raw text. Save this program in a file with the name PosTaggerExample.java."
},
{
"code": null,
"e": 65239,
"s": 64064,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.postag.POSModel; \nimport opennlp.tools.postag.POSSample; \nimport opennlp.tools.postag.POSTaggerME; \nimport opennlp.tools.tokenize.WhitespaceTokenizer; \n\npublic class PosTaggerExample { \n \n public static void main(String args[]) throws Exception{ \n \n //Loading Parts of speech-maxent model \n InputStream inputStream = new \n FileInputStream(\"C:/OpenNLP_models/en-pos-maxent.bin\"); \n POSModel model = new POSModel(inputStream); \n \n //Instantiating POSTaggerME class \n POSTaggerME tagger = new POSTaggerME(model); \n \n String sentence = \"Hi welcome to Tutorialspoint\"; \n \n //Tokenizing the sentence using WhitespaceTokenizer class \n WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE; \n String[] tokens = whitespaceTokenizer.tokenize(sentence); \n \n //Generating tags \n String[] tags = tagger.tag(tokens);\n \n //Instantiating the POSSample class \n POSSample sample = new POSSample(tokens, tags); \n System.out.println(sample.toString()); \n \n } \n} "
},
{
"code": null,
"e": 65334,
"s": 65239,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 65386,
"s": 65334,
"text": "javac PosTaggerExample.java \njava PosTaggerExample "
},
{
"code": null,
"e": 65525,
"s": 65386,
"text": "On executing, the above program reads the given text and detects the parts of speech of these sentences and displays them, as shown below."
},
{
"code": null,
"e": 65569,
"s": 65525,
"text": "Hi_NNP welcome_JJ to_TO Tutorialspoint_VB \n"
},
{
"code": null,
"e": 65793,
"s": 65569,
"text": "Following is the program which tags the parts of speech of a given raw text. It also monitors the performance and displays the performance of the tagger. Save this program in a file with the name PosTagger_Performance.java."
},
{
"code": null,
"e": 67276,
"s": 65793,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.cmdline.PerformanceMonitor; \nimport opennlp.tools.postag.POSModel; \nimport opennlp.tools.postag.POSSample; \nimport opennlp.tools.postag.POSTaggerME; \nimport opennlp.tools.tokenize.WhitespaceTokenizer; \n\npublic class PosTagger_Performance { \n public static void main(String args[]) throws Exception{ \n //Loading Parts of speech-maxent model \n InputStream inputStream = new \n FileInputStream(\"C:/OpenNLP_models/en-pos-maxent.bin\"); \n POSModel model = new POSModel(inputStream); \n \n //Creating an object of WhitespaceTokenizer class \n WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE; \n \n //Tokenizing the sentence \n String sentence = \"Hi welcome to Tutorialspoint\"; \n String[] tokens = whitespaceTokenizer.tokenize(sentence); \n \n //Instantiating POSTaggerME class \n POSTaggerME tagger = new POSTaggerME(model); \n \n //Generating tags \n String[] tags = tagger.tag(tokens); \n \n //Instantiating POSSample class \n POSSample sample = new POSSample(tokens, tags); \n System.out.println(sample.toString()); \n \n //Monitoring the performance of POS tagger \n PerformanceMonitor perfMon = new PerformanceMonitor(System.err, \"sent\"); \n perfMon.start(); \n perfMon.incrementCounter(); \n perfMon.stopAndPrintFinalResult(); \n } \n}"
},
{
"code": null,
"e": 67371,
"s": 67276,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 67423,
"s": 67371,
"text": "javac PosTaggerExample.java \njava PosTaggerExample "
},
{
"code": null,
"e": 67624,
"s": 67423,
"text": "On executing, the above program reads the given text and tags the parts of speech of these sentences and displays them. In addition, it also monitors the performance of the POS tagger and displays it."
},
{
"code": null,
"e": 67721,
"s": 67624,
"text": "Hi_NNP welcome_JJ to_TO Tutorialspoint_VB \nAverage: 0.0 sent/s \nTotal: 1 sent \nRuntime: 0.0s \n"
},
{
"code": null,
"e": 67845,
"s": 67721,
"text": "The probs() method of the POSTaggerME class is used to find the probabilities for each tag of the recently tagged sentence."
},
{
"code": null,
"e": 67973,
"s": 67845,
"text": "//Getting the probabilities of the recent calls to tokenizePos() method \ndouble[] probs = detector.getSentenceProbabilities(); "
},
{
"code": null,
"e": 68136,
"s": 67973,
"text": "Following is the program which displays the probabilities for each tag of the last tagged sentence. Save this program in a file with the name PosTaggerProbs.java."
},
{
"code": null,
"e": 69617,
"s": 68136,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.postag.POSModel; \nimport opennlp.tools.postag.POSSample; \nimport opennlp.tools.postag.POSTaggerME; \nimport opennlp.tools.tokenize.WhitespaceTokenizer; \n\npublic class PosTaggerProbs { \n \n public static void main(String args[]) throws Exception{ \n \n //Loading Parts of speech-maxent model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_mdl/en-pos-maxent.bin\"); \n POSModel model = new POSModel(inputStream); \n \n //Creating an object of WhitespaceTokenizer class \n WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE; \n \n //Tokenizing the sentence \n String sentence = \"Hi welcome to Tutorialspoint\"; \n String[] tokens = whitespaceTokenizer.tokenize(sentence); \n \n //Instantiating POSTaggerME class \n POSTaggerME tagger = new POSTaggerME(model); \n \n //Generating tags \n String[] tags = tagger.tag(tokens); \n \n //Instantiating the POSSample class \n POSSample sample = new POSSample(tokens, tags); \n System.out.println(sample.toString());\n \n //Probabilities for each tag of the last tagged sentence. \n double [] probs = tagger.probs(); \n System.out.println(\" \"); \n \n //Printing the probabilities \n for(int i = 0; i<probs.length; i++) \n System.out.println(probs[i]); \n } \n} "
},
{
"code": null,
"e": 69712,
"s": 69617,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 69763,
"s": 69712,
"text": "javac TokenizerMEProbs.java \njava TokenizerMEProbs"
},
{
"code": null,
"e": 69998,
"s": 69763,
"text": "On executing, the above program reads the given raw text, tags the parts of speech of each token in it, and displays them. In addition, it also displays the probabilities for each parts of speech in the given sentence, as shown below."
},
{
"code": null,
"e": 70126,
"s": 69998,
"text": "Hi_NNP welcome_JJ to_TO Tutorialspoint_VB \n0.6416834779738033 \n0.42983612874819177 \n0.8584513635863117 \n0.4394784478206072 \n"
},
{
"code": null,
"e": 70254,
"s": 70126,
"text": "Using OpenNLP API, you can parse the given sentences. In this chapter, we will discuss how to parse raw text using OpenNLP API."
},
{
"code": null,
"e": 70421,
"s": 70254,
"text": "To detect the sentences, OpenNLP uses a predefined model, a file named en-parserchunking.bin. This is a predefined model which is trained to parse the given raw text."
},
{
"code": null,
"e": 70612,
"s": 70421,
"text": "The Parser class of the opennlp.tools.Parser package is used to hold the parse constituents and the ParserTool class of the opennlp.tools.cmdline.parser package is used to parse the content."
},
{
"code": null,
"e": 70730,
"s": 70612,
"text": "Following are the steps to be followed to write a program which parses the given raw text using the ParserTool class."
},
{
"code": null,
"e": 70855,
"s": 70730,
"text": "The model for parsing text is represented by the class named ParserModel, which belongs to the package opennlp.tools.parser."
},
{
"code": null,
"e": 70883,
"s": 70855,
"text": "To load a tokenizer model −"
},
{
"code": null,
"e": 71027,
"s": 70883,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 71171,
"s": 71027,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 71325,
"s": 71171,
"text": "Instantiate the ParserModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block."
},
{
"code": null,
"e": 71479,
"s": 71325,
"text": "Instantiate the ParserModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block."
},
{
"code": null,
"e": 71630,
"s": 71479,
"text": "//Loading parser model \nInputStream inputStream = new FileInputStream(\".../en-parserchunking.bin\"); \nParserModel model = new ParserModel(inputStream);"
},
{
"code": null,
"e": 71843,
"s": 71630,
"text": "The Parser class of the package opennlp.tools.parser represents a data structure for holding parse constituents. You can create an object of this class using the static create() method of the ParserFactory class."
},
{
"code": null,
"e": 71966,
"s": 71843,
"text": "Invoke the create() method of the ParserFactory by passing the model object created in the previous step, as shown below −"
},
{
"code": null,
"e": 72032,
"s": 71966,
"text": "//Creating a parser Parser parser = ParserFactory.create(model); "
},
{
"code": null,
"e": 72143,
"s": 72032,
"text": "The parseLine() method of the ParserTool class is used to parse the raw text in OpenNLP. This method accepts −"
},
{
"code": null,
"e": 72197,
"s": 72143,
"text": "a String variable representing the text to be parsed."
},
{
"code": null,
"e": 72251,
"s": 72197,
"text": "a String variable representing the text to be parsed."
},
{
"code": null,
"e": 72268,
"s": 72251,
"text": "a parser object."
},
{
"code": null,
"e": 72285,
"s": 72268,
"text": "a parser object."
},
{
"code": null,
"e": 72349,
"s": 72285,
"text": "an integer representing the number of parses to be carried out."
},
{
"code": null,
"e": 72413,
"s": 72349,
"text": "an integer representing the number of parses to be carried out."
},
{
"code": null,
"e": 72609,
"s": 72413,
"text": "Invoke this method by passing the sentence the following parameters: the parse object created in the previous steps, and an integer representing the required number of parses to be carried out. "
},
{
"code": null,
"e": 72772,
"s": 72609,
"text": "//Parsing the sentence \nString sentence = \"Tutorialspoint is the largest tutorial library.\"; \nParse topParses[] = ParserTool.parseLine(sentence, parser, 1);"
},
{
"code": null,
"e": 72780,
"s": 72772,
"text": "Example"
},
{
"code": null,
"e": 72900,
"s": 72780,
"text": "Following is the program which parses the given raw text. Save this program in a file with the name ParserExample.java."
},
{
"code": null,
"e": 73790,
"s": 72900,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \n\nimport opennlp.tools.cmdline.parser.ParserTool; \nimport opennlp.tools.parser.Parse; \nimport opennlp.tools.parser.Parser; \nimport opennlp.tools.parser.ParserFactory; \nimport opennlp.tools.parser.ParserModel; \n\npublic class ParserExample { \n \n public static void main(String args[]) throws Exception{ \n //Loading parser model \n InputStream inputStream = new FileInputStream(\".../en-parserchunking.bin\"); \n ParserModel model = new ParserModel(inputStream); \n \n //Creating a parser \n Parser parser = ParserFactory.create(model); \n \n //Parsing the sentence \n String sentence = \"Tutorialspoint is the largest tutorial library.\";\n Parse topParses[] = ParserTool.parseLine(sentence, parser, 1); \n \n for (Parse p : topParses) \n p.show(); \n } \n} "
},
{
"code": null,
"e": 73885,
"s": 73790,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 73931,
"s": 73885,
"text": "javac ParserExample.java \njava ParserExample "
},
{
"code": null,
"e": 74036,
"s": 73931,
"text": "On executing, the above program reads the given raw text, parses it, and displays the following output −"
},
{
"code": null,
"e": 74146,
"s": 74036,
"text": "(TOP (S (NP (NN Tutorialspoint)) (VP (VBZ is) (NP (DT the) (JJS largest) (NN\n tutorial) (NN library.))))) \n"
},
{
"code": null,
"e": 74263,
"s": 74146,
"text": "Chunking a sentences refers to breaking/dividing a sentence into parts of words such as word groups and verb groups."
},
{
"code": null,
"e": 74429,
"s": 74263,
"text": "To detect the sentences, OpenNLP uses a model, a file named en-chunker.bin. This is a predefined model which is trained to chunk the sentences in the given raw text."
},
{
"code": null,
"e": 74584,
"s": 74429,
"text": "The opennlp.tools.chunker package contains the classes and interfaces that are used to find non-recursive syntactic annotation such as noun phrase chunks."
},
{
"code": null,
"e": 74865,
"s": 74584,
"text": "You can chunk a sentence using the method chunk() of the ChunkerME class. This method accepts tokens of a sentence and POS tags as parameters. Therefore, before starting the process of chunking, first of all you need to Tokenize the sentence and generate the parts POS tags of it."
},
{
"code": null,
"e": 74922,
"s": 74865,
"text": "To chunk a sentence using OpenNLP library, you need to −"
},
{
"code": null,
"e": 74945,
"s": 74922,
"text": "Tokenize the sentence."
},
{
"code": null,
"e": 74968,
"s": 74945,
"text": "Tokenize the sentence."
},
{
"code": null,
"e": 74994,
"s": 74968,
"text": "Generate POS tags for it."
},
{
"code": null,
"e": 75020,
"s": 74994,
"text": "Generate POS tags for it."
},
{
"code": null,
"e": 75079,
"s": 75020,
"text": "Load the en-chunker.bin model using the ChunkerModel class"
},
{
"code": null,
"e": 75138,
"s": 75079,
"text": "Load the en-chunker.bin model using the ChunkerModel class"
},
{
"code": null,
"e": 75171,
"s": 75138,
"text": "Instantiate the ChunkerME class."
},
{
"code": null,
"e": 75204,
"s": 75171,
"text": "Instantiate the ChunkerME class."
},
{
"code": null,
"e": 75264,
"s": 75204,
"text": "Chunk the sentences using the chunk() method of this class."
},
{
"code": null,
"e": 75324,
"s": 75264,
"text": "Chunk the sentences using the chunk() method of this class."
},
{
"code": null,
"e": 75426,
"s": 75324,
"text": "Following are the steps to be followed to write a program to chunk sentences from the given raw text."
},
{
"code": null,
"e": 75549,
"s": 75426,
"text": "Tokenize the sentences using the tokenize() method of the whitespaceTokenizer class, as shown in the following code block."
},
{
"code": null,
"e": 75763,
"s": 75549,
"text": "//Tokenizing the sentence \nString sentence = \"Hi welcome to Tutorialspoint\"; \nWhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE; \nString[] tokens = whitespaceTokenizer.tokenize(sentence);"
},
{
"code": null,
"e": 75889,
"s": 75763,
"text": "Generate the POS tags of the sentence using the tag() method of the POSTaggerME class, as shown in the following code block."
},
{
"code": null,
"e": 76189,
"s": 75889,
"text": "//Generating the POS tags \nFile file = new File(\"C:/OpenNLP_models/en-pos-maxent.bin\"); \nPOSModel model = new POSModelLoader().load(file); \n//Constructing the tagger \nPOSTaggerME tagger = new POSTaggerME(model); \n//Generating tags from the tokens \nString[] tags = tagger.tag(tokens); "
},
{
"code": null,
"e": 76323,
"s": 76189,
"text": "The model for chunking a sentence is represented by the class named ChunkerModel, which belongs to the package opennlp.tools.chunker."
},
{
"code": null,
"e": 76360,
"s": 76323,
"text": "To load a sentence detection model −"
},
{
"code": null,
"e": 76504,
"s": 76360,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 76648,
"s": 76504,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 76804,
"s": 76648,
"text": "Instantiate the ChunkerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block −"
},
{
"code": null,
"e": 76960,
"s": 76804,
"text": "Instantiate the ChunkerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block −"
},
{
"code": null,
"e": 77134,
"s": 76960,
"text": "//Loading the chunker model \nInputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-chunker.bin\"); \nChunkerModel chunkerModel = new ChunkerModel(inputStream); "
},
{
"code": null,
"e": 77273,
"s": 77134,
"text": "The chunkerME class of the package opennlp.tools.chunker contains methods to chunk the sentences. This is a maximum-entropy-based chunker."
},
{
"code": null,
"e": 77352,
"s": 77273,
"text": "Instantiate this class and pass the model object created in the previous step."
},
{
"code": null,
"e": 77439,
"s": 77352,
"text": "//Instantiate the ChunkerME class \nChunkerME chunkerME = new ChunkerME(chunkerModel); "
},
{
"code": null,
"e": 77625,
"s": 77439,
"text": "The chunk() method of the ChunkerME class is used to chunk the sentences in the raw text passed to it. This method accepts two String arrays representing tokens and tags, as parameters."
},
{
"code": null,
"e": 77730,
"s": 77625,
"text": "Invoke this method by passing the token array and tag array created in the previous steps as parameters."
},
{
"code": null,
"e": 77805,
"s": 77730,
"text": "//Generating the chunks \nString result[] = chunkerME.chunk(tokens, tags); "
},
{
"code": null,
"e": 77813,
"s": 77805,
"text": "Example"
},
{
"code": null,
"e": 77947,
"s": 77813,
"text": "Following is the program to chunk the sentences in the given raw text. Save this program in a file with the name ChunkerExample.java."
},
{
"code": null,
"e": 79572,
"s": 77947,
"text": "import java.io.File; \nimport java.io.FileInputStream; \nimport java.io.IOException; \nimport java.io.InputStream; \n\nimport opennlp.tools.chunker.ChunkerME; \nimport opennlp.tools.chunker.ChunkerModel; \nimport opennlp.tools.cmdline.postag.POSModelLoader; \nimport opennlp.tools.postag.POSModel; \nimport opennlp.tools.postag.POSTaggerME; \nimport opennlp.tools.tokenize.WhitespaceTokenizer; \n\npublic class ChunkerExample{ \n \n public static void main(String args[]) throws IOException { \n //Tokenizing the sentence \n String sentence = \"Hi welcome to Tutorialspoint\"; \n WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE; \n String[] tokens = whitespaceTokenizer.tokenize(sentence); \n \n //Generating the POS tags \n //Load the parts of speech model \n File file = new File(\"C:/OpenNLP_models/en-pos-maxent.bin\"); \n POSModel model = new POSModelLoader().load(file); \n \n //Constructing the tagger \n POSTaggerME tagger = new POSTaggerME(model); \n \n //Generating tags from the tokens \n String[] tags = tagger.tag(tokens); \n \n //Loading the chunker model \n InputStream inputStream = new \n FileInputStream(\"C:/OpenNLP_models/en-chunker.bin\"); \n ChunkerModel chunkerModel = new ChunkerModel(inputStream); \n \n //Instantiate the ChunkerME class \n ChunkerME chunkerME = new ChunkerME(chunkerModel);\n \n //Generating the chunks \n String result[] = chunkerME.chunk(tokens, tags); \n \n for (String s : result) \n System.out.println(s); \n } \n} "
},
{
"code": null,
"e": 79666,
"s": 79572,
"text": "Compile and execute the saved Java file from the Command prompt using the following command −"
},
{
"code": null,
"e": 79714,
"s": 79666,
"text": "javac ChunkerExample.java \njava ChunkerExample "
},
{
"code": null,
"e": 79835,
"s": 79714,
"text": "On executing, the above program reads the given String and chunks the sentences in it, and displays them as shown below."
},
{
"code": null,
"e": 79903,
"s": 79835,
"text": "Loading POS Tagger model ... done (1.040s) \nB-NP \nI-NP \nB-VP \nI-VP\n"
},
{
"code": null,
"e": 80180,
"s": 79903,
"text": "We can also detect the positions or spans of the chunks using the chunkAsSpans() method of the ChunkerME class. This method returns an array of objects of the type Span. The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets."
},
{
"code": null,
"e": 80314,
"s": 80180,
"text": "You can store the spans returned by the chunkAsSpans() method in the Span array and print them, as shown in the following code block."
},
{
"code": null,
"e": 80471,
"s": 80314,
"text": "//Generating the tagged chunk spans \nSpan[] span = chunkerME.chunkAsSpans(tokens, tags); \n \nfor (Span s : span) \n System.out.println(s.toString()); "
},
{
"code": null,
"e": 80479,
"s": 80471,
"text": "Example"
},
{
"code": null,
"e": 80622,
"s": 80479,
"text": "Following is the program which detects the sentences in the given raw text. Save this program in a file with the name ChunkerSpansEample.java."
},
{
"code": null,
"e": 82220,
"s": 80622,
"text": "import java.io.File; \nimport java.io.FileInputStream; \nimport java.io.IOException; \nimport java.io.InputStream; \n\nimport opennlp.tools.chunker.ChunkerME; \nimport opennlp.tools.chunker.ChunkerModel; \nimport opennlp.tools.cmdline.postag.POSModelLoader; \nimport opennlp.tools.postag.POSModel; \nimport opennlp.tools.postag.POSTaggerME; \nimport opennlp.tools.tokenize.WhitespaceTokenizer; \nimport opennlp.tools.util.Span; \n\npublic class ChunkerSpansEample{ \n \n public static void main(String args[]) throws IOException { \n //Load the parts of speech model \n File file = new File(\"C:/OpenNLP_models/en-pos-maxent.bin\"); \n POSModel model = new POSModelLoader().load(file); \n \n //Constructing the tagger \n POSTaggerME tagger = new POSTaggerME(model); \n \n //Tokenizing the sentence \n String sentence = \"Hi welcome to Tutorialspoint\"; \n WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE; \n String[] tokens = whitespaceTokenizer.tokenize(sentence); \n \n //Generating tags from the tokens \n String[] tags = tagger.tag(tokens); \n \n //Loading the chunker model \n InputStream inputStream = new \n FileInputStream(\"C:/OpenNLP_models/en-chunker.bin\"); \n ChunkerModel chunkerModel = new ChunkerModel(inputStream);\n ChunkerME chunkerME = new ChunkerME(chunkerModel); \n \n //Generating the tagged chunk spans \n Span[] span = chunkerME.chunkAsSpans(tokens, tags); \n \n for (Span s : span) \n System.out.println(s.toString()); \n } \n}"
},
{
"code": null,
"e": 82315,
"s": 82220,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 82370,
"s": 82315,
"text": "javac ChunkerSpansEample.java \njava ChunkerSpansEample"
},
{
"code": null,
"e": 82492,
"s": 82370,
"text": "On executing, the above program reads the given String and spans of the chunks in it, and displays the following output −"
},
{
"code": null,
"e": 82559,
"s": 82492,
"text": "Loading POS Tagger model ... done (1.059s) \n[0..2) NP \n[2..4) VP \n"
},
{
"code": null,
"e": 82657,
"s": 82559,
"text": "The probs() method of the ChunkerME class returns the probabilities of the last decoded sequence."
},
{
"code": null,
"e": 82758,
"s": 82657,
"text": "//Getting the probabilities of the last decoded sequence \ndouble[] probs = chunkerME.probs(); "
},
{
"code": null,
"e": 82923,
"s": 82758,
"text": "Following is the program to print the probabilities of the last decoded sequence by the chunker. Save this program in a file with the name ChunkerProbsExample.java."
},
{
"code": null,
"e": 84569,
"s": 82923,
"text": "import java.io.File; \nimport java.io.FileInputStream; \nimport java.io.IOException; \nimport java.io.InputStream; \nimport opennlp.tools.chunker.ChunkerME; \nimport opennlp.tools.chunker.ChunkerModel; \nimport opennlp.tools.cmdline.postag.POSModelLoader; \nimport opennlp.tools.postag.POSModel;\nimport opennlp.tools.postag.POSTaggerME; \nimport opennlp.tools.tokenize.WhitespaceTokenizer; \n\npublic class ChunkerProbsExample{ \n \n public static void main(String args[]) throws IOException { \n //Load the parts of speech model \n File file = new File(\"C:/OpenNLP_models/en-pos-maxent.bin\"); \n POSModel model = new POSModelLoader().load(file); \n \n //Constructing the tagger \n POSTaggerME tagger = new POSTaggerME(model); \n \n //Tokenizing the sentence \n String sentence = \"Hi welcome to Tutorialspoint\"; \n WhitespaceTokenizer whitespaceTokenizer= WhitespaceTokenizer.INSTANCE; \n String[] tokens = whitespaceTokenizer.tokenize(sentence); \n \n //Generating tags from the tokens \n String[] tags = tagger.tag(tokens); \n \n //Loading the chunker model \n InputStream inputStream = new \n FileInputStream(\"C:/OpenNLP_models/en-chunker.bin\"); \n ChunkerModel cModel = new ChunkerModel(inputStream); \n ChunkerME chunkerME = new ChunkerME(cModel); \n \n //Generating the chunk tags \n chunkerME.chunk(tokens, tags); \n \n //Getting the probabilities of the last decoded sequence \n double[] probs = chunkerME.probs(); \n for(int i = 0; i<probs.length; i++) \n System.out.println(probs[i]); \n } \n} "
},
{
"code": null,
"e": 84664,
"s": 84569,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 84722,
"s": 84664,
"text": "javac ChunkerProbsExample.java \njava ChunkerProbsExample "
},
{
"code": null,
"e": 84848,
"s": 84722,
"text": "On executing, the above program reads the given String, chunks it, and prints the probabilities of the last decoded sequence."
},
{
"code": null,
"e": 84929,
"s": 84848,
"text": "0.9592746040797778 \n0.6883933131241501 \n0.8830563473996004 \n0.8951150529746051 \n"
},
{
"code": null,
"e": 85140,
"s": 84929,
"text": "OpenNLP provides a Command Line Interface (CLI) to carry out different operations through the command line. In this chapter, we will take some examples to show how we can use the OpenNLP Command Line Interface."
},
{
"code": null,
"e": 85235,
"s": 85140,
"text": "Hi. How are you? Welcome to Tutorialspoint. We provide free tutorials on various technologies\n"
},
{
"code": null,
"e": 85318,
"s": 85235,
"text": " > opennlp TokenizerME path_for_models../en-token.bin <inputfile..> outputfile.. \n"
},
{
"code": null,
"e": 85397,
"s": 85318,
"text": "C:\\> opennlp TokenizerME C:\\OpenNLP_models/en-token.bin <input.txt >output.txt"
},
{
"code": null,
"e": 85496,
"s": 85397,
"text": "Loading Tokenizer model ... done (0.207s) \nAverage: 214.3 sent/s \nTotal: 3 sent \nRuntime: 0.014s\n"
},
{
"code": null,
"e": 85594,
"s": 85496,
"text": "Hi . How are you ? Welcome to Tutorialspoint . We provide free tutorials on various technologies\n"
},
{
"code": null,
"e": 85689,
"s": 85594,
"text": "Hi. How are you? Welcome to Tutorialspoint. We provide free tutorials on various technologies\n"
},
{
"code": null,
"e": 85777,
"s": 85689,
"text": " > opennlp SentenceDetector path_for_models../en-token.bin <inputfile..> outputfile.. \n"
},
{
"code": null,
"e": 85869,
"s": 85777,
"text": "C:\\> opennlp SentenceDetector C:\\OpenNLP_models/en-sent.bin <input.txt > output_sendet.txt "
},
{
"code": null,
"e": 85977,
"s": 85869,
"text": "Loading Sentence Detector model ... done (0.067s) \n\nAverage: 750.0 sent/s \nTotal: 3 sent \nRuntime: 0.004s\n"
},
{
"code": null,
"e": 86075,
"s": 85977,
"text": "Hi. How are you? \nWelcome to Tutorialspoint. \nWe provide free tutorials on various technologies \n"
},
{
"code": null,
"e": 86231,
"s": 86075,
"text": "<START:person> <START:person> Mike <END> <END> is senior programming manager and \n<START:person> Rama <END> is a clerk both are working at Tutorialspoint \n"
},
{
"code": null,
"e": 86304,
"s": 86231,
"text": " > opennlp TokenNameFinder path_for_models../en-token.bin <inputfile.. \n"
},
{
"code": null,
"e": 86390,
"s": 86304,
"text": "C:\\>opennlp TokenNameFinder C:\\OpenNLP_models\\en-ner-person.bin <input_namefinder.txt"
},
{
"code": null,
"e": 86651,
"s": 86390,
"text": "Loading Token Name Finder model ... done (0.730s) \n<START:person> <START:person> Mike <END> <END> is senior programming manager and \n<START:person> Rama <END> is a clerk both are working at Tutorialspoint \nAverage: 55.6 sent/s \nTotal: 1 sent \nRuntime: 0.018s\n"
},
{
"code": null,
"e": 86747,
"s": 86651,
"text": "Hi. How are you? Welcome to Tutorialspoint. We provide free tutorials on various technologies \n"
},
{
"code": null,
"e": 86814,
"s": 86747,
"text": " > opennlp POSTagger path_for_models../en-token.bin <inputfile.. \n"
},
{
"code": null,
"e": 86885,
"s": 86814,
"text": "C:\\>opennlp POSTagger C:\\OpenNLP_models/en-pos-maxent.bin < input.txt "
},
{
"code": null,
"e": 87133,
"s": 86885,
"text": "Loading POS Tagger model ... done (1.315s) \nHi._NNP How_WRB are_VBP you?_JJ Welcome_NNP to_TO Tutorialspoint._NNP We_PRP \nprovide_VBP free_JJ tutorials_NNS on_IN various_JJ technologies_NNS \n\nAverage: 66.7 sent/s \nTotal: 1 sent \nRuntime: 0.015s \n"
},
{
"code": null,
"e": 87140,
"s": 87133,
"text": " Print"
},
{
"code": null,
"e": 87151,
"s": 87140,
"text": " Add Notes"
}
] |
PowerShell: Wait for the First command to finish | We know that PowerShell executes commands sequentially until we specify some parallel Jobs but sometimes the next command executes before the First command because the first command might be taking a long time to retrieve the data. In that case, if you want the previous command to finish first and then the next command to get executed, you can use PowerShell Job functionality.
For example, we need to write a script to ask for the user input to terminate process ID but the program should retrieve the process IDs first.
$job = Start-Job {Get-Process}
Wait-Job $job | Out-Null
Receive-Job $job
$id = Read-Host "Enter the Process ID to terminate the Process "
Stop-Process -Id $id -PassThru -Verbose
In the above example, we are starting a PowerShell process job inside the Start-Job command and waiting for it to proceed further until it gets executed using the Wait-Jobcommand. Once Get-Process
command execution completes, the output will be displayed using the Receive-Job command and at the next, it asks for the process ID to get it terminate the specific process. | [
{
"code": null,
"e": 1442,
"s": 1062,
"text": "We know that PowerShell executes commands sequentially until we specify some parallel Jobs but sometimes the next command executes before the First command because the first command might be taking a long time to retrieve the data. In that case, if you want the previous command to finish first and then the next command to get executed, you can use PowerShell Job functionality."
},
{
"code": null,
"e": 1586,
"s": 1442,
"text": "For example, we need to write a script to ask for the user input to terminate process ID but the program should retrieve the process IDs first."
},
{
"code": null,
"e": 1764,
"s": 1586,
"text": "$job = Start-Job {Get-Process}\nWait-Job $job | Out-Null\nReceive-Job $job\n$id = Read-Host \"Enter the Process ID to terminate the Process \"\nStop-Process -Id $id -PassThru -Verbose"
},
{
"code": null,
"e": 1961,
"s": 1764,
"text": "In the above example, we are starting a PowerShell process job inside the Start-Job command and waiting for it to proceed further until it gets executed using the Wait-Jobcommand. Once Get-Process"
},
{
"code": null,
"e": 2135,
"s": 1961,
"text": "command execution completes, the output will be displayed using the Receive-Job command and at the next, it asks for the process ID to get it terminate the specific process."
}
] |
JavaMail API - Sending Email With Inline Imagess | Here is an example to send an HTML email from your machine with inline image. Here we have used JangoSMPT server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter.
To send a email with an inline image, the steps followed are:
Get a Session
Get a Session
Create a default MimeMessage object and set From, To, Subject in the message.
Create a default MimeMessage object and set From, To, Subject in the message.
Create a MimeMultipart object.
Create a MimeMultipart object.
In our example we will have an HTML part and an Image in the email. So first create the HTML content and set it in the multipart object as:
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
In our example we will have an HTML part and an Image in the email. So first create the HTML content and set it in the multipart object as:
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
Next add the image by creating a Datahandler as follows:
// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource(
"/home/manisha/javamail-mini-logo.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<image>");
Next add the image by creating a Datahandler as follows:
// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource(
"/home/manisha/javamail-mini-logo.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<image>");
Next set the multipart in the message as follows:
message.setContent(multipart);
Next set the multipart in the message as follows:
message.setContent(multipart);
Send the message using the Transport object.
Send the message using the Transport object.
Create a java class file SendInlineImagesInEmail, the contents of which are as follows:
package com.tutorialspoint;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendInlineImagesInEmail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "[email protected]";
// Sender's email ID needs to be mentioned
String from = "[email protected]";
final String username = "manishaspatil";//change accordingly
final String password = "******";//change accordingly
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// This mail has 2 part, the BODY and the embedded image
MimeMultipart multipart = new MimeMultipart("related");
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource(
"/home/manisha/javamail-mini-logo.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<image>");
// add image to the multipart
multipart.addBodyPart(messageBodyPart);
// put everything together
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
As we are using the SMTP server provided by the host provider JangoSMTP, we need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password.
Now that our class is ready, let us compile the above class. I've saved the class SendInlineImagesInEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt:
javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendInlineImagesInEmail.java
Now that the class is compiled, execute the below command to run:
java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendInlineImagesInEmail
You should see the following message on the command console:
Sent message successfully....
As I'm sending an email to my gmail address through JangoSMTP, the following mail would be received in my gmail account inbox:
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2302,
"s": 2071,
"text": "Here is an example to send an HTML email from your machine with inline image. Here we have used JangoSMPT server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter."
},
{
"code": null,
"e": 2364,
"s": 2302,
"text": "To send a email with an inline image, the steps followed are:"
},
{
"code": null,
"e": 2378,
"s": 2364,
"text": "Get a Session"
},
{
"code": null,
"e": 2392,
"s": 2378,
"text": "Get a Session"
},
{
"code": null,
"e": 2470,
"s": 2392,
"text": "Create a default MimeMessage object and set From, To, Subject in the message."
},
{
"code": null,
"e": 2548,
"s": 2470,
"text": "Create a default MimeMessage object and set From, To, Subject in the message."
},
{
"code": null,
"e": 2579,
"s": 2548,
"text": "Create a MimeMultipart object."
},
{
"code": null,
"e": 2610,
"s": 2579,
"text": "Create a MimeMultipart object."
},
{
"code": null,
"e": 2983,
"s": 2610,
"text": "In our example we will have an HTML part and an Image in the email. So first create the HTML content and set it in the multipart object as:\n// first part (the html)\nBodyPart messageBodyPart = new MimeBodyPart();\nString htmlText = \"<H1>Hello</H1><img src=\\\"cid:image\\\">\";\nmessageBodyPart.setContent(htmlText, \"text/html\");\n// add it\nmultipart.addBodyPart(messageBodyPart);\n"
},
{
"code": null,
"e": 3123,
"s": 2983,
"text": "In our example we will have an HTML part and an Image in the email. So first create the HTML content and set it in the multipart object as:"
},
{
"code": null,
"e": 3355,
"s": 3123,
"text": "// first part (the html)\nBodyPart messageBodyPart = new MimeBodyPart();\nString htmlText = \"<H1>Hello</H1><img src=\\\"cid:image\\\">\";\nmessageBodyPart.setContent(htmlText, \"text/html\");\n// add it\nmultipart.addBodyPart(messageBodyPart);"
},
{
"code": null,
"e": 3664,
"s": 3355,
"text": "Next add the image by creating a Datahandler as follows:\n// second part (the image)\nmessageBodyPart = new MimeBodyPart();\nDataSource fds = new FileDataSource(\n \"/home/manisha/javamail-mini-logo.png\");\n\nmessageBodyPart.setDataHandler(new DataHandler(fds));\nmessageBodyPart.setHeader(\"Content-ID\", \"<image>\");\n"
},
{
"code": null,
"e": 3721,
"s": 3664,
"text": "Next add the image by creating a Datahandler as follows:"
},
{
"code": null,
"e": 3972,
"s": 3721,
"text": "// second part (the image)\nmessageBodyPart = new MimeBodyPart();\nDataSource fds = new FileDataSource(\n \"/home/manisha/javamail-mini-logo.png\");\n\nmessageBodyPart.setDataHandler(new DataHandler(fds));\nmessageBodyPart.setHeader(\"Content-ID\", \"<image>\");"
},
{
"code": null,
"e": 4054,
"s": 3972,
"text": "Next set the multipart in the message as follows:\nmessage.setContent(multipart);\n"
},
{
"code": null,
"e": 4104,
"s": 4054,
"text": "Next set the multipart in the message as follows:"
},
{
"code": null,
"e": 4135,
"s": 4104,
"text": "message.setContent(multipart);"
},
{
"code": null,
"e": 4180,
"s": 4135,
"text": "Send the message using the Transport object."
},
{
"code": null,
"e": 4225,
"s": 4180,
"text": "Send the message using the Transport object."
},
{
"code": null,
"e": 4313,
"s": 4225,
"text": "Create a java class file SendInlineImagesInEmail, the contents of which are as follows:"
},
{
"code": null,
"e": 7411,
"s": 4313,
"text": "package com.tutorialspoint;\n\nimport java.util.Properties;\nimport javax.activation.DataHandler;\nimport javax.activation.DataSource;\nimport javax.activation.FileDataSource;\nimport javax.mail.BodyPart;\nimport javax.mail.Message;\nimport javax.mail.MessagingException;\nimport javax.mail.PasswordAuthentication;\nimport javax.mail.Session;\nimport javax.mail.Transport;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeBodyPart;\nimport javax.mail.internet.MimeMessage;\nimport javax.mail.internet.MimeMultipart;\n\npublic class SendInlineImagesInEmail {\n public static void main(String[] args) {\n // Recipient's email ID needs to be mentioned.\n String to = \"[email protected]\";\n\n // Sender's email ID needs to be mentioned\n String from = \"[email protected]\";\n final String username = \"manishaspatil\";//change accordingly\n final String password = \"******\";//change accordingly\n\n // Assuming you are sending email through relay.jangosmtp.net\n String host = \"relay.jangosmtp.net\";\n\n Properties props = new Properties();\n props.put(\"mail.smtp.auth\", \"true\");\n props.put(\"mail.smtp.starttls.enable\", \"true\");\n props.put(\"mail.smtp.host\", host);\n props.put(\"mail.smtp.port\", \"25\");\n\n Session session = Session.getInstance(props,\n new javax.mail.Authenticator() {\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(username, password);\n }\n });\n\n try {\n\n // Create a default MimeMessage object.\n Message message = new MimeMessage(session);\n\n // Set From: header field of the header.\n message.setFrom(new InternetAddress(from));\n\n // Set To: header field of the header.\n message.setRecipients(Message.RecipientType.TO,\n InternetAddress.parse(to));\n\n // Set Subject: header field\n message.setSubject(\"Testing Subject\");\n\n // This mail has 2 part, the BODY and the embedded image\n MimeMultipart multipart = new MimeMultipart(\"related\");\n\n // first part (the html)\n BodyPart messageBodyPart = new MimeBodyPart();\n String htmlText = \"<H1>Hello</H1><img src=\\\"cid:image\\\">\";\n messageBodyPart.setContent(htmlText, \"text/html\");\n // add it\n multipart.addBodyPart(messageBodyPart);\n\n // second part (the image)\n messageBodyPart = new MimeBodyPart();\n DataSource fds = new FileDataSource(\n \"/home/manisha/javamail-mini-logo.png\");\n\n messageBodyPart.setDataHandler(new DataHandler(fds));\n messageBodyPart.setHeader(\"Content-ID\", \"<image>\");\n\n // add image to the multipart\n multipart.addBodyPart(messageBodyPart);\n\n // put everything together\n message.setContent(multipart);\n // Send message\n Transport.send(message);\n\n System.out.println(\"Sent message successfully....\");\n\n } catch (MessagingException e) {\n throw new RuntimeException(e);\n }\n }\n}"
},
{
"code": null,
"e": 7617,
"s": 7411,
"text": "As we are using the SMTP server provided by the host provider JangoSMTP, we need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password."
},
{
"code": null,
"e": 7976,
"s": 7617,
"text": "Now that our class is ready, let us compile the above class. I've saved the class SendInlineImagesInEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt:"
},
{
"code": null,
"e": 8074,
"s": 7976,
"text": "javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendInlineImagesInEmail.java"
},
{
"code": null,
"e": 8140,
"s": 8074,
"text": "Now that the class is compiled, execute the below command to run:"
},
{
"code": null,
"e": 8232,
"s": 8140,
"text": "java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendInlineImagesInEmail"
},
{
"code": null,
"e": 8293,
"s": 8232,
"text": "You should see the following message on the command console:"
},
{
"code": null,
"e": 8323,
"s": 8293,
"text": "Sent message successfully...."
},
{
"code": null,
"e": 8450,
"s": 8323,
"text": "As I'm sending an email to my gmail address through JangoSMTP, the following mail would be received in my gmail account inbox:"
},
{
"code": null,
"e": 8457,
"s": 8450,
"text": " Print"
},
{
"code": null,
"e": 8468,
"s": 8457,
"text": " Add Notes"
}
] |
Machine Learning for Building Recommender System in Python | by Yuefeng Zhang, PhD | Towards Data Science | Recommender systems are widely used in product recommendations such as recommendations of music, movies, books, news, research articles, restaurants, etc. [1][5][9][10].
There are two popular methods for building recommender systems:
collaborative filtering [3][4][5][10]
Content-based filtering [6][9]
The collaborative filtering method [5][10] predicts (filters) the interests of a user on a product by collecting preferences information from many other users (collaborating). The assumption behind the collaborative filtering method is that if a person P1 has the same opinion as another person P2 on an issue, P1 is more likely to share P2’s opinion on a different issue than that of a randomly chosen person [5].
Content-based filtering method [6][9] utilizes product features/attributes to recommend other products similar to what the user likes, based on other users’ previous actions or explicit feedback such as rating on products.
A recommender system may use either or both of these two methods.
In this article, I use the Kaggle Netflix prize data [2] to demonstrate how to use model-based collaborative filtering method to build a recommender system in Python.
The rest of the article is arranged as follows:
Overview of collaborative filtering
Build recommender system in Python
Summary
As described in [5], the main idea behind collaborative filtering is that one person often gets the best recommendations from another with similar interests. Collaborative filtering uses various techniques to match people with similar interests and make recommendations based on shared interests.
The high-level workflow of a collaborative filtering system can be described as follows:
A user rates items (e.g., movies, books) to express his or her preferences on the items
The system treats the ratings as an approximate representation of the user’s interest in items
The system matches this user’s ratings with other users’ ratings and finds the people with the most similar ratings
The system recommends items that the similar users have rated highly but not yet being rated by this user
Typically a collaborative filtering system recommends products to a given user in two steps [5]:
Step 1: Look for people who share the same rating patterns with the given user
Step 2: Use the ratings from the people found in step 1 to calculate a prediction of a rating by the given user on a product
This is called user-based collaborative filtering. One specific implementation of this method is the user-based Nearest Neighbor algorithm.
As an alternative, item-based collaborative filtering (e.g., users who are interested in x also interested in y) works in an item-centric manner:
Step 1: Build an item-item matrix of the rating relationships between pairs of items
Step 2: Predict the rating of the current user on a product by examining the matrix and matching that user’s rating data
There are two types of collaborative filtering system:
Model-based
Memory-based
In a model-based system, we develop models using different machine learning algorithms to predict users’ rating of unrated items [5]. There are many model-based collaborative filtering algorithms such as Matrix factorization algorithms (e.g., singular value decomposition (SVD), Alternating Least Squares (ALS) algorithm [8]), Bayesian networks, clustering models, etc.[5].
A memory-based system uses users’ rating data to compute the similarity between users or items. Typical examples of this type of systems are neighbourhood-based method and item-based/user-based top-N recommendations [5].
This article describes how to build a model-based collaborative filtering system using the SVD model.
This section describes how to build a recommender system in Python.
There are multiple Python libraries available (e.g., Python scikit Surprise [7], Spark RDD-based API for collaborative filtering [8]) for building recommender systems. I use the Python scikit Surprise library in this article for demonstration purpose.
The Surprise library can be installed as follows:
pip install scikit-surprise
As described before, I use the Kaggle Netflix prize data [2] in this article. There are multiple data files for different purposes. The following data files are used in this article:
training data:
combined_data_1.txt
combined_data_2.txt
combined_data_3.txt
combined_data_4.txt
Movie titles data file:
movie_titles.csv
The training dataset is too big to be handled on a Laptop. Thus I only load the first 100,000 records from each of the training data files for demonstration purpose.
Once training data files have been downloaded onto a local machine, the first 100,000 records from each of the training data files can be loaded into memory as Pandas DataFrames as follows:
def readFile(file_path, rows=100000): data_dict = {'Cust_Id' : [], 'Movie_Id' : [], 'Rating' : [], 'Date' : []} f = open(file_path, "r") count = 0 for line in f: count += 1 if count > rows: break if ':' in line: movidId = line[:-2] # remove the last character ':' movieId = int(movidId) else: customerID, rating, date = line.split(',') data_dict['Cust_Id'].append(customerID) data_dict['Movie_Id'].append(movieId) data_dict['Rating'].append(rating) data_dict['Date'].append(date.rstrip("\n")) f.close() return pd.DataFrame(data_dict)df1 = readFile('./data/netflix/combined_data_1.txt', rows=100000)df2 = readFile('./data/netflix/combined_data_2.txt', rows=100000)df3 = readFile('./data/netflix/combined_data_3.txt', rows=100000)df4 = readFile('./data/netflix/combined_data_4.txt', rows=100000)df1['Rating'] = df1['Rating'].astype(float)df2['Rating'] = df2['Rating'].astype(float)df3['Rating'] = df3['Rating'].astype(float)df4['Rating'] = df4['Rating'].astype(float)
The resulting different DataFrames for different portions of training data are combined into one as follows:
df = df1.copy()df = df.append(df2)df = df.append(df3)df = df.append(df4)df.index = np.arange(0,len(df))df.head(10)
The movie titles file can be loaded into memory as Pandas DataFrame:
df_title = pd.read_csv('./data/netflix/movie_titles.csv', encoding = "ISO-8859-1", header = None, names = ['Movie_Id', 'Year', 'Name'])df_title.head(10)
The Dataset module in Surprise provides different methods for loading data from files, Pandas DataFrames, or built-in datasets such as ml-100k (MovieLens 100k) [4]:
Dataset.load_builtin()
Dataset.load_from_file()
Dataset.load_from_df()
I use the load_from_df() method to load data from Pandas DataFrame in this article.
The Reader class in Surprise is to parse a file containing users, items, and users’ ratings on items. The default format is that each rating is stored in a separate line in the following order separated by space: user item rating
This order and the separator are configurable using the following parameters:
line_format is a string like “item user rating” to indicate the order of the data with field names separated by a space
sep is used to specify separator between fields, such as space, ‘,’, etc.
rating_scale is to specify the rating scale. The default value is (1, 5)
skip_lines is to indicate the number of lines to skip at the beginning of the file and the default is 0
I use the default settings in this article. The item, user, rating correspond to the columns of Cust_Id, Movie_Id, and Rating of the DataFrame respectively.
The Surprise library [7] contains the implementation of multiple models/algorithms for building recommender systems such as SVD, Probabilistic Matrix Factorization (PMF), Non-negative Matrix Factorization (NMF), etc. The SVD model is used in this article.
The following code is to load data from Pandas DataFrame and create a SVD model instance:
from surprise import Reader, Dataset, SVDfrom surprise.model_selection.validation import cross_validatereader = Reader()data = Dataset.load_from_df(df[['Cust_Id', 'Movie_Id', 'Rating']], reader)svd = SVD()
Once the data and model for product recommendation are ready, the model can be evaluated using cross-validation as follows:
# Run 5-fold cross-validation and print resultscross_validate(svd, data, measures=['RMSE', 'MAE'], cv=5, verbose=True)
The following are the results of the cross validation of the SVD model:
Once the model has been evaluated to our satisfaction, then we can re-train the model using the entire training dataset:
trainset = data.build_full_trainset()svd.fit(trainset)
After a recommendation model has been trained appropriately, it can be used for prediction.
For example, given a user (e.g., Customer Id 785314), we can use the trained model to predict the ratings given by the user on different products (i.e., Movie titles):
titles = df_title.copy()titles['Estimate_Score'] = titles['Movie_Id'].apply(lambda x: svd.predict(785314, x).est)
To recommend products (i.e., movies) to the given user, we can sort the list of movies in decreasing order of predicted ratings and take the top N movies as recommendations:
titles = titles.sort_values(by=['Estimate_Score'], ascending=False)titles.head(10)
The following are the top 10 movies to be recommended to the user with Customer Id 785314:
In this article, I used the scikit Surprise library [7] and the Kaggle Netflix prize data [2] to demonstrate how to use model-based collaborative filtering method to build a recommender system in Python.
As described at the beginning of this article, the dataset is too big to be handled on a laptop or any typical single personal computer. Thus I only loaded the first 100,000 records from each of the training dataset files for demonstration purpose.
In the settings of real applications, I would recommend to use Surprise with Koalas or use the ALS algorithm in Spark MLLib to implement collaborative filtering system and run it on Spark cluster [8].
The Jupyter notebook with all of the source code used in this article is available in Github [11].
DLao, Netflix — Movie recommendationNetflix Prize data, Dataset from Netflix’s competition to improve their reccommendation algorithmRecommender systemA. Ajitsaria, Build a Recommendation Engine With Collaborative FilteringCollaborative filteringContent-based FilteringSurpriseS. Ryza, U. Laserson, et. al., Advanced Analytics with Spark, O’Reilly, April 2015N.S. Chauhan, How to build a Restaurant Recommendation Engine (part-1)N.S. Chauhan, How to build a Restaurant Recommendation Engine (part-2)Y. Zhang, Jupyter notebook in Github
DLao, Netflix — Movie recommendation
Netflix Prize data, Dataset from Netflix’s competition to improve their reccommendation algorithm
Recommender system
A. Ajitsaria, Build a Recommendation Engine With Collaborative Filtering
Collaborative filtering
Content-based Filtering
Surprise
S. Ryza, U. Laserson, et. al., Advanced Analytics with Spark, O’Reilly, April 2015
N.S. Chauhan, How to build a Restaurant Recommendation Engine (part-1)
N.S. Chauhan, How to build a Restaurant Recommendation Engine (part-2)
Y. Zhang, Jupyter notebook in Github | [
{
"code": null,
"e": 341,
"s": 171,
"text": "Recommender systems are widely used in product recommendations such as recommendations of music, movies, books, news, research articles, restaurants, etc. [1][5][9][10]."
},
{
"code": null,
"e": 405,
"s": 341,
"text": "There are two popular methods for building recommender systems:"
},
{
"code": null,
"e": 443,
"s": 405,
"text": "collaborative filtering [3][4][5][10]"
},
{
"code": null,
"e": 474,
"s": 443,
"text": "Content-based filtering [6][9]"
},
{
"code": null,
"e": 889,
"s": 474,
"text": "The collaborative filtering method [5][10] predicts (filters) the interests of a user on a product by collecting preferences information from many other users (collaborating). The assumption behind the collaborative filtering method is that if a person P1 has the same opinion as another person P2 on an issue, P1 is more likely to share P2’s opinion on a different issue than that of a randomly chosen person [5]."
},
{
"code": null,
"e": 1112,
"s": 889,
"text": "Content-based filtering method [6][9] utilizes product features/attributes to recommend other products similar to what the user likes, based on other users’ previous actions or explicit feedback such as rating on products."
},
{
"code": null,
"e": 1178,
"s": 1112,
"text": "A recommender system may use either or both of these two methods."
},
{
"code": null,
"e": 1345,
"s": 1178,
"text": "In this article, I use the Kaggle Netflix prize data [2] to demonstrate how to use model-based collaborative filtering method to build a recommender system in Python."
},
{
"code": null,
"e": 1393,
"s": 1345,
"text": "The rest of the article is arranged as follows:"
},
{
"code": null,
"e": 1429,
"s": 1393,
"text": "Overview of collaborative filtering"
},
{
"code": null,
"e": 1464,
"s": 1429,
"text": "Build recommender system in Python"
},
{
"code": null,
"e": 1472,
"s": 1464,
"text": "Summary"
},
{
"code": null,
"e": 1769,
"s": 1472,
"text": "As described in [5], the main idea behind collaborative filtering is that one person often gets the best recommendations from another with similar interests. Collaborative filtering uses various techniques to match people with similar interests and make recommendations based on shared interests."
},
{
"code": null,
"e": 1858,
"s": 1769,
"text": "The high-level workflow of a collaborative filtering system can be described as follows:"
},
{
"code": null,
"e": 1946,
"s": 1858,
"text": "A user rates items (e.g., movies, books) to express his or her preferences on the items"
},
{
"code": null,
"e": 2041,
"s": 1946,
"text": "The system treats the ratings as an approximate representation of the user’s interest in items"
},
{
"code": null,
"e": 2157,
"s": 2041,
"text": "The system matches this user’s ratings with other users’ ratings and finds the people with the most similar ratings"
},
{
"code": null,
"e": 2263,
"s": 2157,
"text": "The system recommends items that the similar users have rated highly but not yet being rated by this user"
},
{
"code": null,
"e": 2360,
"s": 2263,
"text": "Typically a collaborative filtering system recommends products to a given user in two steps [5]:"
},
{
"code": null,
"e": 2439,
"s": 2360,
"text": "Step 1: Look for people who share the same rating patterns with the given user"
},
{
"code": null,
"e": 2564,
"s": 2439,
"text": "Step 2: Use the ratings from the people found in step 1 to calculate a prediction of a rating by the given user on a product"
},
{
"code": null,
"e": 2704,
"s": 2564,
"text": "This is called user-based collaborative filtering. One specific implementation of this method is the user-based Nearest Neighbor algorithm."
},
{
"code": null,
"e": 2850,
"s": 2704,
"text": "As an alternative, item-based collaborative filtering (e.g., users who are interested in x also interested in y) works in an item-centric manner:"
},
{
"code": null,
"e": 2935,
"s": 2850,
"text": "Step 1: Build an item-item matrix of the rating relationships between pairs of items"
},
{
"code": null,
"e": 3056,
"s": 2935,
"text": "Step 2: Predict the rating of the current user on a product by examining the matrix and matching that user’s rating data"
},
{
"code": null,
"e": 3111,
"s": 3056,
"text": "There are two types of collaborative filtering system:"
},
{
"code": null,
"e": 3123,
"s": 3111,
"text": "Model-based"
},
{
"code": null,
"e": 3136,
"s": 3123,
"text": "Memory-based"
},
{
"code": null,
"e": 3510,
"s": 3136,
"text": "In a model-based system, we develop models using different machine learning algorithms to predict users’ rating of unrated items [5]. There are many model-based collaborative filtering algorithms such as Matrix factorization algorithms (e.g., singular value decomposition (SVD), Alternating Least Squares (ALS) algorithm [8]), Bayesian networks, clustering models, etc.[5]."
},
{
"code": null,
"e": 3731,
"s": 3510,
"text": "A memory-based system uses users’ rating data to compute the similarity between users or items. Typical examples of this type of systems are neighbourhood-based method and item-based/user-based top-N recommendations [5]."
},
{
"code": null,
"e": 3833,
"s": 3731,
"text": "This article describes how to build a model-based collaborative filtering system using the SVD model."
},
{
"code": null,
"e": 3901,
"s": 3833,
"text": "This section describes how to build a recommender system in Python."
},
{
"code": null,
"e": 4153,
"s": 3901,
"text": "There are multiple Python libraries available (e.g., Python scikit Surprise [7], Spark RDD-based API for collaborative filtering [8]) for building recommender systems. I use the Python scikit Surprise library in this article for demonstration purpose."
},
{
"code": null,
"e": 4203,
"s": 4153,
"text": "The Surprise library can be installed as follows:"
},
{
"code": null,
"e": 4231,
"s": 4203,
"text": "pip install scikit-surprise"
},
{
"code": null,
"e": 4414,
"s": 4231,
"text": "As described before, I use the Kaggle Netflix prize data [2] in this article. There are multiple data files for different purposes. The following data files are used in this article:"
},
{
"code": null,
"e": 4429,
"s": 4414,
"text": "training data:"
},
{
"code": null,
"e": 4449,
"s": 4429,
"text": "combined_data_1.txt"
},
{
"code": null,
"e": 4469,
"s": 4449,
"text": "combined_data_2.txt"
},
{
"code": null,
"e": 4489,
"s": 4469,
"text": "combined_data_3.txt"
},
{
"code": null,
"e": 4509,
"s": 4489,
"text": "combined_data_4.txt"
},
{
"code": null,
"e": 4533,
"s": 4509,
"text": "Movie titles data file:"
},
{
"code": null,
"e": 4550,
"s": 4533,
"text": "movie_titles.csv"
},
{
"code": null,
"e": 4716,
"s": 4550,
"text": "The training dataset is too big to be handled on a Laptop. Thus I only load the first 100,000 records from each of the training data files for demonstration purpose."
},
{
"code": null,
"e": 4906,
"s": 4716,
"text": "Once training data files have been downloaded onto a local machine, the first 100,000 records from each of the training data files can be loaded into memory as Pandas DataFrames as follows:"
},
{
"code": null,
"e": 6030,
"s": 4906,
"text": "def readFile(file_path, rows=100000): data_dict = {'Cust_Id' : [], 'Movie_Id' : [], 'Rating' : [], 'Date' : []} f = open(file_path, \"r\") count = 0 for line in f: count += 1 if count > rows: break if ':' in line: movidId = line[:-2] # remove the last character ':' movieId = int(movidId) else: customerID, rating, date = line.split(',') data_dict['Cust_Id'].append(customerID) data_dict['Movie_Id'].append(movieId) data_dict['Rating'].append(rating) data_dict['Date'].append(date.rstrip(\"\\n\")) f.close() return pd.DataFrame(data_dict)df1 = readFile('./data/netflix/combined_data_1.txt', rows=100000)df2 = readFile('./data/netflix/combined_data_2.txt', rows=100000)df3 = readFile('./data/netflix/combined_data_3.txt', rows=100000)df4 = readFile('./data/netflix/combined_data_4.txt', rows=100000)df1['Rating'] = df1['Rating'].astype(float)df2['Rating'] = df2['Rating'].astype(float)df3['Rating'] = df3['Rating'].astype(float)df4['Rating'] = df4['Rating'].astype(float)"
},
{
"code": null,
"e": 6139,
"s": 6030,
"text": "The resulting different DataFrames for different portions of training data are combined into one as follows:"
},
{
"code": null,
"e": 6254,
"s": 6139,
"text": "df = df1.copy()df = df.append(df2)df = df.append(df3)df = df.append(df4)df.index = np.arange(0,len(df))df.head(10)"
},
{
"code": null,
"e": 6323,
"s": 6254,
"text": "The movie titles file can be loaded into memory as Pandas DataFrame:"
},
{
"code": null,
"e": 6476,
"s": 6323,
"text": "df_title = pd.read_csv('./data/netflix/movie_titles.csv', encoding = \"ISO-8859-1\", header = None, names = ['Movie_Id', 'Year', 'Name'])df_title.head(10)"
},
{
"code": null,
"e": 6641,
"s": 6476,
"text": "The Dataset module in Surprise provides different methods for loading data from files, Pandas DataFrames, or built-in datasets such as ml-100k (MovieLens 100k) [4]:"
},
{
"code": null,
"e": 6664,
"s": 6641,
"text": "Dataset.load_builtin()"
},
{
"code": null,
"e": 6689,
"s": 6664,
"text": "Dataset.load_from_file()"
},
{
"code": null,
"e": 6712,
"s": 6689,
"text": "Dataset.load_from_df()"
},
{
"code": null,
"e": 6796,
"s": 6712,
"text": "I use the load_from_df() method to load data from Pandas DataFrame in this article."
},
{
"code": null,
"e": 7026,
"s": 6796,
"text": "The Reader class in Surprise is to parse a file containing users, items, and users’ ratings on items. The default format is that each rating is stored in a separate line in the following order separated by space: user item rating"
},
{
"code": null,
"e": 7104,
"s": 7026,
"text": "This order and the separator are configurable using the following parameters:"
},
{
"code": null,
"e": 7224,
"s": 7104,
"text": "line_format is a string like “item user rating” to indicate the order of the data with field names separated by a space"
},
{
"code": null,
"e": 7298,
"s": 7224,
"text": "sep is used to specify separator between fields, such as space, ‘,’, etc."
},
{
"code": null,
"e": 7371,
"s": 7298,
"text": "rating_scale is to specify the rating scale. The default value is (1, 5)"
},
{
"code": null,
"e": 7475,
"s": 7371,
"text": "skip_lines is to indicate the number of lines to skip at the beginning of the file and the default is 0"
},
{
"code": null,
"e": 7632,
"s": 7475,
"text": "I use the default settings in this article. The item, user, rating correspond to the columns of Cust_Id, Movie_Id, and Rating of the DataFrame respectively."
},
{
"code": null,
"e": 7888,
"s": 7632,
"text": "The Surprise library [7] contains the implementation of multiple models/algorithms for building recommender systems such as SVD, Probabilistic Matrix Factorization (PMF), Non-negative Matrix Factorization (NMF), etc. The SVD model is used in this article."
},
{
"code": null,
"e": 7978,
"s": 7888,
"text": "The following code is to load data from Pandas DataFrame and create a SVD model instance:"
},
{
"code": null,
"e": 8184,
"s": 7978,
"text": "from surprise import Reader, Dataset, SVDfrom surprise.model_selection.validation import cross_validatereader = Reader()data = Dataset.load_from_df(df[['Cust_Id', 'Movie_Id', 'Rating']], reader)svd = SVD()"
},
{
"code": null,
"e": 8308,
"s": 8184,
"text": "Once the data and model for product recommendation are ready, the model can be evaluated using cross-validation as follows:"
},
{
"code": null,
"e": 8427,
"s": 8308,
"text": "# Run 5-fold cross-validation and print resultscross_validate(svd, data, measures=['RMSE', 'MAE'], cv=5, verbose=True)"
},
{
"code": null,
"e": 8499,
"s": 8427,
"text": "The following are the results of the cross validation of the SVD model:"
},
{
"code": null,
"e": 8620,
"s": 8499,
"text": "Once the model has been evaluated to our satisfaction, then we can re-train the model using the entire training dataset:"
},
{
"code": null,
"e": 8675,
"s": 8620,
"text": "trainset = data.build_full_trainset()svd.fit(trainset)"
},
{
"code": null,
"e": 8767,
"s": 8675,
"text": "After a recommendation model has been trained appropriately, it can be used for prediction."
},
{
"code": null,
"e": 8935,
"s": 8767,
"text": "For example, given a user (e.g., Customer Id 785314), we can use the trained model to predict the ratings given by the user on different products (i.e., Movie titles):"
},
{
"code": null,
"e": 9049,
"s": 8935,
"text": "titles = df_title.copy()titles['Estimate_Score'] = titles['Movie_Id'].apply(lambda x: svd.predict(785314, x).est)"
},
{
"code": null,
"e": 9223,
"s": 9049,
"text": "To recommend products (i.e., movies) to the given user, we can sort the list of movies in decreasing order of predicted ratings and take the top N movies as recommendations:"
},
{
"code": null,
"e": 9306,
"s": 9223,
"text": "titles = titles.sort_values(by=['Estimate_Score'], ascending=False)titles.head(10)"
},
{
"code": null,
"e": 9397,
"s": 9306,
"text": "The following are the top 10 movies to be recommended to the user with Customer Id 785314:"
},
{
"code": null,
"e": 9601,
"s": 9397,
"text": "In this article, I used the scikit Surprise library [7] and the Kaggle Netflix prize data [2] to demonstrate how to use model-based collaborative filtering method to build a recommender system in Python."
},
{
"code": null,
"e": 9850,
"s": 9601,
"text": "As described at the beginning of this article, the dataset is too big to be handled on a laptop or any typical single personal computer. Thus I only loaded the first 100,000 records from each of the training dataset files for demonstration purpose."
},
{
"code": null,
"e": 10051,
"s": 9850,
"text": "In the settings of real applications, I would recommend to use Surprise with Koalas or use the ALS algorithm in Spark MLLib to implement collaborative filtering system and run it on Spark cluster [8]."
},
{
"code": null,
"e": 10150,
"s": 10051,
"text": "The Jupyter notebook with all of the source code used in this article is available in Github [11]."
},
{
"code": null,
"e": 10686,
"s": 10150,
"text": "DLao, Netflix — Movie recommendationNetflix Prize data, Dataset from Netflix’s competition to improve their reccommendation algorithmRecommender systemA. Ajitsaria, Build a Recommendation Engine With Collaborative FilteringCollaborative filteringContent-based FilteringSurpriseS. Ryza, U. Laserson, et. al., Advanced Analytics with Spark, O’Reilly, April 2015N.S. Chauhan, How to build a Restaurant Recommendation Engine (part-1)N.S. Chauhan, How to build a Restaurant Recommendation Engine (part-2)Y. Zhang, Jupyter notebook in Github"
},
{
"code": null,
"e": 10723,
"s": 10686,
"text": "DLao, Netflix — Movie recommendation"
},
{
"code": null,
"e": 10821,
"s": 10723,
"text": "Netflix Prize data, Dataset from Netflix’s competition to improve their reccommendation algorithm"
},
{
"code": null,
"e": 10840,
"s": 10821,
"text": "Recommender system"
},
{
"code": null,
"e": 10913,
"s": 10840,
"text": "A. Ajitsaria, Build a Recommendation Engine With Collaborative Filtering"
},
{
"code": null,
"e": 10937,
"s": 10913,
"text": "Collaborative filtering"
},
{
"code": null,
"e": 10961,
"s": 10937,
"text": "Content-based Filtering"
},
{
"code": null,
"e": 10970,
"s": 10961,
"text": "Surprise"
},
{
"code": null,
"e": 11053,
"s": 10970,
"text": "S. Ryza, U. Laserson, et. al., Advanced Analytics with Spark, O’Reilly, April 2015"
},
{
"code": null,
"e": 11124,
"s": 11053,
"text": "N.S. Chauhan, How to build a Restaurant Recommendation Engine (part-1)"
},
{
"code": null,
"e": 11195,
"s": 11124,
"text": "N.S. Chauhan, How to build a Restaurant Recommendation Engine (part-2)"
}
] |
K-Means Clustering for Beginners. An in-depth explanation and... | by Aden Haussmann | Towards Data Science | K-Means clustering was one of the first algorithms I learned when I was getting into Machine Learning, right after Linear and Polynomial Regression.
But K-Means diverges fundamentally from the the latter two. Regression analysis is a supervised ML algorithm, whereas K-Means is unsupervised.
What does this mean?
Supervised and unsupervised learning are two broad categories for Machine Learning algorithms:
You feed the program labelled data. In other words, you train the algorithm on data where the correct answers are provided, then apply the learned rules to new data to predict their answers.
This is useful for regression and classification.
You don’t supply labels for the data, and it is up to the program to discover them.
This is useful for clustering and discovering hidden patterns in data.
If you are a beginner, I do recommend you read these articles on Linear and Polynomial Regression first, which I’ve linked below. In them, I cover some foundational Machine Learning knowledge and terminology, upon which I will be building throughout this text.
towardsdatascience.com
towardsdatascience.com
Imagine a dataset with a large number of data points. Our goal is to assign each point to a cluster, or group. To do this, we need to find out where the clusters are, and which points should belong to each one. In our example, we will have two variables: the birth rate and life expectancy of different countries. We can create a scatter plot of this data to visualise our groups.
Why would we want to perform K-Means clustering on this data?
Here’s a practical example: let’s say that the UN wants to group countries into three categories based on these two metrics, so that they can deliver proportionate aid packages depending on respective need.
Instead of eyeballing it, we can use K-Means to automate this process (where K represents the number of clusters we want to create, and Mean represents the average).
There are two key assumptions behind K-means:
The centre of each cluster is the mean of all the data points that belong to the cluster.Each data point belongs to the cluster with the nearest centre point.
The centre of each cluster is the mean of all the data points that belong to the cluster.
Each data point belongs to the cluster with the nearest centre point.
These two simple assumptions describe the entire algorithm. All our program will do is iterate over a few steps, each trying to satisfy the above conditions.
Before we continue, we must discuss the concept of distance. We can use a number of distance metrics in ML, such as Manhattan and Chebyshev, but today we will stick to the more familiar Euclidian, which you will likely remember from high school maths.
In two dimensions, the Euclidian distance between two points is
u0016√((xj — xi)2 + (yj — yi)2)
This is an outline of the algorithm:
Initialise a mean for each cluster by randomly picking points from the dataset and using these as starting values for the means.Assign each point to the nearest cluster.Compute the means for each cluster as the mean for all the points that belong to it.Repeat 2 and 3 either a pre-specified number of times, or until convergence.
Initialise a mean for each cluster by randomly picking points from the dataset and using these as starting values for the means.
Assign each point to the nearest cluster.
Compute the means for each cluster as the mean for all the points that belong to it.
Repeat 2 and 3 either a pre-specified number of times, or until convergence.
As usual, we begin with the imports:
Matplotlib (pyplot & rcParams) — To create our data visualisationScikit-Learn (pairwise_distances_argmin) — To perform Machine LearningNumPy — To do scientific computingcsv — To read csv filescollections (Counter and defaultdict) — For counting
Matplotlib (pyplot & rcParams) — To create our data visualisation
Scikit-Learn (pairwise_distances_argmin) — To perform Machine Learning
NumPy — To do scientific computing
csv — To read csv files
collections (Counter and defaultdict) — For counting
import matplotlib.pyplot as pltimport numpy as npimport csvfrom sklearn.metrics import pairwise_distances_argminfrom collections import Counter, defaultdict
I’ve got a csv file containing the data that looks like this:
Countries,BirthRate(Per1000 - 2008),LifeExpectancy(2008)Afghanistan,46.613,47.532Albania,14.69,76.492Algeria,20.804,72.44...
To wrangle this data, we’re going to need some variables to hold our x values, y values, labels and country names, in the case of this csv file. We can extract all of this information from the file in a single function:
x, y, x_label, y_label, countries = read_csv()
My definition for the read_csv() function is below. Of course, you should adjust it to suit your csv file.
def read_csv(): x = [] y = [] countries = [] x_label = "" y_label = "" with open('dataBoth.csv') as csvfile: reader = csv.reader(csvfile, delimiter=',') lines = 0 for row in reader: if lines >= 1: print(', '.join(row)) x.append(float(row[1])) y.append(float(row[2])) countries.append(row[0]) lines += 1 else: x_label = row[1] y_label = row[2] print(', '.join(row)) lines += 1 return x, y, x_label, y_label, countries
So now that we have our data processed, we need to combine x and y into a 2D list of (x, y) pairs, which we can do like this:
X = np.vstack((x, y)).T
Now we’ve got a 2D list (actually a numpy array) that looks like this:
[[46.613, 47.532] [14.69, 76.492] [20.804, 72.44] ...]
Let’s draw a scatter plot of these data points to see what we’re dealing with here:
plt.xlabel(x_label)plt.ylabel(y_label)plt.scatter(x, y, color='#76c2b4')plt.show()
As you can see, a negative correlation between birth rate and life expectancy is evident. However, 3 distinct groups do not immediately appear. This is where K-Means comes in.
We’ll write the function that will iteratively create our clusters next. A line-by-line explanation of the function is included in the code snippet below as comments, but I will also provide some clarification here.
We can choose random centres using np.random.RandomState(rseed), calling .permutation on that to find an i, and then choosing the ith element of X, which is our 2D list of (x, y) pairs, remember. We have a loop, in which we use pairwise_distance_argmin to calculate the distances between points and centres, then find new centres from the means of the points, then check if the clusters have converged (if no new centre can be chosen such that the means become smaller). This loop terminates when the clusters have converged:
def find_clusters(X, n_clusters, rseed=2): # 1. Randomly choose clusters rng = np.random.RandomState(rseed) i = rng.permutation(X.shape[0])[:n_clusters] centers = X[i] # The main loop # This loop continues until convergence. # You could make it run a set number of times by changing # it to say while x > 5, for example, and removing the break print("\nConverging centres:") while True: # 2a. Assign labels based on closest center # I am using the pairwise_distances_argmin method to # calculate distances between points to centres labels = pairwise_distances_argmin(X, centers) # 2b. Find new centers from means of points new_centers = np.array([X[labels == i].mean(0) for i in range(n_clusters)]) # 2c. Check for convergence if np.all(centers == new_centers): break centers = new_centers # Print converging centres print(centers) print() return centers, labels
Let’s set our number of clusters as 3:
clust_num = 3
All that’s left to do is visualise the result of our K-Means algorithm applied to the data:
centers, labels = find_clusters(X, clust_num)plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis')plt.title('K-Means clustering of countries by birth rate vs life expectancy')plt.xlabel(x_label)plt.ylabel(y_label)plt.show()
That’s the algorithm successfully implemented!
But what if we want more information?
After all, the UN would want to see the names of the countries in each cluster.
We can extract all this information, and print it to the terminal:
print("\nNumber of countries in each cluster:")print(Counter(labels))# Get cluster indicesclusters_indices = defaultdict(list)for index, c in enumerate(labels): clusters_indices[c].append(index)# Print countries in each cluster and meansx = 0while x < clust_num: print("\nCluster " + str(x + 1)) print("----------") for i in clusters_indices[x]: print(countries[i]) print("----------") print("Mean birth rate:") print(centers[x][0]) print("Mean life expectancy:") print(centers[x][1]) x+=1
This will print the countries in each cluster as well as that cluster’s mean birth rate and life expectancy.
It should at least be clear that K-Means clustering is a very useful algorithm with many real-world applications. Hopefully, you’ve learnt enough to perform your own implementation on some interesting data and discover some hidden clusters.
A summary of the content covered:
A brief comparison of supervised vs. unsupervised Machine Learning.An example of the technique’s application.An outline of the algorithm.An example of implementation.
A brief comparison of supervised vs. unsupervised Machine Learning.
An example of the technique’s application.
An outline of the algorithm.
An example of implementation.
If you found the article helpful, I’d love to engage with you! Follow me on Instagram for more Machine Learning and Software Engineering content.
Happy coding!
Skikit Learn sklearn.cluster.KMeans https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html
Python Documentation collections https://docs.python.org/2/library/collections.html
SciPy numpy.random.RandomState https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.RandomState.html
Scikit Learn sklearn.metrics.pairwise_distance_argmin https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise_distances_argmin.html
Numpy.org numpy.vstack https://numpy.org/doc/stable/reference/generated/numpy.vstack.html | [
{
"code": null,
"e": 321,
"s": 172,
"text": "K-Means clustering was one of the first algorithms I learned when I was getting into Machine Learning, right after Linear and Polynomial Regression."
},
{
"code": null,
"e": 464,
"s": 321,
"text": "But K-Means diverges fundamentally from the the latter two. Regression analysis is a supervised ML algorithm, whereas K-Means is unsupervised."
},
{
"code": null,
"e": 485,
"s": 464,
"text": "What does this mean?"
},
{
"code": null,
"e": 580,
"s": 485,
"text": "Supervised and unsupervised learning are two broad categories for Machine Learning algorithms:"
},
{
"code": null,
"e": 771,
"s": 580,
"text": "You feed the program labelled data. In other words, you train the algorithm on data where the correct answers are provided, then apply the learned rules to new data to predict their answers."
},
{
"code": null,
"e": 821,
"s": 771,
"text": "This is useful for regression and classification."
},
{
"code": null,
"e": 905,
"s": 821,
"text": "You don’t supply labels for the data, and it is up to the program to discover them."
},
{
"code": null,
"e": 976,
"s": 905,
"text": "This is useful for clustering and discovering hidden patterns in data."
},
{
"code": null,
"e": 1237,
"s": 976,
"text": "If you are a beginner, I do recommend you read these articles on Linear and Polynomial Regression first, which I’ve linked below. In them, I cover some foundational Machine Learning knowledge and terminology, upon which I will be building throughout this text."
},
{
"code": null,
"e": 1260,
"s": 1237,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1283,
"s": 1260,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1664,
"s": 1283,
"text": "Imagine a dataset with a large number of data points. Our goal is to assign each point to a cluster, or group. To do this, we need to find out where the clusters are, and which points should belong to each one. In our example, we will have two variables: the birth rate and life expectancy of different countries. We can create a scatter plot of this data to visualise our groups."
},
{
"code": null,
"e": 1726,
"s": 1664,
"text": "Why would we want to perform K-Means clustering on this data?"
},
{
"code": null,
"e": 1933,
"s": 1726,
"text": "Here’s a practical example: let’s say that the UN wants to group countries into three categories based on these two metrics, so that they can deliver proportionate aid packages depending on respective need."
},
{
"code": null,
"e": 2099,
"s": 1933,
"text": "Instead of eyeballing it, we can use K-Means to automate this process (where K represents the number of clusters we want to create, and Mean represents the average)."
},
{
"code": null,
"e": 2145,
"s": 2099,
"text": "There are two key assumptions behind K-means:"
},
{
"code": null,
"e": 2304,
"s": 2145,
"text": "The centre of each cluster is the mean of all the data points that belong to the cluster.Each data point belongs to the cluster with the nearest centre point."
},
{
"code": null,
"e": 2394,
"s": 2304,
"text": "The centre of each cluster is the mean of all the data points that belong to the cluster."
},
{
"code": null,
"e": 2464,
"s": 2394,
"text": "Each data point belongs to the cluster with the nearest centre point."
},
{
"code": null,
"e": 2622,
"s": 2464,
"text": "These two simple assumptions describe the entire algorithm. All our program will do is iterate over a few steps, each trying to satisfy the above conditions."
},
{
"code": null,
"e": 2874,
"s": 2622,
"text": "Before we continue, we must discuss the concept of distance. We can use a number of distance metrics in ML, such as Manhattan and Chebyshev, but today we will stick to the more familiar Euclidian, which you will likely remember from high school maths."
},
{
"code": null,
"e": 2938,
"s": 2874,
"text": "In two dimensions, the Euclidian distance between two points is"
},
{
"code": null,
"e": 2970,
"s": 2938,
"text": "u0016√((xj — xi)2 + (yj — yi)2)"
},
{
"code": null,
"e": 3007,
"s": 2970,
"text": "This is an outline of the algorithm:"
},
{
"code": null,
"e": 3337,
"s": 3007,
"text": "Initialise a mean for each cluster by randomly picking points from the dataset and using these as starting values for the means.Assign each point to the nearest cluster.Compute the means for each cluster as the mean for all the points that belong to it.Repeat 2 and 3 either a pre-specified number of times, or until convergence."
},
{
"code": null,
"e": 3466,
"s": 3337,
"text": "Initialise a mean for each cluster by randomly picking points from the dataset and using these as starting values for the means."
},
{
"code": null,
"e": 3508,
"s": 3466,
"text": "Assign each point to the nearest cluster."
},
{
"code": null,
"e": 3593,
"s": 3508,
"text": "Compute the means for each cluster as the mean for all the points that belong to it."
},
{
"code": null,
"e": 3670,
"s": 3593,
"text": "Repeat 2 and 3 either a pre-specified number of times, or until convergence."
},
{
"code": null,
"e": 3707,
"s": 3670,
"text": "As usual, we begin with the imports:"
},
{
"code": null,
"e": 3952,
"s": 3707,
"text": "Matplotlib (pyplot & rcParams) — To create our data visualisationScikit-Learn (pairwise_distances_argmin) — To perform Machine LearningNumPy — To do scientific computingcsv — To read csv filescollections (Counter and defaultdict) — For counting"
},
{
"code": null,
"e": 4018,
"s": 3952,
"text": "Matplotlib (pyplot & rcParams) — To create our data visualisation"
},
{
"code": null,
"e": 4089,
"s": 4018,
"text": "Scikit-Learn (pairwise_distances_argmin) — To perform Machine Learning"
},
{
"code": null,
"e": 4124,
"s": 4089,
"text": "NumPy — To do scientific computing"
},
{
"code": null,
"e": 4148,
"s": 4124,
"text": "csv — To read csv files"
},
{
"code": null,
"e": 4201,
"s": 4148,
"text": "collections (Counter and defaultdict) — For counting"
},
{
"code": null,
"e": 4358,
"s": 4201,
"text": "import matplotlib.pyplot as pltimport numpy as npimport csvfrom sklearn.metrics import pairwise_distances_argminfrom collections import Counter, defaultdict"
},
{
"code": null,
"e": 4420,
"s": 4358,
"text": "I’ve got a csv file containing the data that looks like this:"
},
{
"code": null,
"e": 4545,
"s": 4420,
"text": "Countries,BirthRate(Per1000 - 2008),LifeExpectancy(2008)Afghanistan,46.613,47.532Albania,14.69,76.492Algeria,20.804,72.44..."
},
{
"code": null,
"e": 4765,
"s": 4545,
"text": "To wrangle this data, we’re going to need some variables to hold our x values, y values, labels and country names, in the case of this csv file. We can extract all of this information from the file in a single function:"
},
{
"code": null,
"e": 4812,
"s": 4765,
"text": "x, y, x_label, y_label, countries = read_csv()"
},
{
"code": null,
"e": 4919,
"s": 4812,
"text": "My definition for the read_csv() function is below. Of course, you should adjust it to suit your csv file."
},
{
"code": null,
"e": 5535,
"s": 4919,
"text": "def read_csv(): x = [] y = [] countries = [] x_label = \"\" y_label = \"\" with open('dataBoth.csv') as csvfile: reader = csv.reader(csvfile, delimiter=',') lines = 0 for row in reader: if lines >= 1: print(', '.join(row)) x.append(float(row[1])) y.append(float(row[2])) countries.append(row[0]) lines += 1 else: x_label = row[1] y_label = row[2] print(', '.join(row)) lines += 1 return x, y, x_label, y_label, countries"
},
{
"code": null,
"e": 5661,
"s": 5535,
"text": "So now that we have our data processed, we need to combine x and y into a 2D list of (x, y) pairs, which we can do like this:"
},
{
"code": null,
"e": 5685,
"s": 5661,
"text": "X = np.vstack((x, y)).T"
},
{
"code": null,
"e": 5756,
"s": 5685,
"text": "Now we’ve got a 2D list (actually a numpy array) that looks like this:"
},
{
"code": null,
"e": 5811,
"s": 5756,
"text": "[[46.613, 47.532] [14.69, 76.492] [20.804, 72.44] ...]"
},
{
"code": null,
"e": 5895,
"s": 5811,
"text": "Let’s draw a scatter plot of these data points to see what we’re dealing with here:"
},
{
"code": null,
"e": 5978,
"s": 5895,
"text": "plt.xlabel(x_label)plt.ylabel(y_label)plt.scatter(x, y, color='#76c2b4')plt.show()"
},
{
"code": null,
"e": 6154,
"s": 5978,
"text": "As you can see, a negative correlation between birth rate and life expectancy is evident. However, 3 distinct groups do not immediately appear. This is where K-Means comes in."
},
{
"code": null,
"e": 6370,
"s": 6154,
"text": "We’ll write the function that will iteratively create our clusters next. A line-by-line explanation of the function is included in the code snippet below as comments, but I will also provide some clarification here."
},
{
"code": null,
"e": 6896,
"s": 6370,
"text": "We can choose random centres using np.random.RandomState(rseed), calling .permutation on that to find an i, and then choosing the ith element of X, which is our 2D list of (x, y) pairs, remember. We have a loop, in which we use pairwise_distance_argmin to calculate the distances between points and centres, then find new centres from the means of the points, then check if the clusters have converged (if no new centre can be chosen such that the means become smaller). This loop terminates when the clusters have converged:"
},
{
"code": null,
"e": 7894,
"s": 6896,
"text": "def find_clusters(X, n_clusters, rseed=2): # 1. Randomly choose clusters rng = np.random.RandomState(rseed) i = rng.permutation(X.shape[0])[:n_clusters] centers = X[i] # The main loop # This loop continues until convergence. # You could make it run a set number of times by changing # it to say while x > 5, for example, and removing the break print(\"\\nConverging centres:\") while True: # 2a. Assign labels based on closest center # I am using the pairwise_distances_argmin method to # calculate distances between points to centres labels = pairwise_distances_argmin(X, centers) # 2b. Find new centers from means of points new_centers = np.array([X[labels == i].mean(0) for i in range(n_clusters)]) # 2c. Check for convergence if np.all(centers == new_centers): break centers = new_centers # Print converging centres print(centers) print() return centers, labels"
},
{
"code": null,
"e": 7933,
"s": 7894,
"text": "Let’s set our number of clusters as 3:"
},
{
"code": null,
"e": 7947,
"s": 7933,
"text": "clust_num = 3"
},
{
"code": null,
"e": 8039,
"s": 7947,
"text": "All that’s left to do is visualise the result of our K-Means algorithm applied to the data:"
},
{
"code": null,
"e": 8271,
"s": 8039,
"text": "centers, labels = find_clusters(X, clust_num)plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis')plt.title('K-Means clustering of countries by birth rate vs life expectancy')plt.xlabel(x_label)plt.ylabel(y_label)plt.show()"
},
{
"code": null,
"e": 8318,
"s": 8271,
"text": "That’s the algorithm successfully implemented!"
},
{
"code": null,
"e": 8356,
"s": 8318,
"text": "But what if we want more information?"
},
{
"code": null,
"e": 8436,
"s": 8356,
"text": "After all, the UN would want to see the names of the countries in each cluster."
},
{
"code": null,
"e": 8503,
"s": 8436,
"text": "We can extract all this information, and print it to the terminal:"
},
{
"code": null,
"e": 9030,
"s": 8503,
"text": "print(\"\\nNumber of countries in each cluster:\")print(Counter(labels))# Get cluster indicesclusters_indices = defaultdict(list)for index, c in enumerate(labels): clusters_indices[c].append(index)# Print countries in each cluster and meansx = 0while x < clust_num: print(\"\\nCluster \" + str(x + 1)) print(\"----------\") for i in clusters_indices[x]: print(countries[i]) print(\"----------\") print(\"Mean birth rate:\") print(centers[x][0]) print(\"Mean life expectancy:\") print(centers[x][1]) x+=1"
},
{
"code": null,
"e": 9139,
"s": 9030,
"text": "This will print the countries in each cluster as well as that cluster’s mean birth rate and life expectancy."
},
{
"code": null,
"e": 9380,
"s": 9139,
"text": "It should at least be clear that K-Means clustering is a very useful algorithm with many real-world applications. Hopefully, you’ve learnt enough to perform your own implementation on some interesting data and discover some hidden clusters."
},
{
"code": null,
"e": 9414,
"s": 9380,
"text": "A summary of the content covered:"
},
{
"code": null,
"e": 9581,
"s": 9414,
"text": "A brief comparison of supervised vs. unsupervised Machine Learning.An example of the technique’s application.An outline of the algorithm.An example of implementation."
},
{
"code": null,
"e": 9649,
"s": 9581,
"text": "A brief comparison of supervised vs. unsupervised Machine Learning."
},
{
"code": null,
"e": 9692,
"s": 9649,
"text": "An example of the technique’s application."
},
{
"code": null,
"e": 9721,
"s": 9692,
"text": "An outline of the algorithm."
},
{
"code": null,
"e": 9751,
"s": 9721,
"text": "An example of implementation."
},
{
"code": null,
"e": 9897,
"s": 9751,
"text": "If you found the article helpful, I’d love to engage with you! Follow me on Instagram for more Machine Learning and Software Engineering content."
},
{
"code": null,
"e": 9911,
"s": 9897,
"text": "Happy coding!"
},
{
"code": null,
"e": 10025,
"s": 9911,
"text": "Skikit Learn sklearn.cluster.KMeans https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html"
},
{
"code": null,
"e": 10109,
"s": 10025,
"text": "Python Documentation collections https://docs.python.org/2/library/collections.html"
},
{
"code": null,
"e": 10230,
"s": 10109,
"text": "SciPy numpy.random.RandomState https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.RandomState.html"
},
{
"code": null,
"e": 10381,
"s": 10230,
"text": "Scikit Learn sklearn.metrics.pairwise_distance_argmin https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise_distances_argmin.html"
}
] |
SQLite - TRUNCATE TABLE Command | Unfortunately, we do not have TRUNCATE TABLE command in SQLite but you can use SQLite DELETE command to delete complete data from an existing table, though it is recommended to use DROP TABLE command to drop the complete table and re-create it once again.
Following is the basic syntax of DELETE command.
sqlite> DELETE FROM table_name;
Following is the basic syntax of DROP TABLE.
sqlite> DROP TABLE table_name;
If you are using DELETE TABLE command to delete all the records, it is recommended to use VACUUM command to clear unused space.
Consider COMPANY table with the following records.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is the example to truncate the above table −
SQLite> DELETE FROM COMPANY;
SQLite> VACUUM;
Now, COMPANY table is truncated completely and nothing will be the output from SELECT statement.
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2895,
"s": 2638,
"text": "Unfortunately, we do not have TRUNCATE TABLE command in SQLite but you can use SQLite DELETE command to delete complete data from an existing table, though it is recommended to use DROP TABLE command to drop the complete table and re-create it once again."
},
{
"code": null,
"e": 2944,
"s": 2895,
"text": "Following is the basic syntax of DELETE command."
},
{
"code": null,
"e": 2977,
"s": 2944,
"text": "sqlite> DELETE FROM table_name;\n"
},
{
"code": null,
"e": 3022,
"s": 2977,
"text": "Following is the basic syntax of DROP TABLE."
},
{
"code": null,
"e": 3054,
"s": 3022,
"text": "sqlite> DROP TABLE table_name;\n"
},
{
"code": null,
"e": 3182,
"s": 3054,
"text": "If you are using DELETE TABLE command to delete all the records, it is recommended to use VACUUM command to clear unused space."
},
{
"code": null,
"e": 3233,
"s": 3182,
"text": "Consider COMPANY table with the following records."
},
{
"code": null,
"e": 3739,
"s": 3233,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 3794,
"s": 3739,
"text": "Following is the example to truncate the above table −"
},
{
"code": null,
"e": 3839,
"s": 3794,
"text": "SQLite> DELETE FROM COMPANY;\nSQLite> VACUUM;"
},
{
"code": null,
"e": 3936,
"s": 3839,
"text": "Now, COMPANY table is truncated completely and nothing will be the output from SELECT statement."
},
{
"code": null,
"e": 3971,
"s": 3936,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3992,
"s": 3971,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4025,
"s": 3992,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4042,
"s": 4025,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4073,
"s": 4042,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 4086,
"s": 4073,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 4093,
"s": 4086,
"text": " Print"
},
{
"code": null,
"e": 4104,
"s": 4093,
"text": " Add Notes"
}
] |
Creating a tree with Left-Child Right-Sibling Representation - GeeksforGeeks | 23 Feb, 2022
Left-Child Right-Sibling Representation is a different representation of an n-ary tree where instead of holding a reference to each and every child node, a node holds just two references, first a reference to its first child, and the other to its immediate next sibling. This new transformation not only removes the need for advanced knowledge of the number of children a node has but also limits the number of references to a maximum of two, thereby making it so much easier to code.
At each node, link children of same parent from left to right.
Parent should be linked with only first child.
Examples:
Left Child Right Sibling tree representation
10
|
2 -> 3 -> 4 -> 5
| |
6 7 -> 8 -> 9
Prerequisite: Left-Child Right-Sibling Representation of Tree
Below is the implementation.
C++
Java
Python3
C#
Javascript
// C++ program to create a tree with left child// right sibling representation.#include<bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *next; struct Node *child;}; // Creating new NodeNode* newNode(int data){ Node *newNode = new Node; newNode->next = newNode->child = NULL; newNode->data = data; return newNode;} // Adds a sibling to a list with starting with nNode *addSibling(Node *n, int data){ if (n == NULL) return NULL; while (n->next) n = n->next; return (n->next = newNode(data));} // Add child Node to a NodeNode *addChild(Node * n, int data){ if (n == NULL) return NULL; // Check if child list is not empty. if (n->child) return addSibling(n->child, data); else return (n->child = newNode(data));} // Traverses tree in depth first ordervoid traverseTree(Node * root){ if (root == NULL) return; while (root) { cout << " " << root->data; if (root->child) traverseTree(root->child); root = root->next; }} //Driver code int main(){ /* Let us create below tree * 10 * / / \ \ * 2 3 4 5 * | / | \ * 6 7 8 9 */ // Left child right sibling /* 10 * | * 2 -> 3 -> 4 -> 5 * | | * 6 7 -> 8 -> 9 */ Node *root = newNode(10); Node *n1 = addChild(root, 2); Node *n2 = addChild(root, 3); Node *n3 = addChild(root, 4); Node *n4 = addChild(n3, 6); Node *n5 = addChild(root, 5); Node *n6 = addChild(n5, 7); Node *n7 = addChild(n5, 8); Node *n8 = addChild(n5, 9); traverseTree(root); return 0;}
// Java program to create a tree with left child// right sibling representation. class GFG { static class NodeTemp { int data; NodeTemp next, child; public NodeTemp(int data) { this.data = data; next = child = null; } } // Adds a sibling to a list with starting with n static public NodeTemp addSibling(NodeTemp node, int data) { if(node == null) return null; while(node.next != null) node = node.next; return(node.next = new NodeTemp(data)); } // Add child Node to a Node static public NodeTemp addChild(NodeTemp node,int data) { if(node == null) return null; // Check if child is not empty. if(node.child != null) return(addSibling(node.child,data)); else return(node.child = new NodeTemp(data)); } // Traverses tree in depth first order static public void traverseTree(NodeTemp root) { if(root == null) return; while(root != null) { System.out.print(root.data + " "); if(root.child != null) traverseTree(root.child); root = root.next; } } // Driver code public static void main(String args[]) { /* Let us create below tree * 10 * / / \ \ * 2 3 4 5 * | / | \ * 6 7 8 9 */ // Left child right sibling /* 10 * | * 2 -> 3 -> 4 -> 5 * | | * 6 7 -> 8 -> 9 */ NodeTemp root = new NodeTemp(10); NodeTemp n1 = addChild(root,2); NodeTemp n2 = addChild(root,3); NodeTemp n3 = addChild(root,4); NodeTemp n4 = addChild(n3,6); NodeTemp n5 = addChild(root,5); NodeTemp n6 = addChild(n5,7); NodeTemp n7 = addChild(n5,8); NodeTemp n8 = addChild(n5,9); traverseTree(root); }} // This code is contributed by M.V.S.Surya Teja.
# Python3 program to create a tree with# left child right sibling representation. # Creating new Nodeclass newNode: def __init__(self, data): self.Next = self.child = None self.data = data # Adds a sibling to a list with# starting with ndef addSibling(n, data): if (n == None): return None while (n.Next): n = n.Next n.Next = newNode(data) return n.Next # Add child Node to a Nodedef addChild(n, data): if (n == None): return None # Check if child list is not empty. if (n.child): return addSibling(n.child, data) else: n.child = newNode(data) return n.child # Traverses tree in depth first orderdef traverseTree(root): if (root == None): return while (root): print(root.data, end = " ") if (root.child): traverseTree(root.child) root = root.Next # Driver codeif __name__ == '__main__': # Let us create below tree # 10 # / / \ \ # 2 3 4 5 # | / | \ # 6 7 8 9 # Left child right sibling # 10 # | # 2 -> 3 -> 4 -> 5 # | | # 6 7 -> 8 -> 9 root = newNode(10) n1 = addChild(root, 2) n2 = addChild(root, 3) n3 = addChild(root, 4) n4 = addChild(n3, 6) n5 = addChild(root, 5) n6 = addChild(n5, 7) n7 = addChild(n5, 8) n8 = addChild(n5, 9) traverseTree(root) # This code is contributed by pranchalK
// C# program to create a tree with left// child right sibling representation.using System; class GFG{public class NodeTemp{ public int data; public NodeTemp next, child; public NodeTemp(int data) { this.data = data; next = child = null; }} // Adds a sibling to a list with// starting with npublic static NodeTemp addSibling(NodeTemp node, int data){ if (node == null) { return null; } while (node.next != null) { node = node.next; } return (node.next = new NodeTemp(data));} // Add child Node to a Nodepublic static NodeTemp addChild(NodeTemp node, int data){ if (node == null) { return null; } // Check if child is not empty. if (node.child != null) { return (addSibling(node.child,data)); } else { return (node.child = new NodeTemp(data)); }} // Traverses tree in depth first orderpublic static void traverseTree(NodeTemp root){ if (root == null) { return; } while (root != null) { Console.Write(root.data + " "); if (root.child != null) { traverseTree(root.child); } root = root.next; }} // Driver codepublic static void Main(string[] args){ /* Let us create below tree * 10 * / / \ \ * 2 3 4 5 * | / | \ * 6 7 8 9 */ // Left child right sibling /* 10 * | * 2 -> 3 -> 4 -> 5 * | | * 6 7 -> 8 -> 9 */ NodeTemp root = new NodeTemp(10); NodeTemp n1 = addChild(root, 2); NodeTemp n2 = addChild(root, 3); NodeTemp n3 = addChild(root, 4); NodeTemp n4 = addChild(n3, 6); NodeTemp n5 = addChild(root, 5); NodeTemp n6 = addChild(n5, 7); NodeTemp n7 = addChild(n5, 8); NodeTemp n8 = addChild(n5, 9); traverseTree(root);}} // This code is contributed by Shrikant13
<script> // Javascript program to create a tree with left child// right sibling representation. class NodeTemp { constructor(data) { this.data=data; this.next = this.child = null; } } // Adds a sibling to a list with starting with n function addSibling(node,data) { if(node == null) return null; while(node.next != null) node = node.next; return(node.next = new NodeTemp(data)); } // Add child Node to a Node function addChild(node,data) { if(node == null) return null; // Check if child is not empty. if(node.child != null) return(addSibling(node.child,data)); else return(node.child = new NodeTemp(data)); } // Traverses tree in depth first order function traverseTree(root) { if(root == null) return; while(root != null) { document.write(root.data + " "); if(root.child != null) traverseTree(root.child); root = root.next; } } // Driver code /* Let us create below tree * 10 * / / \ \ * 2 3 4 5 * | / | \ * 6 7 8 9 */ // Left child right sibling /* 10 * | * 2 -> 3 -> 4 -> 5 * | | * 6 7 -> 8 -> 9 */ let root = new NodeTemp(10); let n1 = addChild(root,2); let n2 = addChild(root,3); let n3 = addChild(root,4); let n4 = addChild(n3,6); let n5 = addChild(root,5); let n6 = addChild(n5,7); let n7 = addChild(n5,8); let n8 = addChild(n5,9); traverseTree(root); // This code is contributed by patel2127 </script>
10 2 3 4 6 5 7 8 9
Level Order Traversal: The above code talks about depth-first traversal. We can also do level order traversal of such representation.
C++
Java
Python3
C#
Javascript
// C++ program to create a tree with left child// right sibling representation.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next; struct Node* child;}; // Creating new NodeNode* newNode(int data){ Node* newNode = new Node; newNode->next = newNode->child = NULL; newNode->data = data; return newNode;} // Adds a sibling to a list with starting with nNode* addSibling(Node* n, int data){ if (n == NULL) return NULL; while (n->next) n = n->next; return (n->next = newNode(data));} // Add child Node to a NodeNode* addChild(Node* n, int data){ if (n == NULL) return NULL; // Check if child list is not empty. if (n->child) return addSibling(n->child, data); else return (n->child = newNode(data));} // Traverses tree in level ordervoid traverseTree(Node* root){ // Corner cases if (root == NULL) return; cout << root->data << " "; if (root->child == NULL) return; // Create a queue and enqueue root queue<Node*> q; Node* curr = root->child; q.push(curr); while (!q.empty()) { // Take out an item from the queue curr = q.front(); q.pop(); // Print next level of taken out item and enqueue // next level's children while (curr != NULL) { cout << curr->data << " "; if (curr->child != NULL) { q.push(curr->child); } curr = curr->next; } }} // Driver codeint main(){ Node* root = newNode(10); Node* n1 = addChild(root, 2); Node* n2 = addChild(root, 3); Node* n3 = addChild(root, 4); Node* n4 = addChild(n3, 6); Node* n5 = addChild(root, 5); Node* n6 = addChild(n5, 7); Node* n7 = addChild(n5, 8); Node* n8 = addChild(n5, 9); traverseTree(root); return 0;}
// Java program to create a tree with left child// right sibling representation.import java.util.*;class GFG{ static class Node { int data; Node next; Node child; }; // Creating new Node static Node newNode(int data) { Node newNode = new Node(); newNode.next = newNode.child = null; newNode.data = data; return newNode; } // Adds a sibling to a list with starting with n static Node addSibling(Node n, int data) { if (n == null) return null; while (n.next != null) n = n.next; return (n.next = newNode(data)); } // Add child Node to a Node static Node addChild(Node n, int data) { if (n == null) return null; // Check if child list is not empty. if (n.child != null) return addSibling(n.child, data); else return (n.child = newNode(data)); } // Traverses tree in level order static void traverseTree(Node root) { // Corner cases if (root == null) return; System.out.print(root.data+ " "); if (root.child == null) return; // Create a queue and enqueue root Queue<Node> q = new LinkedList<>(); Node curr = root.child; q.add(curr); while (!q.isEmpty()) { // Take out an item from the queue curr = q.peek(); q.remove(); // Print next level of taken out item and enqueue // next level's children while (curr != null) { System.out.print(curr.data + " "); if (curr.child != null) { q.add(curr.child); } curr = curr.next; } } } // Driver code public static void main(String[] args) { Node root = newNode(10); Node n1 = addChild(root, 2); Node n2 = addChild(root, 3); Node n3 = addChild(root, 4); Node n4 = addChild(n3, 6); Node n5 = addChild(root, 5); Node n6 = addChild(n5, 7); Node n7 = addChild(n5, 8); Node n8 = addChild(n5, 9); traverseTree(root); }} // This code is contributed by aashish1995
# Python3 program to create a tree with# left child right sibling representationfrom collections import deque class Node: def __init__(self, x): self.data = x self.next = None self.child = None # Adds a sibling to a list with# starting with ndef addSibling(n, data): if (n == None): return None while (n.next): n = n.next n.next = Node(data) return n # Add child Node to a Nodedef addChild(n, data): if (n == None): return None # Check if child list is not empty if (n.child): return addSibling(n.child, data) else: n.child = Node(data) return n # Traverses tree in level orderdef traverseTree(root): # Corner cases if (root == None): return print(root.data, end = " ") if (root.child == None): return # Create a queue and enqueue root q = deque() curr = root.child q.append(curr) while (len(q) > 0): # Take out an item from the queue curr = q.popleft() #q.pop() # Print next level of taken out # item and enqueue next level's children while (curr != None): print(curr.data, end = " ") if (curr.child != None): q.append(curr.child) curr = curr.next # Driver codeif __name__ == '__main__': root = Node(10) n1 = addChild(root, 2) n2 = addChild(root, 3) n3 = addChild(root, 4) n4 = addChild(n3, 6) n5 = addChild(root, 5) n6 = addChild(n5, 7) n7 = addChild(n5, 8) n8 = addChild(n5, 9) traverseTree(root) # This code is contributed by mohit kumar 29
// C# program to create a tree with left child// right sibling representation.using System;using System.Collections.Generic;class GFG{ public class Node { public int data; public Node next; public Node child; }; // Creating new Node static Node newNode(int data) { Node newNode = new Node(); newNode.next = newNode.child = null; newNode.data = data; return newNode; } // Adds a sibling to a list with starting with n static Node addSibling(Node n, int data) { if (n == null) return null; while (n.next != null) n = n.next; return (n.next = newNode(data)); } // Add child Node to a Node static Node addChild(Node n, int data) { if (n == null) return null; // Check if child list is not empty. if (n.child != null) return addSibling(n.child, data); else return (n.child = newNode(data)); } // Traverses tree in level order static void traverseTree(Node root) { // Corner cases if (root == null) return; Console.Write(root.data + " "); if (root.child == null) return; // Create a queue and enqueue root Queue<Node> q = new Queue<Node>(); Node curr = root.child; q.Enqueue(curr); while (q.Count != 0) { // Take out an item from the queue curr = q.Peek(); q.Dequeue(); // Print next level of taken out item and enqueue // next level's children while (curr != null) { Console.Write(curr.data + " "); if (curr.child != null) { q.Enqueue(curr.child); } curr = curr.next; } } } // Driver code public static void Main(String[] args) { Node root = newNode(10); Node n1 = addChild(root, 2); Node n2 = addChild(root, 3); Node n3 = addChild(root, 4); Node n4 = addChild(n3, 6); Node n5 = addChild(root, 5); Node n6 = addChild(n5, 7); Node n7 = addChild(n5, 8); Node n8 = addChild(n5, 9); traverseTree(root); }} // This code is contributed by Rajput-Ji
<script> // JavaScript program to create a// tree with left child// right sibling representation. class Node { // Creating new Node constructor(data) { this.data=data; this.next = this.child = null; } } // Adds a sibling to a list with starting with nfunction addSibling(n,data){ if (n == null) return null; while (n.next != null) n = n.next; return (n.next = new Node(data));} // Add child Node to a Nodefunction addChild(n,data){ if (n == null) return null; // Check if child list is not empty. if (n.child != null) return addSibling(n.child, data); else return (n.child = new Node(data));} // Traverses tree in level orderfunction traverseTree(root){ // Corner cases if (root == null) return; document.write(root.data+ " "); if (root.child == null) return; // Create a queue and enqueue root let q = []; let curr = root.child; q.push(curr); while (q.length!=0) { // Take out an item from the queue curr = q[0]; q.shift(); // Print next level of taken out item and enqueue // next level's children while (curr != null) { document.write(curr.data + " "); if (curr.child != null) { q.push(curr.child); } curr = curr.next; } }} // Driver codelet root = new Node(10);let n1 = addChild(root, 2);let n2 = addChild(root, 3);let n3 = addChild(root, 4);let n4 = addChild(n3, 6);let n5 = addChild(root, 5);let n6 = addChild(n5, 7);let n7 = addChild(n5, 8);let n8 = addChild(n5, 9);traverseTree(root); // This code is contributed by unknown2108 </script>
10 2 3 4 5 6 7 8 9
This article is contributed by SAKSHI TIWARI. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
MvssTeja
shrikanth13
PranchalKatiyar
Sheenam Yadav
mohit kumar 29
aashish1995
Rajput-Ji
patel2127
unknown2108
surinderdawra388
n-ary-tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Decision Tree
Binary Tree | Set 2 (Properties)
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Expression Tree
Binary Tree (Array implementation)
Deletion in a Binary Tree
BFS vs DFS for Binary Tree
Relationship between number of nodes and height of binary tree | [
{
"code": null,
"e": 24665,
"s": 24637,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 25151,
"s": 24665,
"text": "Left-Child Right-Sibling Representation is a different representation of an n-ary tree where instead of holding a reference to each and every child node, a node holds just two references, first a reference to its first child, and the other to its immediate next sibling. This new transformation not only removes the need for advanced knowledge of the number of children a node has but also limits the number of references to a maximum of two, thereby making it so much easier to code. "
},
{
"code": null,
"e": 25261,
"s": 25151,
"text": "At each node, link children of same parent from left to right.\nParent should be linked with only first child."
},
{
"code": null,
"e": 25272,
"s": 25261,
"text": "Examples: "
},
{
"code": null,
"e": 25397,
"s": 25272,
"text": "Left Child Right Sibling tree representation\n 10\n | \n 2 -> 3 -> 4 -> 5\n | | \n 6 7 -> 8 -> 9"
},
{
"code": null,
"e": 25460,
"s": 25397,
"text": "Prerequisite: Left-Child Right-Sibling Representation of Tree "
},
{
"code": null,
"e": 25490,
"s": 25460,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 25494,
"s": 25490,
"text": "C++"
},
{
"code": null,
"e": 25499,
"s": 25494,
"text": "Java"
},
{
"code": null,
"e": 25507,
"s": 25499,
"text": "Python3"
},
{
"code": null,
"e": 25510,
"s": 25507,
"text": "C#"
},
{
"code": null,
"e": 25521,
"s": 25510,
"text": "Javascript"
},
{
"code": "// C++ program to create a tree with left child// right sibling representation.#include<bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *next; struct Node *child;}; // Creating new NodeNode* newNode(int data){ Node *newNode = new Node; newNode->next = newNode->child = NULL; newNode->data = data; return newNode;} // Adds a sibling to a list with starting with nNode *addSibling(Node *n, int data){ if (n == NULL) return NULL; while (n->next) n = n->next; return (n->next = newNode(data));} // Add child Node to a NodeNode *addChild(Node * n, int data){ if (n == NULL) return NULL; // Check if child list is not empty. if (n->child) return addSibling(n->child, data); else return (n->child = newNode(data));} // Traverses tree in depth first ordervoid traverseTree(Node * root){ if (root == NULL) return; while (root) { cout << \" \" << root->data; if (root->child) traverseTree(root->child); root = root->next; }} //Driver code int main(){ /* Let us create below tree * 10 * / / \\ \\ * 2 3 4 5 * | / | \\ * 6 7 8 9 */ // Left child right sibling /* 10 * | * 2 -> 3 -> 4 -> 5 * | | * 6 7 -> 8 -> 9 */ Node *root = newNode(10); Node *n1 = addChild(root, 2); Node *n2 = addChild(root, 3); Node *n3 = addChild(root, 4); Node *n4 = addChild(n3, 6); Node *n5 = addChild(root, 5); Node *n6 = addChild(n5, 7); Node *n7 = addChild(n5, 8); Node *n8 = addChild(n5, 9); traverseTree(root); return 0;}",
"e": 27248,
"s": 25521,
"text": null
},
{
"code": "// Java program to create a tree with left child// right sibling representation. class GFG { static class NodeTemp { int data; NodeTemp next, child; public NodeTemp(int data) { this.data = data; next = child = null; } } // Adds a sibling to a list with starting with n static public NodeTemp addSibling(NodeTemp node, int data) { if(node == null) return null; while(node.next != null) node = node.next; return(node.next = new NodeTemp(data)); } // Add child Node to a Node static public NodeTemp addChild(NodeTemp node,int data) { if(node == null) return null; // Check if child is not empty. if(node.child != null) return(addSibling(node.child,data)); else return(node.child = new NodeTemp(data)); } // Traverses tree in depth first order static public void traverseTree(NodeTemp root) { if(root == null) return; while(root != null) { System.out.print(root.data + \" \"); if(root.child != null) traverseTree(root.child); root = root.next; } } // Driver code public static void main(String args[]) { /* Let us create below tree * 10 * / / \\ \\ * 2 3 4 5 * | / | \\ * 6 7 8 9 */ // Left child right sibling /* 10 * | * 2 -> 3 -> 4 -> 5 * | | * 6 7 -> 8 -> 9 */ NodeTemp root = new NodeTemp(10); NodeTemp n1 = addChild(root,2); NodeTemp n2 = addChild(root,3); NodeTemp n3 = addChild(root,4); NodeTemp n4 = addChild(n3,6); NodeTemp n5 = addChild(root,5); NodeTemp n6 = addChild(n5,7); NodeTemp n7 = addChild(n5,8); NodeTemp n8 = addChild(n5,9); traverseTree(root); }} // This code is contributed by M.V.S.Surya Teja.",
"e": 29377,
"s": 27248,
"text": null
},
{
"code": "# Python3 program to create a tree with# left child right sibling representation. # Creating new Nodeclass newNode: def __init__(self, data): self.Next = self.child = None self.data = data # Adds a sibling to a list with# starting with ndef addSibling(n, data): if (n == None): return None while (n.Next): n = n.Next n.Next = newNode(data) return n.Next # Add child Node to a Nodedef addChild(n, data): if (n == None): return None # Check if child list is not empty. if (n.child): return addSibling(n.child, data) else: n.child = newNode(data) return n.child # Traverses tree in depth first orderdef traverseTree(root): if (root == None): return while (root): print(root.data, end = \" \") if (root.child): traverseTree(root.child) root = root.Next # Driver codeif __name__ == '__main__': # Let us create below tree # 10 # / / \\ \\ # 2 3 4 5 # | / | \\ # 6 7 8 9 # Left child right sibling # 10 # | # 2 -> 3 -> 4 -> 5 # | | # 6 7 -> 8 -> 9 root = newNode(10) n1 = addChild(root, 2) n2 = addChild(root, 3) n3 = addChild(root, 4) n4 = addChild(n3, 6) n5 = addChild(root, 5) n6 = addChild(n5, 7) n7 = addChild(n5, 8) n8 = addChild(n5, 9) traverseTree(root) # This code is contributed by pranchalK",
"e": 30838,
"s": 29377,
"text": null
},
{
"code": "// C# program to create a tree with left// child right sibling representation.using System; class GFG{public class NodeTemp{ public int data; public NodeTemp next, child; public NodeTemp(int data) { this.data = data; next = child = null; }} // Adds a sibling to a list with// starting with npublic static NodeTemp addSibling(NodeTemp node, int data){ if (node == null) { return null; } while (node.next != null) { node = node.next; } return (node.next = new NodeTemp(data));} // Add child Node to a Nodepublic static NodeTemp addChild(NodeTemp node, int data){ if (node == null) { return null; } // Check if child is not empty. if (node.child != null) { return (addSibling(node.child,data)); } else { return (node.child = new NodeTemp(data)); }} // Traverses tree in depth first orderpublic static void traverseTree(NodeTemp root){ if (root == null) { return; } while (root != null) { Console.Write(root.data + \" \"); if (root.child != null) { traverseTree(root.child); } root = root.next; }} // Driver codepublic static void Main(string[] args){ /* Let us create below tree * 10 * / / \\ \\ * 2 3 4 5 * | / | \\ * 6 7 8 9 */ // Left child right sibling /* 10 * | * 2 -> 3 -> 4 -> 5 * | | * 6 7 -> 8 -> 9 */ NodeTemp root = new NodeTemp(10); NodeTemp n1 = addChild(root, 2); NodeTemp n2 = addChild(root, 3); NodeTemp n3 = addChild(root, 4); NodeTemp n4 = addChild(n3, 6); NodeTemp n5 = addChild(root, 5); NodeTemp n6 = addChild(n5, 7); NodeTemp n7 = addChild(n5, 8); NodeTemp n8 = addChild(n5, 9); traverseTree(root);}} // This code is contributed by Shrikant13",
"e": 32781,
"s": 30838,
"text": null
},
{
"code": "<script> // Javascript program to create a tree with left child// right sibling representation. class NodeTemp { constructor(data) { this.data=data; this.next = this.child = null; } } // Adds a sibling to a list with starting with n function addSibling(node,data) { if(node == null) return null; while(node.next != null) node = node.next; return(node.next = new NodeTemp(data)); } // Add child Node to a Node function addChild(node,data) { if(node == null) return null; // Check if child is not empty. if(node.child != null) return(addSibling(node.child,data)); else return(node.child = new NodeTemp(data)); } // Traverses tree in depth first order function traverseTree(root) { if(root == null) return; while(root != null) { document.write(root.data + \" \"); if(root.child != null) traverseTree(root.child); root = root.next; } } // Driver code /* Let us create below tree * 10 * / / \\ \\ * 2 3 4 5 * | / | \\ * 6 7 8 9 */ // Left child right sibling /* 10 * | * 2 -> 3 -> 4 -> 5 * | | * 6 7 -> 8 -> 9 */ let root = new NodeTemp(10); let n1 = addChild(root,2); let n2 = addChild(root,3); let n3 = addChild(root,4); let n4 = addChild(n3,6); let n5 = addChild(root,5); let n6 = addChild(n5,7); let n7 = addChild(n5,8); let n8 = addChild(n5,9); traverseTree(root); // This code is contributed by patel2127 </script>",
"e": 34703,
"s": 32781,
"text": null
},
{
"code": null,
"e": 34722,
"s": 34703,
"text": "10 2 3 4 6 5 7 8 9"
},
{
"code": null,
"e": 34858,
"s": 34724,
"text": "Level Order Traversal: The above code talks about depth-first traversal. We can also do level order traversal of such representation."
},
{
"code": null,
"e": 34862,
"s": 34858,
"text": "C++"
},
{
"code": null,
"e": 34867,
"s": 34862,
"text": "Java"
},
{
"code": null,
"e": 34875,
"s": 34867,
"text": "Python3"
},
{
"code": null,
"e": 34878,
"s": 34875,
"text": "C#"
},
{
"code": null,
"e": 34889,
"s": 34878,
"text": "Javascript"
},
{
"code": "// C++ program to create a tree with left child// right sibling representation.#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next; struct Node* child;}; // Creating new NodeNode* newNode(int data){ Node* newNode = new Node; newNode->next = newNode->child = NULL; newNode->data = data; return newNode;} // Adds a sibling to a list with starting with nNode* addSibling(Node* n, int data){ if (n == NULL) return NULL; while (n->next) n = n->next; return (n->next = newNode(data));} // Add child Node to a NodeNode* addChild(Node* n, int data){ if (n == NULL) return NULL; // Check if child list is not empty. if (n->child) return addSibling(n->child, data); else return (n->child = newNode(data));} // Traverses tree in level ordervoid traverseTree(Node* root){ // Corner cases if (root == NULL) return; cout << root->data << \" \"; if (root->child == NULL) return; // Create a queue and enqueue root queue<Node*> q; Node* curr = root->child; q.push(curr); while (!q.empty()) { // Take out an item from the queue curr = q.front(); q.pop(); // Print next level of taken out item and enqueue // next level's children while (curr != NULL) { cout << curr->data << \" \"; if (curr->child != NULL) { q.push(curr->child); } curr = curr->next; } }} // Driver codeint main(){ Node* root = newNode(10); Node* n1 = addChild(root, 2); Node* n2 = addChild(root, 3); Node* n3 = addChild(root, 4); Node* n4 = addChild(n3, 6); Node* n5 = addChild(root, 5); Node* n6 = addChild(n5, 7); Node* n7 = addChild(n5, 8); Node* n8 = addChild(n5, 9); traverseTree(root); return 0;}",
"e": 36745,
"s": 34889,
"text": null
},
{
"code": "// Java program to create a tree with left child// right sibling representation.import java.util.*;class GFG{ static class Node { int data; Node next; Node child; }; // Creating new Node static Node newNode(int data) { Node newNode = new Node(); newNode.next = newNode.child = null; newNode.data = data; return newNode; } // Adds a sibling to a list with starting with n static Node addSibling(Node n, int data) { if (n == null) return null; while (n.next != null) n = n.next; return (n.next = newNode(data)); } // Add child Node to a Node static Node addChild(Node n, int data) { if (n == null) return null; // Check if child list is not empty. if (n.child != null) return addSibling(n.child, data); else return (n.child = newNode(data)); } // Traverses tree in level order static void traverseTree(Node root) { // Corner cases if (root == null) return; System.out.print(root.data+ \" \"); if (root.child == null) return; // Create a queue and enqueue root Queue<Node> q = new LinkedList<>(); Node curr = root.child; q.add(curr); while (!q.isEmpty()) { // Take out an item from the queue curr = q.peek(); q.remove(); // Print next level of taken out item and enqueue // next level's children while (curr != null) { System.out.print(curr.data + \" \"); if (curr.child != null) { q.add(curr.child); } curr = curr.next; } } } // Driver code public static void main(String[] args) { Node root = newNode(10); Node n1 = addChild(root, 2); Node n2 = addChild(root, 3); Node n3 = addChild(root, 4); Node n4 = addChild(n3, 6); Node n5 = addChild(root, 5); Node n6 = addChild(n5, 7); Node n7 = addChild(n5, 8); Node n8 = addChild(n5, 9); traverseTree(root); }} // This code is contributed by aashish1995",
"e": 38693,
"s": 36745,
"text": null
},
{
"code": "# Python3 program to create a tree with# left child right sibling representationfrom collections import deque class Node: def __init__(self, x): self.data = x self.next = None self.child = None # Adds a sibling to a list with# starting with ndef addSibling(n, data): if (n == None): return None while (n.next): n = n.next n.next = Node(data) return n # Add child Node to a Nodedef addChild(n, data): if (n == None): return None # Check if child list is not empty if (n.child): return addSibling(n.child, data) else: n.child = Node(data) return n # Traverses tree in level orderdef traverseTree(root): # Corner cases if (root == None): return print(root.data, end = \" \") if (root.child == None): return # Create a queue and enqueue root q = deque() curr = root.child q.append(curr) while (len(q) > 0): # Take out an item from the queue curr = q.popleft() #q.pop() # Print next level of taken out # item and enqueue next level's children while (curr != None): print(curr.data, end = \" \") if (curr.child != None): q.append(curr.child) curr = curr.next # Driver codeif __name__ == '__main__': root = Node(10) n1 = addChild(root, 2) n2 = addChild(root, 3) n3 = addChild(root, 4) n4 = addChild(n3, 6) n5 = addChild(root, 5) n6 = addChild(n5, 7) n7 = addChild(n5, 8) n8 = addChild(n5, 9) traverseTree(root) # This code is contributed by mohit kumar 29",
"e": 40379,
"s": 38693,
"text": null
},
{
"code": "// C# program to create a tree with left child// right sibling representation.using System;using System.Collections.Generic;class GFG{ public class Node { public int data; public Node next; public Node child; }; // Creating new Node static Node newNode(int data) { Node newNode = new Node(); newNode.next = newNode.child = null; newNode.data = data; return newNode; } // Adds a sibling to a list with starting with n static Node addSibling(Node n, int data) { if (n == null) return null; while (n.next != null) n = n.next; return (n.next = newNode(data)); } // Add child Node to a Node static Node addChild(Node n, int data) { if (n == null) return null; // Check if child list is not empty. if (n.child != null) return addSibling(n.child, data); else return (n.child = newNode(data)); } // Traverses tree in level order static void traverseTree(Node root) { // Corner cases if (root == null) return; Console.Write(root.data + \" \"); if (root.child == null) return; // Create a queue and enqueue root Queue<Node> q = new Queue<Node>(); Node curr = root.child; q.Enqueue(curr); while (q.Count != 0) { // Take out an item from the queue curr = q.Peek(); q.Dequeue(); // Print next level of taken out item and enqueue // next level's children while (curr != null) { Console.Write(curr.data + \" \"); if (curr.child != null) { q.Enqueue(curr.child); } curr = curr.next; } } } // Driver code public static void Main(String[] args) { Node root = newNode(10); Node n1 = addChild(root, 2); Node n2 = addChild(root, 3); Node n3 = addChild(root, 4); Node n4 = addChild(n3, 6); Node n5 = addChild(root, 5); Node n6 = addChild(n5, 7); Node n7 = addChild(n5, 8); Node n8 = addChild(n5, 9); traverseTree(root); }} // This code is contributed by Rajput-Ji",
"e": 42408,
"s": 40379,
"text": null
},
{
"code": "<script> // JavaScript program to create a// tree with left child// right sibling representation. class Node { // Creating new Node constructor(data) { this.data=data; this.next = this.child = null; } } // Adds a sibling to a list with starting with nfunction addSibling(n,data){ if (n == null) return null; while (n.next != null) n = n.next; return (n.next = new Node(data));} // Add child Node to a Nodefunction addChild(n,data){ if (n == null) return null; // Check if child list is not empty. if (n.child != null) return addSibling(n.child, data); else return (n.child = new Node(data));} // Traverses tree in level orderfunction traverseTree(root){ // Corner cases if (root == null) return; document.write(root.data+ \" \"); if (root.child == null) return; // Create a queue and enqueue root let q = []; let curr = root.child; q.push(curr); while (q.length!=0) { // Take out an item from the queue curr = q[0]; q.shift(); // Print next level of taken out item and enqueue // next level's children while (curr != null) { document.write(curr.data + \" \"); if (curr.child != null) { q.push(curr.child); } curr = curr.next; } }} // Driver codelet root = new Node(10);let n1 = addChild(root, 2);let n2 = addChild(root, 3);let n3 = addChild(root, 4);let n4 = addChild(n3, 6);let n5 = addChild(root, 5);let n6 = addChild(n5, 7);let n7 = addChild(n5, 8);let n8 = addChild(n5, 9);traverseTree(root); // This code is contributed by unknown2108 </script>",
"e": 44098,
"s": 42408,
"text": null
},
{
"code": null,
"e": 44117,
"s": 44098,
"text": "10 2 3 4 5 6 7 8 9"
},
{
"code": null,
"e": 44558,
"s": 44119,
"text": "This article is contributed by SAKSHI TIWARI. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 44567,
"s": 44558,
"text": "MvssTeja"
},
{
"code": null,
"e": 44579,
"s": 44567,
"text": "shrikanth13"
},
{
"code": null,
"e": 44595,
"s": 44579,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 44609,
"s": 44595,
"text": "Sheenam Yadav"
},
{
"code": null,
"e": 44624,
"s": 44609,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 44636,
"s": 44624,
"text": "aashish1995"
},
{
"code": null,
"e": 44646,
"s": 44636,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 44656,
"s": 44646,
"text": "patel2127"
},
{
"code": null,
"e": 44668,
"s": 44656,
"text": "unknown2108"
},
{
"code": null,
"e": 44685,
"s": 44668,
"text": "surinderdawra388"
},
{
"code": null,
"e": 44696,
"s": 44685,
"text": "n-ary-tree"
},
{
"code": null,
"e": 44701,
"s": 44696,
"text": "Tree"
},
{
"code": null,
"e": 44706,
"s": 44701,
"text": "Tree"
},
{
"code": null,
"e": 44804,
"s": 44706,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44813,
"s": 44804,
"text": "Comments"
},
{
"code": null,
"e": 44826,
"s": 44813,
"text": "Old Comments"
},
{
"code": null,
"e": 44840,
"s": 44826,
"text": "Decision Tree"
},
{
"code": null,
"e": 44873,
"s": 44840,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 44956,
"s": 44873,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 44992,
"s": 44956,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 45040,
"s": 44992,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 45056,
"s": 45040,
"text": "Expression Tree"
},
{
"code": null,
"e": 45091,
"s": 45056,
"text": "Binary Tree (Array implementation)"
},
{
"code": null,
"e": 45117,
"s": 45091,
"text": "Deletion in a Binary Tree"
},
{
"code": null,
"e": 45144,
"s": 45117,
"text": "BFS vs DFS for Binary Tree"
}
] |
Understanding and using Python classes | by Valentina Alto | Towards Data Science | Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. The latter is the formal definition given by the official website python.org. Let’s break it and try to understand it:
interpreted: differently from compiled programming languages (where the source code has to be converted into machine-readable code), interpreted languages are not directly executed by the target machine. Instead, they are read and executed by some other computer program called interpreter;
object-oriented: it means that python, like any other Object-Oriented Programming (OOP) languages, is organized around objects. Everything in python (lists, dictionaries, classes and so forth) is an object;
high-level: it means that the syntax of the code is easier to interpret by humans. Namely, if you have to display something on the screen, the built-in function is called print;
dynamic semantics: dynamics objects are instances of values contained into constructs in the code, and they exist at run-time level. Furthermore, we can assign to one object multiple values, since it will update itself, differently from a static semantic language. Namely, if we set a=2 and then a=’hello’, the string value will substitute the integer one as soon as the line is executed.
In this article, I want to dive deeper into the concept of classes. Classes are a particular type of object. More specifically, they are object-constructors, which are able to build both data representation and the procedure we can use to interact with that object (hence methods, functions and so forth).
To create a class in Python, we need to give that class a name and some attributes. So let’s start with the following example:
class Actor: def __init__(self, name, surname, age, years_on_stage): self.name=name self.surname=surname self.age=age self.years_on_stage=years_on_stage
So we created a class called Actor, which defines some features (name, surname, age, years on stage). There are two elements to focus on:
__init__(): it is a special method used to initialize data attributes. We can look at it as an initializer.
self: it is a standard notation which is used to point the parameters.
Now, we can use our class and create an object of class Actor:
mario=Actor( 'Mario', 'Rossi', 40, 13)
Now, we can access all the attribute of mario (which we defined in __init__()):
mario.name"mario"mario.age40
Now, imagine we want to know specific information about mario which is not stored among its attributes. More specifically, we want to know the year of debut, but we are only provided with the years on stage. So what we would like to have is a function which subtracts from the current date the years on stage, so that it returns the year of debut.
We can do so directly into our class Actor:
class Actor: def __init__(self, name, surname, age, years_on_stage): self.name=name self.surname=surname self.age=age self.years_on_stage=years_on_stage def year_of_debut(self, current_year): self.current_year=current_year year_of_debut=self.current_year-self.years_on_stage return year_of_debut
Now let’s test it on our object mario:
mario.year_of_debut(2019)2006
The last thing I’m going to talk about is a very interesting and useful property of python classes, called class inheritance. The idea is that, if you have to create a class (called child class) which is a subset of the one you’ve already created (called parent class), you can easily import its attributes to the child class.
Let’s see how to do that with the following example. Let’s say you want to create a child class called Comedian, which will have some attributes in common with the parent class Actor:
class Comedian(Actor): def __init__(self, n_shows, field, shows_schedule, name, surname, age, years_on_stage): self.n_shows=n_shows self.field=field self.shows_schedule=shows_schedule super().__init__(name,surname,age,years_on_stage)
As you can see, instead of specifying self.attribute=attribute for name, surname, age and years_on_stage, we directly inherited them by the parent class through the function super(). Now, we can create an object of our child class and access its attributes exactly as in the parent class example:
a_comedian=Comedian( 21, 'politics', 'late night', 'amelia', 'smith', '33', '10')a_comedian.name'amelia'a_comedian.field'politics'
The advantages of Python classes are noticeable. Particularly, they make Python language extremely customizable: not only you can create personalized functions (besides those which are built-in), but also can you create object-generators which are able to perfectly satisfy your needs. | [
{
"code": null,
"e": 389,
"s": 171,
"text": "Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. The latter is the formal definition given by the official website python.org. Let’s break it and try to understand it:"
},
{
"code": null,
"e": 680,
"s": 389,
"text": "interpreted: differently from compiled programming languages (where the source code has to be converted into machine-readable code), interpreted languages are not directly executed by the target machine. Instead, they are read and executed by some other computer program called interpreter;"
},
{
"code": null,
"e": 887,
"s": 680,
"text": "object-oriented: it means that python, like any other Object-Oriented Programming (OOP) languages, is organized around objects. Everything in python (lists, dictionaries, classes and so forth) is an object;"
},
{
"code": null,
"e": 1065,
"s": 887,
"text": "high-level: it means that the syntax of the code is easier to interpret by humans. Namely, if you have to display something on the screen, the built-in function is called print;"
},
{
"code": null,
"e": 1454,
"s": 1065,
"text": "dynamic semantics: dynamics objects are instances of values contained into constructs in the code, and they exist at run-time level. Furthermore, we can assign to one object multiple values, since it will update itself, differently from a static semantic language. Namely, if we set a=2 and then a=’hello’, the string value will substitute the integer one as soon as the line is executed."
},
{
"code": null,
"e": 1760,
"s": 1454,
"text": "In this article, I want to dive deeper into the concept of classes. Classes are a particular type of object. More specifically, they are object-constructors, which are able to build both data representation and the procedure we can use to interact with that object (hence methods, functions and so forth)."
},
{
"code": null,
"e": 1887,
"s": 1760,
"text": "To create a class in Python, we need to give that class a name and some attributes. So let’s start with the following example:"
},
{
"code": null,
"e": 2071,
"s": 1887,
"text": "class Actor: def __init__(self, name, surname, age, years_on_stage): self.name=name self.surname=surname self.age=age self.years_on_stage=years_on_stage"
},
{
"code": null,
"e": 2209,
"s": 2071,
"text": "So we created a class called Actor, which defines some features (name, surname, age, years on stage). There are two elements to focus on:"
},
{
"code": null,
"e": 2317,
"s": 2209,
"text": "__init__(): it is a special method used to initialize data attributes. We can look at it as an initializer."
},
{
"code": null,
"e": 2388,
"s": 2317,
"text": "self: it is a standard notation which is used to point the parameters."
},
{
"code": null,
"e": 2451,
"s": 2388,
"text": "Now, we can use our class and create an object of class Actor:"
},
{
"code": null,
"e": 2502,
"s": 2451,
"text": "mario=Actor( 'Mario', 'Rossi', 40, 13)"
},
{
"code": null,
"e": 2582,
"s": 2502,
"text": "Now, we can access all the attribute of mario (which we defined in __init__()):"
},
{
"code": null,
"e": 2611,
"s": 2582,
"text": "mario.name\"mario\"mario.age40"
},
{
"code": null,
"e": 2959,
"s": 2611,
"text": "Now, imagine we want to know specific information about mario which is not stored among its attributes. More specifically, we want to know the year of debut, but we are only provided with the years on stage. So what we would like to have is a function which subtracts from the current date the years on stage, so that it returns the year of debut."
},
{
"code": null,
"e": 3003,
"s": 2959,
"text": "We can do so directly into our class Actor:"
},
{
"code": null,
"e": 3354,
"s": 3003,
"text": "class Actor: def __init__(self, name, surname, age, years_on_stage): self.name=name self.surname=surname self.age=age self.years_on_stage=years_on_stage def year_of_debut(self, current_year): self.current_year=current_year year_of_debut=self.current_year-self.years_on_stage return year_of_debut"
},
{
"code": null,
"e": 3393,
"s": 3354,
"text": "Now let’s test it on our object mario:"
},
{
"code": null,
"e": 3423,
"s": 3393,
"text": "mario.year_of_debut(2019)2006"
},
{
"code": null,
"e": 3750,
"s": 3423,
"text": "The last thing I’m going to talk about is a very interesting and useful property of python classes, called class inheritance. The idea is that, if you have to create a class (called child class) which is a subset of the one you’ve already created (called parent class), you can easily import its attributes to the child class."
},
{
"code": null,
"e": 3934,
"s": 3750,
"text": "Let’s see how to do that with the following example. Let’s say you want to create a child class called Comedian, which will have some attributes in common with the parent class Actor:"
},
{
"code": null,
"e": 4199,
"s": 3934,
"text": "class Comedian(Actor): def __init__(self, n_shows, field, shows_schedule, name, surname, age, years_on_stage): self.n_shows=n_shows self.field=field self.shows_schedule=shows_schedule super().__init__(name,surname,age,years_on_stage)"
},
{
"code": null,
"e": 4496,
"s": 4199,
"text": "As you can see, instead of specifying self.attribute=attribute for name, surname, age and years_on_stage, we directly inherited them by the parent class through the function super(). Now, we can create an object of our child class and access its attributes exactly as in the parent class example:"
},
{
"code": null,
"e": 4695,
"s": 4496,
"text": "a_comedian=Comedian( 21, 'politics', 'late night', 'amelia', 'smith', '33', '10')a_comedian.name'amelia'a_comedian.field'politics'"
}
] |
Winning the Kaggle Google Brain — Ventilator Pressure Prediction | by Gilles Vandewiele | Towards Data Science | On the 4th of November, we managed to came out on top out of 2650 teams in the Google Brain — Ventilator Pressure Prediction, organized on Kaggle. In this blog post I would like to take you through the journey that bagged us the victory. A more summarized version of this write-up can be found on the Kaggle forum and we have published code for our LSTM + CNN Transformer model and PID matching.
I was a little bit burnt down after finishing my PhD and after an unpleasant but short work experience. As a result, I was taking a bit of a hiatus from Kaggle in 2021, as you can see from my activity log. I participated a little bit in the “Rock, Paper, Scissors contest” and had a go at the “Indoor Location & Navigation challenge”.
On the 23rd of September, Yves and I received an email from Kha. He spotted an interesting time series competition that was only lasting for 1 month on Kaggle. The competition appealed to me as I am quite familiar with time series data, and also a big fan of shorter competitions. Moreover, I know that when Kha, Yves and I team up, that good things often follow! I replied to Kha that I would be interested in joining, but had some things to take care of in real life first before I could really dive into it. One of those things that had to be done was preparing & giving a presentation on the third place solution Kha, Yves and I obtained in 2020 in the “Liverpool Ion Switching” competition. Kha and Yves started working on the problem and making some good progress. Some time later, on the 6th of October, I joined them.
The goal of this competition is to predict the pressure within a mechanical lung on any given time step, based on how much the inspiratory solenoid valve is opened (u_in; a value between 0 and 100). We were given roughly 75000 training breaths and 50000 test breaths. Every breath consisted of an inspiratory phase and an expiratory phase, which was indicated by the provided u_out. Our submissions were only scored on inspiratory phase (so where u_out was equal to 0). Moreover, the breaths were recorded in a mechanical lung with different resistance and capacity properties, which were encoded in provided R and C variables.
From the public notebooks that were published in this competition, it was clear that LSTMs or any kind of temporal deep learning models would reign supreme. All three of us quickly adding features or making small modifications to these pipelines, but to no avail... It was clear that deep learning isn’t our forté. We then had a switch in mindset: “instead of trying to create one model, fitted on all train data, that is then used to make predictions for all test data, can’t we just focus on breaths individually instead and see whether we can model those to find patterns?”
Yves, who has a background in physics, looked at PID controllers and quickly found a nice and simple post-processing trick that was able to give us a +0.004 boost on the LB, which is quite significant. Thanks to this post-processing trick, we were able to climb the leaderboard with a blend of slightly modified public notebooks, landing us a spot right out of the gold zone. The post-processing trick of Yves is rather simple to explain (but not that easy to find) and is based on the theory of PID controllers.
We could come up with a very simple formula: pressure = kt — (u_in/kp) . With kt and kp parameters of the algorithm that had to be tuned, u_in the input data and pressure the output data that we want to predict. The grid to search these parameters in was mentioned in a paper written by the organizers. But this grid can easily be discovered without the paper by just applying linear regression to each breath in the training data (where we have u_in and pressure).
Now the question is, how do we know how good a certain set of parameters is for test breaths, as we do not have pressures to calculate an error. For this, we could make use of the discrete nature of the pressures. There are only 950 unique pressure values, with equal distances in between them. As such, if we fill in two candidate parameters kt and kp and the calculated pressure values align perfectly with these 950 unique pressure values, we have a match. This matching worked for roughly 2.5% of the data.
KP_GRID = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]KT_GRID = [10, 15, 20, 25, 30, 35]def match_breath(breath): u_in = breath['u_in'].values inspiratory_len = np.sum(1 - breath['u_out']) u_in = u_in[1:inspiratory_len] breath_mask = (u_in > 0) & (u_in < 100) if np.sum(breath_mask) < 2: return None, None, None, None for kt in KT_GRID: for kp in KP_GRID: preds = (kt - u_in / kp) preds_round = (preds-MIN_PRESSURE)/DIFF_PRESSURE tune_error = np.round(preds_round[breath_mask]) - preds_round[breath_mask] if np.sum(np.abs(tune_error)) < 1e-6: return preds, kt, kp, breath_mask return None, None, None, None
After discovering the post-processing trick, we were not able to make any more significant improvements. We slowly saw our rank dropping on the LB, and it was clear that we would needed someone with more deep learning experience in order to obtain a good result in this competition. We messaged Shujun who was just below the gold zone at that time. I knew that Shujun is extremely strong in deep learning as he got a solo gold medal with a unique and strong architecture in the “OpenVaccine — Covid mRNA” competition in which I participated too. Boy did he NOT disappoint.
Shujun’s deep learning architecture was a combination of LSTM cells, 1D convolutions, and transformers. LSTMs were necessary because of target pressure’s heavy dependence on previous time points. Convolutions in conjunction with transformers is a good combination to model global dependencies while making up for transformers’ inability to capture local interactions. The network was rather deep, and we ran into some gradient issues. Therefore, a new module called ResidualLSTM, which adds a Feedforward Network (FFN) and connects the input to the LSTM with the output after FFN with a residual connection, was created. The model works on the raw data in addition with a few lag and difference features, a cumulative sum of the u_in, and one-hot-encoded R & C features.
We ensembled our current blend with Shujun’s blend of different runs of his model and applied our PP trick. Boom, we were in the gold!
We tried suggesting some ideas to Shujun to implement in his pipeline, and also tried adding some features so the pipeline (as his pipeline was leveraging features). But again, we were not successful.
A few days later, we felt that we needed another unique deep learning pipeline for our blend. This is where Riccardo enters the story! At the time when we messaged him, Riccardo was only a few spots below us. He had an LSTM architecture up and running that converged on just the raw data. No feature engineering, no fancy stuff, just raw data and a lot of epochs. The trick was to have a good learning rate scheduler. We opted for a ReduceLROnPlateau with a patience of 30 epochs. This was in contrast with the fast annealing schedulers typically used within the public notebooks, which were susceptible to overfitting. This can be seen when we compare our validation loss curves to those of the public notebooks, as displayed below. Here the red (stakes) curve corresponds to the public notebooks and quickly overfits.
This approach even scored better than the LSTM + 1D CNN Transformer Encoder. The blend of these pipelines gave us the fourth spot on the leaderboard. We decided to change our ambitions from a gold medal to winning money.
Again, all of us focused on improving the two pipelines we had up and running. Making slight modifications to both pipelines or adding features to the transformer pipeline. Only extremely marginal improvements were made, and the gap with the competitors ahead of us was too big. Surely, there was something hidden in the data that they had found and we did not yet...
On the 26th of October, my birthday, I decided to learn some more about PID (Proportional - Integral - Derivative) controllers, as those were a core concept in the organizers their paper as well. Moreover, our post-processing trick came from Yves looking into these PID controllers.
I played around with the simple-pid package in Python as this package already implements the PID formulas. I was able to reproduce our post-processing trick with this package as well. However, for most breaths I was not able to find a match. That was until I decided to play around with the code and the integral term specifically. There are multiple ways to calculate the Integral term of PID controllers, and the package only included the vanilla implementation. I decided to plug in some other alternatives and suddenly, I had a breakthrough... WHAT A BIRTHDAY GIFT! The following code snippet (based on the simple-pid package) was able to model pressure->u_in perfectly for some breaths:
Here is the code snippet that was able to perfectly model pressure to u_in for some of the breaths:
def generate_u_in(pressure, time_step, kp, ki, kt, integral=0): dt = np.diff(time_step, prepend=[0]) preds = [] for j in range(32): error = kt - pressure[j] integral += (error - integral) * (dt[j] / (dt[j] + 0.5)) preds.append(kp * error + ki * integral) return preds
I thought we had a new nice post-processing trick on our hands, and sent this information to Yves. Yves made something much much bigger out of it. He came up with some code that was able to match the pressures perfectly.
We can write the “vanilla” equation of a PID controller (that corresponds to the generate_u_in snippet I provided):
With epsilon equal to target — pressure where target represents the ideal pressure that is set by the user. Now gamma, which is the weight of the derivative term, was always set to zero by the organizers. So we only had to focus on the first (proportional) and second (integral) term. Our previously discussed post-processing technique actually corresponds to this equation with beta set to 0. Let’s rewrite the second integral term for ease of notation. Moreover, the integral term was implemented by a weight decay as follows:
With delta_t the difference in time between timestep t and t-1 and tau a constant, which was equal to 0.5 for this data. We can isolate the integral term from the PID equation, in order to calculate it for any point in time. This avoids having to propagate this across the entire signal:
With these equations, we are all set for our matching algorithm. Our matching algorithm to fill in the pressure for a given breath at timestep t, for a given configuration of parameters (target, alpha and beta or referred to as kt, kp and ki respectively in the remainder of this post) goes as follows:
Take two random pressure values P0 and P1 . There are 950 possible pressure values and thus 950*950 possible combinations.Calculate I0 = (u_in[t - 1] - kp * (kt - P0))/kiCalculate I1 = I0 + (kt - P1 - I0) * (dt / (dt + 0.5))If kp * (kt - P1) + ki * I1 == u_in[t] we have a match and we can fill in P1 for pressure[t]
Take two random pressure values P0 and P1 . There are 950 possible pressure values and thus 950*950 possible combinations.
Calculate I0 = (u_in[t - 1] - kp * (kt - P0))/ki
Calculate I1 = I0 + (kt - P1 - I0) * (dt / (dt + 0.5))
If kp * (kt - P1) + ki * I1 == u_in[t] we have a match and we can fill in P1 for pressure[t]
In code:
P_RANGE = np.arange( MIN_PRESSURE, MAX_PRESSURE + DIFF_PRESSURE, DIFF_PRESSURE)for P0 in P_RANGE: for P1 in P_RANGE: I0 = (u_in[t - 1] - kp * (kt - P0))/ki I1 = I0 + (kt - P1 - I0) * (dt / (dt + 0.5)) u_in_hat = kp * (kt - P1) + ki * I1 if abs(u_in_hat - u_in[t]) < 1e-8: print(P0, P1, pressure[t-1:t+1])
However, this code is rather slow. This is because 950*950 combinations need to be tried for every possible parameter combination. kp and ki have 20 possible values and kt has 6 possible values, in total we thus have 950*950*20*20*6 possible combinations. However, for a fixed P0 we notice that abs(u_in_hat — u_in[t]) grows linearly across the for-loop. As such, we can extrapolate this with just 2 measurements. If the intersection of this extrapolated function with the x-axis occurs at an integer (or close to an integer), our if-condition would have evaluated to True in an iteration of our inner for-loop.
This observation allows us to speed up the code with a factor of 950.
for P0 in P_RANGE: I0 = (u_in[t - 1] - kp * (kt - P0))/ki # Calculate 2 points for P1 so we can get the slope I11 = I0 + (kt - MIN_PRESSURE - I0) * (dt / (dt + 0.5)) u_in_hat1 = kp * (kt - MIN_PRESSURE) + ki * I11 I12 = I0 + (kt - MIN_PRESSURE2 - I0) * (dt / (dt + 0.5)) u_in_hat2 = kp * (kt - MIN_PRESSURE2) + ki * I12 slope = u_in_hat2 - u_in_hat1 x_intersect = (u_in[t] - u_in_hat2) / slope if abs(np.round(x_intersect) - x_intersect) < 1e-8: print(P0, MIN_PRESSURE + (x_intersect + 1) * DIFF_PRESSURE)
With the code above, we were able to match a lot of pressures. But many of them still remained unmatched. In the paper of the organizers, it was explained that artificial noise was added to the u_in data. We set out on an endeavour to remove this noise. Let us first look at the output of the current version of a matching algorithm on a particular breath (train breath id 17)
As one notices, the first value of the u_in and some values in the middle were not fully matched. The first values of all breaths are noisy and are not matchable, but the points in the middle should be matchable... Let us start from index 5 and call our generate_u_in code on the provided pressures to generate “ideal u_in values” and subtract this from the u_in we are provided.
kp, ki, kt = 1., 3., 30I5 = (u_in[4] - kp * (kt - pressure[4]))/kiu_in_hat = generate_u_in(pressure[5:], timestep[4:], kp, ki, kt, integral=I5)noise = u_in[5:32] - u_in_hat[:-5]plt.plot(timestep[5:32], noise, '-o')plt.title('noise')plt.show()
The difference between the ideal u_in values and the provided u_in values form a nice triangle, except on the turning point / peak of the triangle. The key insight is that the slope of this noise ((np.diff(noise) / np.diff(timestep[5:32]))) will be equal for consecutive points on this triangle. We can also rewrite our integral calculation to work backwards.
Strapped with these two insights, we were able to match a lot more data:
Given our DL models and matching algorithm, our approach was rather simple:
Generate predictions with our two DL models. Train them in 10-fold cross validation at multiple seeds. This gives us multiple models with slight variations. Take the (weighted) median of these models as an ensembling technique as that is typically better than a mean when MAE is the metric.From these predictions, apply our matching algorithm. If we find a match, replace the prediction of the DL algorithm by the matcher. If there is not a match, keep the DL prediction.
Generate predictions with our two DL models. Train them in 10-fold cross validation at multiple seeds. This gives us multiple models with slight variations. Take the (weighted) median of these models as an ensembling technique as that is typically better than a mean when MAE is the metric.
From these predictions, apply our matching algorithm. If we find a match, replace the prediction of the DL algorithm by the matcher. If there is not a match, keep the DL prediction.
In total we were able to roughly match 66% of the data, which gave us a HUGE boost on the leaderboard.
This was my first victory on Kaggle. While I admit that the PID controller matching was a bit cheeky, I am still extremely proud of our result as only 2 teams out of 2650 were able to find this exploit. Moreover, we were the only team that was able to match the noise within the u_in data as well. I would like to thank my team mates zidmie, kha, shujun and B as without them this result would not have been possible!
In case you have any questions or something is unclear, feel free to leave some comments or contact me through some other medium (pun intended).
Organizers PaperKaggle Forum write-upPID Matching Code + Explanation (Kaggle)PID Matching Code + Explanation (Github)LSTM + CNN Transformer code (Kaggle)LSTM + CNN Transformer code (Github)LSTM on raw data code (Github)
Organizers Paper
Kaggle Forum write-up
PID Matching Code + Explanation (Kaggle)
PID Matching Code + Explanation (Github)
LSTM + CNN Transformer code (Kaggle)
LSTM + CNN Transformer code (Github)
LSTM on raw data code (Github) | [
{
"code": null,
"e": 568,
"s": 172,
"text": "On the 4th of November, we managed to came out on top out of 2650 teams in the Google Brain — Ventilator Pressure Prediction, organized on Kaggle. In this blog post I would like to take you through the journey that bagged us the victory. A more summarized version of this write-up can be found on the Kaggle forum and we have published code for our LSTM + CNN Transformer model and PID matching."
},
{
"code": null,
"e": 903,
"s": 568,
"text": "I was a little bit burnt down after finishing my PhD and after an unpleasant but short work experience. As a result, I was taking a bit of a hiatus from Kaggle in 2021, as you can see from my activity log. I participated a little bit in the “Rock, Paper, Scissors contest” and had a go at the “Indoor Location & Navigation challenge”."
},
{
"code": null,
"e": 1729,
"s": 903,
"text": "On the 23rd of September, Yves and I received an email from Kha. He spotted an interesting time series competition that was only lasting for 1 month on Kaggle. The competition appealed to me as I am quite familiar with time series data, and also a big fan of shorter competitions. Moreover, I know that when Kha, Yves and I team up, that good things often follow! I replied to Kha that I would be interested in joining, but had some things to take care of in real life first before I could really dive into it. One of those things that had to be done was preparing & giving a presentation on the third place solution Kha, Yves and I obtained in 2020 in the “Liverpool Ion Switching” competition. Kha and Yves started working on the problem and making some good progress. Some time later, on the 6th of October, I joined them."
},
{
"code": null,
"e": 2357,
"s": 1729,
"text": "The goal of this competition is to predict the pressure within a mechanical lung on any given time step, based on how much the inspiratory solenoid valve is opened (u_in; a value between 0 and 100). We were given roughly 75000 training breaths and 50000 test breaths. Every breath consisted of an inspiratory phase and an expiratory phase, which was indicated by the provided u_out. Our submissions were only scored on inspiratory phase (so where u_out was equal to 0). Moreover, the breaths were recorded in a mechanical lung with different resistance and capacity properties, which were encoded in provided R and C variables."
},
{
"code": null,
"e": 2935,
"s": 2357,
"text": "From the public notebooks that were published in this competition, it was clear that LSTMs or any kind of temporal deep learning models would reign supreme. All three of us quickly adding features or making small modifications to these pipelines, but to no avail... It was clear that deep learning isn’t our forté. We then had a switch in mindset: “instead of trying to create one model, fitted on all train data, that is then used to make predictions for all test data, can’t we just focus on breaths individually instead and see whether we can model those to find patterns?”"
},
{
"code": null,
"e": 3448,
"s": 2935,
"text": "Yves, who has a background in physics, looked at PID controllers and quickly found a nice and simple post-processing trick that was able to give us a +0.004 boost on the LB, which is quite significant. Thanks to this post-processing trick, we were able to climb the leaderboard with a blend of slightly modified public notebooks, landing us a spot right out of the gold zone. The post-processing trick of Yves is rather simple to explain (but not that easy to find) and is based on the theory of PID controllers."
},
{
"code": null,
"e": 3914,
"s": 3448,
"text": "We could come up with a very simple formula: pressure = kt — (u_in/kp) . With kt and kp parameters of the algorithm that had to be tuned, u_in the input data and pressure the output data that we want to predict. The grid to search these parameters in was mentioned in a paper written by the organizers. But this grid can easily be discovered without the paper by just applying linear regression to each breath in the training data (where we have u_in and pressure)."
},
{
"code": null,
"e": 4425,
"s": 3914,
"text": "Now the question is, how do we know how good a certain set of parameters is for test breaths, as we do not have pressures to calculate an error. For this, we could make use of the discrete nature of the pressures. There are only 950 unique pressure values, with equal distances in between them. As such, if we fill in two candidate parameters kt and kp and the calculated pressure values align perfectly with these 950 unique pressure values, we have a match. This matching worked for roughly 2.5% of the data."
},
{
"code": null,
"e": 5217,
"s": 4425,
"text": "KP_GRID = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]KT_GRID = [10, 15, 20, 25, 30, 35]def match_breath(breath): u_in = breath['u_in'].values inspiratory_len = np.sum(1 - breath['u_out']) u_in = u_in[1:inspiratory_len] breath_mask = (u_in > 0) & (u_in < 100) if np.sum(breath_mask) < 2: return None, None, None, None for kt in KT_GRID: for kp in KP_GRID: preds = (kt - u_in / kp) preds_round = (preds-MIN_PRESSURE)/DIFF_PRESSURE tune_error = np.round(preds_round[breath_mask]) - preds_round[breath_mask] if np.sum(np.abs(tune_error)) < 1e-6: return preds, kt, kp, breath_mask return None, None, None, None"
},
{
"code": null,
"e": 5790,
"s": 5217,
"text": "After discovering the post-processing trick, we were not able to make any more significant improvements. We slowly saw our rank dropping on the LB, and it was clear that we would needed someone with more deep learning experience in order to obtain a good result in this competition. We messaged Shujun who was just below the gold zone at that time. I knew that Shujun is extremely strong in deep learning as he got a solo gold medal with a unique and strong architecture in the “OpenVaccine — Covid mRNA” competition in which I participated too. Boy did he NOT disappoint."
},
{
"code": null,
"e": 6561,
"s": 5790,
"text": "Shujun’s deep learning architecture was a combination of LSTM cells, 1D convolutions, and transformers. LSTMs were necessary because of target pressure’s heavy dependence on previous time points. Convolutions in conjunction with transformers is a good combination to model global dependencies while making up for transformers’ inability to capture local interactions. The network was rather deep, and we ran into some gradient issues. Therefore, a new module called ResidualLSTM, which adds a Feedforward Network (FFN) and connects the input to the LSTM with the output after FFN with a residual connection, was created. The model works on the raw data in addition with a few lag and difference features, a cumulative sum of the u_in, and one-hot-encoded R & C features."
},
{
"code": null,
"e": 6696,
"s": 6561,
"text": "We ensembled our current blend with Shujun’s blend of different runs of his model and applied our PP trick. Boom, we were in the gold!"
},
{
"code": null,
"e": 6897,
"s": 6696,
"text": "We tried suggesting some ideas to Shujun to implement in his pipeline, and also tried adding some features so the pipeline (as his pipeline was leveraging features). But again, we were not successful."
},
{
"code": null,
"e": 7717,
"s": 6897,
"text": "A few days later, we felt that we needed another unique deep learning pipeline for our blend. This is where Riccardo enters the story! At the time when we messaged him, Riccardo was only a few spots below us. He had an LSTM architecture up and running that converged on just the raw data. No feature engineering, no fancy stuff, just raw data and a lot of epochs. The trick was to have a good learning rate scheduler. We opted for a ReduceLROnPlateau with a patience of 30 epochs. This was in contrast with the fast annealing schedulers typically used within the public notebooks, which were susceptible to overfitting. This can be seen when we compare our validation loss curves to those of the public notebooks, as displayed below. Here the red (stakes) curve corresponds to the public notebooks and quickly overfits."
},
{
"code": null,
"e": 7938,
"s": 7717,
"text": "This approach even scored better than the LSTM + 1D CNN Transformer Encoder. The blend of these pipelines gave us the fourth spot on the leaderboard. We decided to change our ambitions from a gold medal to winning money."
},
{
"code": null,
"e": 8306,
"s": 7938,
"text": "Again, all of us focused on improving the two pipelines we had up and running. Making slight modifications to both pipelines or adding features to the transformer pipeline. Only extremely marginal improvements were made, and the gap with the competitors ahead of us was too big. Surely, there was something hidden in the data that they had found and we did not yet..."
},
{
"code": null,
"e": 8589,
"s": 8306,
"text": "On the 26th of October, my birthday, I decided to learn some more about PID (Proportional - Integral - Derivative) controllers, as those were a core concept in the organizers their paper as well. Moreover, our post-processing trick came from Yves looking into these PID controllers."
},
{
"code": null,
"e": 9281,
"s": 8589,
"text": "I played around with the simple-pid package in Python as this package already implements the PID formulas. I was able to reproduce our post-processing trick with this package as well. However, for most breaths I was not able to find a match. That was until I decided to play around with the code and the integral term specifically. There are multiple ways to calculate the Integral term of PID controllers, and the package only included the vanilla implementation. I decided to plug in some other alternatives and suddenly, I had a breakthrough... WHAT A BIRTHDAY GIFT! The following code snippet (based on the simple-pid package) was able to model pressure->u_in perfectly for some breaths:"
},
{
"code": null,
"e": 9381,
"s": 9281,
"text": "Here is the code snippet that was able to perfectly model pressure to u_in for some of the breaths:"
},
{
"code": null,
"e": 9682,
"s": 9381,
"text": "def generate_u_in(pressure, time_step, kp, ki, kt, integral=0): dt = np.diff(time_step, prepend=[0]) preds = [] for j in range(32): error = kt - pressure[j] integral += (error - integral) * (dt[j] / (dt[j] + 0.5)) preds.append(kp * error + ki * integral) return preds"
},
{
"code": null,
"e": 9903,
"s": 9682,
"text": "I thought we had a new nice post-processing trick on our hands, and sent this information to Yves. Yves made something much much bigger out of it. He came up with some code that was able to match the pressures perfectly."
},
{
"code": null,
"e": 10019,
"s": 9903,
"text": "We can write the “vanilla” equation of a PID controller (that corresponds to the generate_u_in snippet I provided):"
},
{
"code": null,
"e": 10548,
"s": 10019,
"text": "With epsilon equal to target — pressure where target represents the ideal pressure that is set by the user. Now gamma, which is the weight of the derivative term, was always set to zero by the organizers. So we only had to focus on the first (proportional) and second (integral) term. Our previously discussed post-processing technique actually corresponds to this equation with beta set to 0. Let’s rewrite the second integral term for ease of notation. Moreover, the integral term was implemented by a weight decay as follows:"
},
{
"code": null,
"e": 10836,
"s": 10548,
"text": "With delta_t the difference in time between timestep t and t-1 and tau a constant, which was equal to 0.5 for this data. We can isolate the integral term from the PID equation, in order to calculate it for any point in time. This avoids having to propagate this across the entire signal:"
},
{
"code": null,
"e": 11139,
"s": 10836,
"text": "With these equations, we are all set for our matching algorithm. Our matching algorithm to fill in the pressure for a given breath at timestep t, for a given configuration of parameters (target, alpha and beta or referred to as kt, kp and ki respectively in the remainder of this post) goes as follows:"
},
{
"code": null,
"e": 11456,
"s": 11139,
"text": "Take two random pressure values P0 and P1 . There are 950 possible pressure values and thus 950*950 possible combinations.Calculate I0 = (u_in[t - 1] - kp * (kt - P0))/kiCalculate I1 = I0 + (kt - P1 - I0) * (dt / (dt + 0.5))If kp * (kt - P1) + ki * I1 == u_in[t] we have a match and we can fill in P1 for pressure[t]"
},
{
"code": null,
"e": 11579,
"s": 11456,
"text": "Take two random pressure values P0 and P1 . There are 950 possible pressure values and thus 950*950 possible combinations."
},
{
"code": null,
"e": 11628,
"s": 11579,
"text": "Calculate I0 = (u_in[t - 1] - kp * (kt - P0))/ki"
},
{
"code": null,
"e": 11683,
"s": 11628,
"text": "Calculate I1 = I0 + (kt - P1 - I0) * (dt / (dt + 0.5))"
},
{
"code": null,
"e": 11776,
"s": 11683,
"text": "If kp * (kt - P1) + ki * I1 == u_in[t] we have a match and we can fill in P1 for pressure[t]"
},
{
"code": null,
"e": 11785,
"s": 11776,
"text": "In code:"
},
{
"code": null,
"e": 12137,
"s": 11785,
"text": "P_RANGE = np.arange( MIN_PRESSURE, MAX_PRESSURE + DIFF_PRESSURE, DIFF_PRESSURE)for P0 in P_RANGE: for P1 in P_RANGE: I0 = (u_in[t - 1] - kp * (kt - P0))/ki I1 = I0 + (kt - P1 - I0) * (dt / (dt + 0.5)) u_in_hat = kp * (kt - P1) + ki * I1 if abs(u_in_hat - u_in[t]) < 1e-8: print(P0, P1, pressure[t-1:t+1])"
},
{
"code": null,
"e": 12749,
"s": 12137,
"text": "However, this code is rather slow. This is because 950*950 combinations need to be tried for every possible parameter combination. kp and ki have 20 possible values and kt has 6 possible values, in total we thus have 950*950*20*20*6 possible combinations. However, for a fixed P0 we notice that abs(u_in_hat — u_in[t]) grows linearly across the for-loop. As such, we can extrapolate this with just 2 measurements. If the intersection of this extrapolated function with the x-axis occurs at an integer (or close to an integer), our if-condition would have evaluated to True in an iteration of our inner for-loop."
},
{
"code": null,
"e": 12819,
"s": 12749,
"text": "This observation allows us to speed up the code with a factor of 950."
},
{
"code": null,
"e": 13371,
"s": 12819,
"text": "for P0 in P_RANGE: I0 = (u_in[t - 1] - kp * (kt - P0))/ki # Calculate 2 points for P1 so we can get the slope I11 = I0 + (kt - MIN_PRESSURE - I0) * (dt / (dt + 0.5)) u_in_hat1 = kp * (kt - MIN_PRESSURE) + ki * I11 I12 = I0 + (kt - MIN_PRESSURE2 - I0) * (dt / (dt + 0.5)) u_in_hat2 = kp * (kt - MIN_PRESSURE2) + ki * I12 slope = u_in_hat2 - u_in_hat1 x_intersect = (u_in[t] - u_in_hat2) / slope if abs(np.round(x_intersect) - x_intersect) < 1e-8: print(P0, MIN_PRESSURE + (x_intersect + 1) * DIFF_PRESSURE)"
},
{
"code": null,
"e": 13748,
"s": 13371,
"text": "With the code above, we were able to match a lot of pressures. But many of them still remained unmatched. In the paper of the organizers, it was explained that artificial noise was added to the u_in data. We set out on an endeavour to remove this noise. Let us first look at the output of the current version of a matching algorithm on a particular breath (train breath id 17)"
},
{
"code": null,
"e": 14128,
"s": 13748,
"text": "As one notices, the first value of the u_in and some values in the middle were not fully matched. The first values of all breaths are noisy and are not matchable, but the points in the middle should be matchable... Let us start from index 5 and call our generate_u_in code on the provided pressures to generate “ideal u_in values” and subtract this from the u_in we are provided."
},
{
"code": null,
"e": 14371,
"s": 14128,
"text": "kp, ki, kt = 1., 3., 30I5 = (u_in[4] - kp * (kt - pressure[4]))/kiu_in_hat = generate_u_in(pressure[5:], timestep[4:], kp, ki, kt, integral=I5)noise = u_in[5:32] - u_in_hat[:-5]plt.plot(timestep[5:32], noise, '-o')plt.title('noise')plt.show()"
},
{
"code": null,
"e": 14731,
"s": 14371,
"text": "The difference between the ideal u_in values and the provided u_in values form a nice triangle, except on the turning point / peak of the triangle. The key insight is that the slope of this noise ((np.diff(noise) / np.diff(timestep[5:32]))) will be equal for consecutive points on this triangle. We can also rewrite our integral calculation to work backwards."
},
{
"code": null,
"e": 14804,
"s": 14731,
"text": "Strapped with these two insights, we were able to match a lot more data:"
},
{
"code": null,
"e": 14880,
"s": 14804,
"text": "Given our DL models and matching algorithm, our approach was rather simple:"
},
{
"code": null,
"e": 15352,
"s": 14880,
"text": "Generate predictions with our two DL models. Train them in 10-fold cross validation at multiple seeds. This gives us multiple models with slight variations. Take the (weighted) median of these models as an ensembling technique as that is typically better than a mean when MAE is the metric.From these predictions, apply our matching algorithm. If we find a match, replace the prediction of the DL algorithm by the matcher. If there is not a match, keep the DL prediction."
},
{
"code": null,
"e": 15643,
"s": 15352,
"text": "Generate predictions with our two DL models. Train them in 10-fold cross validation at multiple seeds. This gives us multiple models with slight variations. Take the (weighted) median of these models as an ensembling technique as that is typically better than a mean when MAE is the metric."
},
{
"code": null,
"e": 15825,
"s": 15643,
"text": "From these predictions, apply our matching algorithm. If we find a match, replace the prediction of the DL algorithm by the matcher. If there is not a match, keep the DL prediction."
},
{
"code": null,
"e": 15928,
"s": 15825,
"text": "In total we were able to roughly match 66% of the data, which gave us a HUGE boost on the leaderboard."
},
{
"code": null,
"e": 16346,
"s": 15928,
"text": "This was my first victory on Kaggle. While I admit that the PID controller matching was a bit cheeky, I am still extremely proud of our result as only 2 teams out of 2650 were able to find this exploit. Moreover, we were the only team that was able to match the noise within the u_in data as well. I would like to thank my team mates zidmie, kha, shujun and B as without them this result would not have been possible!"
},
{
"code": null,
"e": 16491,
"s": 16346,
"text": "In case you have any questions or something is unclear, feel free to leave some comments or contact me through some other medium (pun intended)."
},
{
"code": null,
"e": 16711,
"s": 16491,
"text": "Organizers PaperKaggle Forum write-upPID Matching Code + Explanation (Kaggle)PID Matching Code + Explanation (Github)LSTM + CNN Transformer code (Kaggle)LSTM + CNN Transformer code (Github)LSTM on raw data code (Github)"
},
{
"code": null,
"e": 16728,
"s": 16711,
"text": "Organizers Paper"
},
{
"code": null,
"e": 16750,
"s": 16728,
"text": "Kaggle Forum write-up"
},
{
"code": null,
"e": 16791,
"s": 16750,
"text": "PID Matching Code + Explanation (Kaggle)"
},
{
"code": null,
"e": 16832,
"s": 16791,
"text": "PID Matching Code + Explanation (Github)"
},
{
"code": null,
"e": 16869,
"s": 16832,
"text": "LSTM + CNN Transformer code (Kaggle)"
},
{
"code": null,
"e": 16906,
"s": 16869,
"text": "LSTM + CNN Transformer code (Github)"
}
] |
How to generate non-repeating random numbers in Python? | Following program generates 10 random, non-repetitive integers between 1 to 100. It generates a random integer in the given interval and adds it in a list if it is not previously added.
>>> import random
>>> list=[]
>>> for i in range(10):
r=random.randint(1,100)
if r not in list: list.append(r)
>>> list
[13, 53, 25, 95, 64, 87, 27, 93, 74, 60] | [
{
"code": null,
"e": 1248,
"s": 1062,
"text": "Following program generates 10 random, non-repetitive integers between 1 to 100. It generates a random integer in the given interval and adds it in a list if it is not previously added."
},
{
"code": null,
"e": 1430,
"s": 1248,
"text": ">>> import random\n>>> list=[]\n>>> for i in range(10):\n r=random.randint(1,100)\n if r not in list: list.append(r)\n\n>>> list\n[13, 53, 25, 95, 64, 87, 27, 93, 74, 60]"
}
] |
How to retrieve multiple ResultSets from a stored procedure using a JDBC program? | Stored procedures are sub routines, segment of SQL statements which are stored in SQL catalog. All the applications that can access Relational databases (Java, Python, PHP etc.), can access stored procedures.
Stored procedures contain IN and OUT parameters or both. They may return result sets in case you use SELECT statements. Stored procedures can return multiple result sets.
You can call an existing stored procedure using the CallableStatement. The prepareCall() method of the Connection interface accepts the procedure call in string format and returns a callable statement object.
CallableStatement cstmt = con.prepareCall("{call sampleProcedure()}");
Execute the above created callable statement using the executeQuery() method this returns a result set object.
//Executing the CallableStatement
ResultSet rs1 = cstmt.executeQuery();
If this procedure returns more result-set objects move to the next result-set using the cstmt.getMoreResults() method.
And then, retrieve the next result-set using the getResultSet() method of the CallableStatement interface.
ResultSet rs2 = cstmt.getResultSet();
Assume we have a table named cricketers_data in the database with the following description:
+----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| First_Name | varchar(255) | YES | | NULL | |
| Last_Name | varchar(255) | YES | | NULL | |
| Year_Of_Birth | date | YES | | NULL | |
| Place_Of_Birth | varchar(255) | YES | | NULL | |
| Country | varchar(255) | YES | | NULL | |
+----------------+--------------+------+-----+---------+-------+
And a table named dispatch_data with the following description:
+------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| Product_Name | varchar(255) | YES | | NULL | |
| Name_Of_Customer | varchar(255) | YES | | NULL | |
| Dispatch_Date | date | YES | | NULL | |
| Location | varchar(255) | YES | | NULL | |
+------------------+--------------+------+-----+---------+-------+
And we have created a procedure named sampleProcedure which retrieves the contents of these two tables as shown below:
mysql> DELIMITER // ;
mysql> Create procedure sampleProcedure ()
BEGIN
Select * from cricketers_data;
Select * from dispatch_data;
END//
Query OK, 0 rows affected (0.04 sec)
mysql> DELIMITER ;
Following JDBC example establishes connection with the database, calls the procedure named sampleProcedure, retrieves the result-sets it returns, and prints the contents.
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MultipleResultSetsStoredProcedure {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Preparing a CallableStatement to call the retrieveData procedure
CallableStatement cstmt = con.prepareCall("{call sampleProcedure()}");
//Executing the CallableStatement
ResultSet rs1 = cstmt.executeQuery();
//Displaying the result
System.out.println("Contents of the first result-set");
while(rs1.next()) {
System.out.print("First Name: "+rs1.getString("First_Name")+", ");
System.out.print("Last Name: "+rs1.getString("Last_Name")+", ");
System.out.print("Year of Birth: "+rs1.getDate("Year_Of_Birth")+", ");
System.out.print("Place of Birth: "+rs1.getString("Place_Of_Birth")+", ");
System.out.print("Country: "+rs1.getString("Country"));
System.out.println();
}
System.out.println(" ");
cstmt.getMoreResults();
System.out.println("Contents of the second result-set");
ResultSet rs2 = cstmt.getResultSet();
while(rs2.next()) {
System.out.print("Product Name: "+rs2.getString("Product_Name")+", ");
System.out.print("Name of Customer: "+rs2.getString("Name_Of_Customer")+", ");
System.out.print("Dispatch Date: "+rs2.getDate("Dispatch_Date")+", ");
System.out.print("Location: "+rs2.getString("Location"));
System.out.println();
}
}
}
Connection established......
Contents of the first result-set
First Name: Shikhar, Last Name: Dhawan, Year of Birth: 1981-12-05, Place of Birth: Delhi, Country: India
First Name: Jonathan, Last Name: Trott, Year of Birth: 1981-04-22, Place of Birth: CapeTown, Country: SouthAfrica
First Name: Lumara, Last Name: Sangakkara, Year of Birth: 1977-10-27, Place of Birth: Matale, Country: Srilanka
First Name: Virat, Last Name: Kohli, Year of Birth: 1988-11-05, Place of Birth: Delhi, Country: India
First Name: Rohit, Last Name: Sharma, Year of Birth: 1987-04-30, Place of Birth: Nagpur, Country: India
Contents of the second result-set
Product Name: KeyBoard, Name of Customer: Amith, Dispatch Date: 1981-12-05, Location: Hyderabad
Product Name: Ear phones, Name of Customer: Sumith, Dispatch Date: 1981-04-22, Location: Vishakhapatnam
Product Name: Mouse, Name of Customer: Sudha, Dispatch Date: 1988-11-05, Location: Vijayawada | [
{
"code": null,
"e": 1271,
"s": 1062,
"text": "Stored procedures are sub routines, segment of SQL statements which are stored in SQL catalog. All the applications that can access Relational databases (Java, Python, PHP etc.), can access stored procedures."
},
{
"code": null,
"e": 1442,
"s": 1271,
"text": "Stored procedures contain IN and OUT parameters or both. They may return result sets in case you use SELECT statements. Stored procedures can return multiple result sets."
},
{
"code": null,
"e": 1651,
"s": 1442,
"text": "You can call an existing stored procedure using the CallableStatement. The prepareCall() method of the Connection interface accepts the procedure call in string format and returns a callable statement object."
},
{
"code": null,
"e": 1722,
"s": 1651,
"text": "CallableStatement cstmt = con.prepareCall(\"{call sampleProcedure()}\");"
},
{
"code": null,
"e": 1833,
"s": 1722,
"text": "Execute the above created callable statement using the executeQuery() method this returns a result set object."
},
{
"code": null,
"e": 1905,
"s": 1833,
"text": "//Executing the CallableStatement\nResultSet rs1 = cstmt.executeQuery();"
},
{
"code": null,
"e": 2024,
"s": 1905,
"text": "If this procedure returns more result-set objects move to the next result-set using the cstmt.getMoreResults() method."
},
{
"code": null,
"e": 2131,
"s": 2024,
"text": "And then, retrieve the next result-set using the getResultSet() method of the CallableStatement interface."
},
{
"code": null,
"e": 2169,
"s": 2131,
"text": "ResultSet rs2 = cstmt.getResultSet();"
},
{
"code": null,
"e": 2262,
"s": 2169,
"text": "Assume we have a table named cricketers_data in the database with the following description:"
},
{
"code": null,
"e": 2847,
"s": 2262,
"text": "+----------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+----------------+--------------+------+-----+---------+-------+\n| First_Name | varchar(255) | YES | | NULL | |\n| Last_Name | varchar(255) | YES | | NULL | |\n| Year_Of_Birth | date | YES | | NULL | |\n| Place_Of_Birth | varchar(255) | YES | | NULL | |\n| Country | varchar(255) | YES | | NULL | |\n+----------------+--------------+------+-----+---------+-------+"
},
{
"code": null,
"e": 2911,
"s": 2847,
"text": "And a table named dispatch_data with the following description:"
},
{
"code": null,
"e": 3447,
"s": 2911,
"text": "+------------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+------------------+--------------+------+-----+---------+-------+\n| Product_Name | varchar(255) | YES | | NULL | |\n| Name_Of_Customer | varchar(255) | YES | | NULL | |\n| Dispatch_Date | date | YES | | NULL | |\n| Location | varchar(255) | YES | | NULL | |\n+------------------+--------------+------+-----+---------+-------+"
},
{
"code": null,
"e": 3566,
"s": 3447,
"text": "And we have created a procedure named sampleProcedure which retrieves the contents of these two tables as shown below:"
},
{
"code": null,
"e": 3793,
"s": 3566,
"text": "mysql> DELIMITER // ;\nmysql> Create procedure sampleProcedure ()\n BEGIN\n Select * from cricketers_data;\n Select * from dispatch_data;\n END//\nQuery OK, 0 rows affected (0.04 sec)\nmysql> DELIMITER ;"
},
{
"code": null,
"e": 3964,
"s": 3793,
"text": "Following JDBC example establishes connection with the database, calls the procedure named sampleProcedure, retrieves the result-sets it returns, and prints the contents."
},
{
"code": null,
"e": 5881,
"s": 3964,
"text": "import java.sql.CallableStatement;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\npublic class MultipleResultSetsStoredProcedure {\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 mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Preparing a CallableStatement to call the retrieveData procedure\n CallableStatement cstmt = con.prepareCall(\"{call sampleProcedure()}\");\n //Executing the CallableStatement\n ResultSet rs1 = cstmt.executeQuery();\n //Displaying the result\n System.out.println(\"Contents of the first result-set\");\n while(rs1.next()) {\n System.out.print(\"First Name: \"+rs1.getString(\"First_Name\")+\", \");\n System.out.print(\"Last Name: \"+rs1.getString(\"Last_Name\")+\", \");\n System.out.print(\"Year of Birth: \"+rs1.getDate(\"Year_Of_Birth\")+\", \");\n System.out.print(\"Place of Birth: \"+rs1.getString(\"Place_Of_Birth\")+\", \");\n System.out.print(\"Country: \"+rs1.getString(\"Country\"));\n System.out.println();\n }\n System.out.println(\" \");\n cstmt.getMoreResults();\n System.out.println(\"Contents of the second result-set\");\n ResultSet rs2 = cstmt.getResultSet();\n while(rs2.next()) {\n System.out.print(\"Product Name: \"+rs2.getString(\"Product_Name\")+\", \");\n System.out.print(\"Name of Customer: \"+rs2.getString(\"Name_Of_Customer\")+\", \");\n System.out.print(\"Dispatch Date: \"+rs2.getDate(\"Dispatch_Date\")+\", \");\n System.out.print(\"Location: \"+rs2.getString(\"Location\"));\n System.out.println();\n }\n }\n}"
},
{
"code": null,
"e": 6809,
"s": 5881,
"text": "Connection established......\nContents of the first result-set\nFirst Name: Shikhar, Last Name: Dhawan, Year of Birth: 1981-12-05, Place of Birth: Delhi, Country: India\nFirst Name: Jonathan, Last Name: Trott, Year of Birth: 1981-04-22, Place of Birth: CapeTown, Country: SouthAfrica\nFirst Name: Lumara, Last Name: Sangakkara, Year of Birth: 1977-10-27, Place of Birth: Matale, Country: Srilanka\nFirst Name: Virat, Last Name: Kohli, Year of Birth: 1988-11-05, Place of Birth: Delhi, Country: India\nFirst Name: Rohit, Last Name: Sharma, Year of Birth: 1987-04-30, Place of Birth: Nagpur, Country: India\n\nContents of the second result-set\nProduct Name: KeyBoard, Name of Customer: Amith, Dispatch Date: 1981-12-05, Location: Hyderabad\nProduct Name: Ear phones, Name of Customer: Sumith, Dispatch Date: 1981-04-22, Location: Vishakhapatnam\nProduct Name: Mouse, Name of Customer: Sudha, Dispatch Date: 1988-11-05, Location: Vijayawada"
}
] |
How to Create a Unlock Slide-Bar in Android? - GeeksforGeeks | 23 Feb, 2021
A SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch the thumb and drag left or right to set the current progress level or use the arrow keys. SeekBar is a useful user interface element in Android that allows the selection of integer values using a natural user interface. An example of SeekBar is your device’s brightness control and volume control. But did you knew a SeekBar could be implemented as an Unlock Slide Bar? Through this article, we want to share with you how one can implement an Unlock Slide Bar using a SeekBar.
SeekBar has the same attributes as a ProgressBar. But the only difference is the user determines the progress by moving a slider (thumb) in SeekBar. To add a SeekBar to a layout (XML) file, you can use the <SeekBar> element. Below is an example of the Unlock Slide Bar.
To unlock a screen, unlock an activity, go to an activity (what we discussed in this article).
Using a similar concept to build Games.
Confirming a checkout at Payment Gateways.
For Switching off the Alarms.
A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Please refer to the following points that define the module for the application that we implemented:
The application has 2 Activities, MainActivity and MainActivity2, both have respective layout files activity_main and activity_main2.
The SeekBar is present in the First Activity, i.e., declared in the activity_main file.
We have programmed the SeekBar in such a way that when the user swipes it till the end, the user is taken to a new activity, i.e., MainActivity2. Else, the SeekBar sets its progress to 0 and displays a Toast message.
A textView is provided in the First Activity to show the progress of the SeekBar in real-time.
To create a Slide-Bar in Android, we follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Now go to the activity_main.xml file which represents the UI of the application. Create a SeekBar and TextView as shown. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Seek Bar, set max to 100 to view the progress with respect to 100--> <!--progressDrawable is the color you want for your progress track--> <!--thumb is the icon that user will slide over the track--> <SeekBar android:id="@+id/sbb" android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="false" android:max="100" android:progressDrawable="@color/colorPrimaryDark" android:thumb="@mipmap/ic_launcher" tools:ignore="MissingConstraints" /> <!--This textView will display the progress of SeekBar--> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> </RelativeLayout>
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Intentimport android.os.Bundleimport android.widget.SeekBarimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // declare the textView from the layout file val tv = findViewById<TextView>(R.id.tv) // declare the SeekBar from the layout file val sb = findViewById<SeekBar>(R.id.sbb) // Action when SeekBar is used sb.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { // Member Implementation (Required) // Keeps the track if touch was lifted off the SeekBar override fun onStopTrackingTouch(seekBar: SeekBar) { // If touch was lifted before the SeekBar progress was 100 // Make a Toast message "Try Again" and set the progress to 0 if (seekBar.progress < 100) { Toast.makeText(applicationContext, "Try Again", Toast.LENGTH_SHORT).show() seekBar.progress = 0 } } // Member Implementation (Required) override fun onStartTrackingTouch(seekBar: SeekBar) { // Do anything or Nothing } // Member Implementation (Required) // Keeps the track of progress of the seekbar override fun onProgressChanged( seekBar: SeekBar, progress: Int, fromUser: Boolean ) { // Show the progress when progress was less than 100 if (progress < 100) { tv.text = "Progress : $progress" } // If the progress is 100, take the user to another activity // Via Intent if (progress == 100) { startActivity( Intent( applicationContext, MainActivity2::class.java ) ) } } }) }}
Step 4: Create another activity
Create another activity with layout file by right-clicking on the app folder > New > Activity > Empty Activity. And refer to the following code. The only changes made to the activity_main2.xml file, no changes made to the MainActivity2.kt file. Below is the core for both activity_main2.xml and MainActivity2.kt file.
XML
Kotlin
<?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=".MainActivity2"> <!--activity_main2.xml file that shows "New Activity" message in a textView--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="New Activity" android:textSize="50sp" /> </RelativeLayout>
// No Changes in this fileimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity2 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) }}
Android-Bars
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Resource Raw Folder in Android Studio
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
Broadcast Receiver in Android With Example
Kotlin Array
Android UI Layouts
Android RecyclerView in Kotlin
Content Providers in Android with Example | [
{
"code": null,
"e": 26731,
"s": 26703,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 27297,
"s": 26731,
"text": "A SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch the thumb and drag left or right to set the current progress level or use the arrow keys. SeekBar is a useful user interface element in Android that allows the selection of integer values using a natural user interface. An example of SeekBar is your device’s brightness control and volume control. But did you knew a SeekBar could be implemented as an Unlock Slide Bar? Through this article, we want to share with you how one can implement an Unlock Slide Bar using a SeekBar."
},
{
"code": null,
"e": 27567,
"s": 27297,
"text": "SeekBar has the same attributes as a ProgressBar. But the only difference is the user determines the progress by moving a slider (thumb) in SeekBar. To add a SeekBar to a layout (XML) file, you can use the <SeekBar> element. Below is an example of the Unlock Slide Bar."
},
{
"code": null,
"e": 27662,
"s": 27567,
"text": "To unlock a screen, unlock an activity, go to an activity (what we discussed in this article)."
},
{
"code": null,
"e": 27702,
"s": 27662,
"text": "Using a similar concept to build Games."
},
{
"code": null,
"e": 27745,
"s": 27702,
"text": "Confirming a checkout at Payment Gateways."
},
{
"code": null,
"e": 27775,
"s": 27745,
"text": "For Switching off the Alarms."
},
{
"code": null,
"e": 27942,
"s": 27775,
"text": "A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 28043,
"s": 27942,
"text": "Please refer to the following points that define the module for the application that we implemented:"
},
{
"code": null,
"e": 28177,
"s": 28043,
"text": "The application has 2 Activities, MainActivity and MainActivity2, both have respective layout files activity_main and activity_main2."
},
{
"code": null,
"e": 28265,
"s": 28177,
"text": "The SeekBar is present in the First Activity, i.e., declared in the activity_main file."
},
{
"code": null,
"e": 28482,
"s": 28265,
"text": "We have programmed the SeekBar in such a way that when the user swipes it till the end, the user is taken to a new activity, i.e., MainActivity2. Else, the SeekBar sets its progress to 0 and displays a Toast message."
},
{
"code": null,
"e": 28577,
"s": 28482,
"text": "A textView is provided in the First Activity to show the progress of the SeekBar in real-time."
},
{
"code": null,
"e": 28642,
"s": 28577,
"text": "To create a Slide-Bar in Android, we follow the following steps:"
},
{
"code": null,
"e": 28671,
"s": 28642,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 28835,
"s": 28671,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 28883,
"s": 28835,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 29054,
"s": 28883,
"text": "Now go to the activity_main.xml file which represents the UI of the application. Create a SeekBar and TextView as shown. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 29058,
"s": 29054,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Seek Bar, set max to 100 to view the progress with respect to 100--> <!--progressDrawable is the color you want for your progress track--> <!--thumb is the icon that user will slide over the track--> <SeekBar android:id=\"@+id/sbb\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:clickable=\"false\" android:max=\"100\" android:progressDrawable=\"@color/colorPrimaryDark\" android:thumb=\"@mipmap/ic_launcher\" tools:ignore=\"MissingConstraints\" /> <!--This textView will display the progress of SeekBar--> <TextView android:id=\"@+id/tv\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" /> </RelativeLayout>",
"e": 30141,
"s": 29058,
"text": null
},
{
"code": null,
"e": 30187,
"s": 30141,
"text": "Step 3: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 30371,
"s": 30187,
"text": "Go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 30378,
"s": 30371,
"text": "Kotlin"
},
{
"code": "import android.content.Intentimport android.os.Bundleimport android.widget.SeekBarimport android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // declare the textView from the layout file val tv = findViewById<TextView>(R.id.tv) // declare the SeekBar from the layout file val sb = findViewById<SeekBar>(R.id.sbb) // Action when SeekBar is used sb.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { // Member Implementation (Required) // Keeps the track if touch was lifted off the SeekBar override fun onStopTrackingTouch(seekBar: SeekBar) { // If touch was lifted before the SeekBar progress was 100 // Make a Toast message \"Try Again\" and set the progress to 0 if (seekBar.progress < 100) { Toast.makeText(applicationContext, \"Try Again\", Toast.LENGTH_SHORT).show() seekBar.progress = 0 } } // Member Implementation (Required) override fun onStartTrackingTouch(seekBar: SeekBar) { // Do anything or Nothing } // Member Implementation (Required) // Keeps the track of progress of the seekbar override fun onProgressChanged( seekBar: SeekBar, progress: Int, fromUser: Boolean ) { // Show the progress when progress was less than 100 if (progress < 100) { tv.text = \"Progress : $progress\" } // If the progress is 100, take the user to another activity // Via Intent if (progress == 100) { startActivity( Intent( applicationContext, MainActivity2::class.java ) ) } } }) }}",
"e": 32612,
"s": 30378,
"text": null
},
{
"code": null,
"e": 32644,
"s": 32612,
"text": "Step 4: Create another activity"
},
{
"code": null,
"e": 32962,
"s": 32644,
"text": "Create another activity with layout file by right-clicking on the app folder > New > Activity > Empty Activity. And refer to the following code. The only changes made to the activity_main2.xml file, no changes made to the MainActivity2.kt file. Below is the core for both activity_main2.xml and MainActivity2.kt file."
},
{
"code": null,
"e": 32966,
"s": 32962,
"text": "XML"
},
{
"code": null,
"e": 32973,
"s": 32966,
"text": "Kotlin"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity2\"> <!--activity_main2.xml file that shows \"New Activity\" message in a textView--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"New Activity\" android:textSize=\"50sp\" /> </RelativeLayout>",
"e": 33577,
"s": 32973,
"text": null
},
{
"code": "// No Changes in this fileimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity2 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) }}",
"e": 33871,
"s": 33577,
"text": null
},
{
"code": null,
"e": 33884,
"s": 33871,
"text": "Android-Bars"
},
{
"code": null,
"e": 33892,
"s": 33884,
"text": "Android"
},
{
"code": null,
"e": 33899,
"s": 33892,
"text": "Kotlin"
},
{
"code": null,
"e": 33907,
"s": 33899,
"text": "Android"
},
{
"code": null,
"e": 34005,
"s": 33907,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34063,
"s": 34005,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 34101,
"s": 34063,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 34144,
"s": 34101,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 34175,
"s": 34144,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 34217,
"s": 34175,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 34260,
"s": 34217,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 34273,
"s": 34260,
"text": "Kotlin Array"
},
{
"code": null,
"e": 34292,
"s": 34273,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 34323,
"s": 34292,
"text": "Android RecyclerView in Kotlin"
}
] |
Scala List exists() method with example - GeeksforGeeks | 29 Jul, 2019
The exists() method is utilized to check if the given predicate satisfy the elements of the list or not.
Method Definition: def exists(p: (A) => Boolean): Boolean
Return Type: It returns true if the stated predicate holds true for some elements of the list else it returns false.
Example #1:
// Scala program of exists()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3, 4, 5) // Applying exists method val result = m1.exists(y => {y % 3 == 0}) // Displays output println(result) }}
true
Example #2:
// Scala program of exists()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3, 4, 5) // Applying exists method val result = m1.exists(y => {y % 9 == 0}) // Displays output println(result) }}
false
Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala Lists
Class and Object in Scala
Operators in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Constructors
How to get the first element of List in Scala
Scala Map get() method with example
Scala | Arrays
Scala String replace() method with example
Break statement in Scala | [
{
"code": null,
"e": 23980,
"s": 23952,
"text": "\n29 Jul, 2019"
},
{
"code": null,
"e": 24085,
"s": 23980,
"text": "The exists() method is utilized to check if the given predicate satisfy the elements of the list or not."
},
{
"code": null,
"e": 24143,
"s": 24085,
"text": "Method Definition: def exists(p: (A) => Boolean): Boolean"
},
{
"code": null,
"e": 24260,
"s": 24143,
"text": "Return Type: It returns true if the stated predicate holds true for some elements of the list else it returns false."
},
{
"code": null,
"e": 24272,
"s": 24260,
"text": "Example #1:"
},
{
"code": "// Scala program of exists()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3, 4, 5) // Applying exists method val result = m1.exists(y => {y % 3 == 0}) // Displays output println(result) }} ",
"e": 24629,
"s": 24272,
"text": null
},
{
"code": null,
"e": 24635,
"s": 24629,
"text": "true\n"
},
{
"code": null,
"e": 24647,
"s": 24635,
"text": "Example #2:"
},
{
"code": "// Scala program of exists()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3, 4, 5) // Applying exists method val result = m1.exists(y => {y % 9 == 0}) // Displays output println(result) }} ",
"e": 25000,
"s": 24647,
"text": null
},
{
"code": null,
"e": 25007,
"s": 25000,
"text": "false\n"
},
{
"code": null,
"e": 25013,
"s": 25007,
"text": "Scala"
},
{
"code": null,
"e": 25024,
"s": 25013,
"text": "Scala-list"
},
{
"code": null,
"e": 25037,
"s": 25024,
"text": "Scala-Method"
},
{
"code": null,
"e": 25043,
"s": 25037,
"text": "Scala"
},
{
"code": null,
"e": 25141,
"s": 25043,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25153,
"s": 25141,
"text": "Scala Lists"
},
{
"code": null,
"e": 25179,
"s": 25153,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 25198,
"s": 25179,
"text": "Operators in Scala"
},
{
"code": null,
"e": 25251,
"s": 25198,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 25270,
"s": 25251,
"text": "Scala Constructors"
},
{
"code": null,
"e": 25316,
"s": 25270,
"text": "How to get the first element of List in Scala"
},
{
"code": null,
"e": 25352,
"s": 25316,
"text": "Scala Map get() method with example"
},
{
"code": null,
"e": 25367,
"s": 25352,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 25410,
"s": 25367,
"text": "Scala String replace() method with example"
}
] |
An Utterly Simple Guide on Installing Tensorflow-GPU 2.0 on Windows 10 | by Dario Radečić | Towards Data Science | TensorFlow is Google’s open-source library which enables you to develop and train deep learning models. Whilst most of the install guides focus on installing the CPU version, which is your regular pip install, today I want to focus on installing it’s bigger, much more powerful brother — the GPU version.
The main reason why you’d want to use GPU version instead of the CPU one is speed — there’s an incredible speed improvement if you decide to train models on GPU and I don’t wont to go in the reasons why — as this is an How to guide instead of Why to guide.
On top of everything, the setup will be done on Windows 10 x64 machine. So no Linux here, as I know installation on Linux is fairly trivial.
Without further ado, let’s jump right in. The next section will briefly discuss what you’ll need.
In this entire process we’ll need to download and install three tools:
Microsoft Visual Studio (Community edition is fine if you don’t have access to the Professional one)Nvidia CUDA Toolkit (I’m using version 10.0)Nvidia cuDNN (Version 7.6.5 is fine)
Microsoft Visual Studio (Community edition is fine if you don’t have access to the Professional one)
Nvidia CUDA Toolkit (I’m using version 10.0)
Nvidia cuDNN (Version 7.6.5 is fine)
The following sections will focus on how to install each individual tool.
Now we won’t be really using Visual Studio, but some components of the Nvidia CUDA Toolkit require it, so it is what it is.
Visual Studio can be downloaded from this link, and from here it’s easy to download the Community edition:
When installing you don’t need to check any additional components — leave everything as is and click on Next a couple of times. In about 5 to 10 minutes the installation should finish. You won’t need to touch the Visual Studio ever again, Tensorflow-wise.
This Toolkit enables you to create high-performance GPU-accelerated applications. In can be downloaded from this link, just make sure to select everything I have selected and then click on Download button down below.
It’s slightly over 2 GB in size, so depending on your internet speed it could take a while.
Once downloaded you can run the .exe file, it will ask you to extract the contents into some temporary folder. Once the installation begins you can stick with the Express option:
And after a couple of minutes, Nvidia CUDA Toolkit will be installed!
Up next, Nvidia cuDNN.
Nvidia cuDNN is a GPU-accelerated library for deep neural networks. It can be downloaded from this link. Keep in mind that you will need to create an account, but you can just log in with Google and you’re good to go.
Upon login, you will be redirected to the page below — click on Download cuDNN 7.6.5 for CUDA 10.0:
It is a ZIP file, maybe 250MB in size so it should download quickly. Once downloaded you can unzip the contents ̨(that is the 3 directories inside) to your CUDA installation directory — which will be in:
C:\Program Files\Nvidia GPU Computing Toolkit\CUDA\v10.0
if you haven’t changed anything upon the installation. And that’s it. Setup done!
We’ve completed the tedious setup process, now it’s only time to do a simple pip install. By the time of writing this article, the latest GPU enabled TensorFlow version was 2.0.0 RC1.
To install it, open up the Command Prompt and execute the following (I assume you have Python installed):
pip install tensorflow-gpu=2.0.0-rc1
If you fail to provide the version it will install version 1.14, which we don’t want.
And that’s it, it will take some time to download (300+ MB), but TensorFlow should now be installed on your machine. Let’s just quickly verify that claim:
As you can see, I opened the Python shell inside the Command Prompt, imported TensorFlow and checked if GPU is available. The function called return True, and you can also see my GPU colored yellow on the bottom of the prompt.
Having a thin and light laptop is nice — you can go anywhere without messing up your back. But what’s even cooler than not having back issues is having a powerful laptop capable of training neural networks on the GPU.
This article shouldn’t take you more than 5 minutes to read front to back, and 15 minutes to install and configure everything, provided you have a decent internet speed.
Thanks for reading. Have fun — I know I will.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. | [
{
"code": null,
"e": 477,
"s": 172,
"text": "TensorFlow is Google’s open-source library which enables you to develop and train deep learning models. Whilst most of the install guides focus on installing the CPU version, which is your regular pip install, today I want to focus on installing it’s bigger, much more powerful brother — the GPU version."
},
{
"code": null,
"e": 734,
"s": 477,
"text": "The main reason why you’d want to use GPU version instead of the CPU one is speed — there’s an incredible speed improvement if you decide to train models on GPU and I don’t wont to go in the reasons why — as this is an How to guide instead of Why to guide."
},
{
"code": null,
"e": 875,
"s": 734,
"text": "On top of everything, the setup will be done on Windows 10 x64 machine. So no Linux here, as I know installation on Linux is fairly trivial."
},
{
"code": null,
"e": 973,
"s": 875,
"text": "Without further ado, let’s jump right in. The next section will briefly discuss what you’ll need."
},
{
"code": null,
"e": 1044,
"s": 973,
"text": "In this entire process we’ll need to download and install three tools:"
},
{
"code": null,
"e": 1225,
"s": 1044,
"text": "Microsoft Visual Studio (Community edition is fine if you don’t have access to the Professional one)Nvidia CUDA Toolkit (I’m using version 10.0)Nvidia cuDNN (Version 7.6.5 is fine)"
},
{
"code": null,
"e": 1326,
"s": 1225,
"text": "Microsoft Visual Studio (Community edition is fine if you don’t have access to the Professional one)"
},
{
"code": null,
"e": 1371,
"s": 1326,
"text": "Nvidia CUDA Toolkit (I’m using version 10.0)"
},
{
"code": null,
"e": 1408,
"s": 1371,
"text": "Nvidia cuDNN (Version 7.6.5 is fine)"
},
{
"code": null,
"e": 1482,
"s": 1408,
"text": "The following sections will focus on how to install each individual tool."
},
{
"code": null,
"e": 1606,
"s": 1482,
"text": "Now we won’t be really using Visual Studio, but some components of the Nvidia CUDA Toolkit require it, so it is what it is."
},
{
"code": null,
"e": 1713,
"s": 1606,
"text": "Visual Studio can be downloaded from this link, and from here it’s easy to download the Community edition:"
},
{
"code": null,
"e": 1969,
"s": 1713,
"text": "When installing you don’t need to check any additional components — leave everything as is and click on Next a couple of times. In about 5 to 10 minutes the installation should finish. You won’t need to touch the Visual Studio ever again, Tensorflow-wise."
},
{
"code": null,
"e": 2186,
"s": 1969,
"text": "This Toolkit enables you to create high-performance GPU-accelerated applications. In can be downloaded from this link, just make sure to select everything I have selected and then click on Download button down below."
},
{
"code": null,
"e": 2278,
"s": 2186,
"text": "It’s slightly over 2 GB in size, so depending on your internet speed it could take a while."
},
{
"code": null,
"e": 2457,
"s": 2278,
"text": "Once downloaded you can run the .exe file, it will ask you to extract the contents into some temporary folder. Once the installation begins you can stick with the Express option:"
},
{
"code": null,
"e": 2527,
"s": 2457,
"text": "And after a couple of minutes, Nvidia CUDA Toolkit will be installed!"
},
{
"code": null,
"e": 2550,
"s": 2527,
"text": "Up next, Nvidia cuDNN."
},
{
"code": null,
"e": 2768,
"s": 2550,
"text": "Nvidia cuDNN is a GPU-accelerated library for deep neural networks. It can be downloaded from this link. Keep in mind that you will need to create an account, but you can just log in with Google and you’re good to go."
},
{
"code": null,
"e": 2868,
"s": 2768,
"text": "Upon login, you will be redirected to the page below — click on Download cuDNN 7.6.5 for CUDA 10.0:"
},
{
"code": null,
"e": 3072,
"s": 2868,
"text": "It is a ZIP file, maybe 250MB in size so it should download quickly. Once downloaded you can unzip the contents ̨(that is the 3 directories inside) to your CUDA installation directory — which will be in:"
},
{
"code": null,
"e": 3129,
"s": 3072,
"text": "C:\\Program Files\\Nvidia GPU Computing Toolkit\\CUDA\\v10.0"
},
{
"code": null,
"e": 3211,
"s": 3129,
"text": "if you haven’t changed anything upon the installation. And that’s it. Setup done!"
},
{
"code": null,
"e": 3395,
"s": 3211,
"text": "We’ve completed the tedious setup process, now it’s only time to do a simple pip install. By the time of writing this article, the latest GPU enabled TensorFlow version was 2.0.0 RC1."
},
{
"code": null,
"e": 3501,
"s": 3395,
"text": "To install it, open up the Command Prompt and execute the following (I assume you have Python installed):"
},
{
"code": null,
"e": 3538,
"s": 3501,
"text": "pip install tensorflow-gpu=2.0.0-rc1"
},
{
"code": null,
"e": 3624,
"s": 3538,
"text": "If you fail to provide the version it will install version 1.14, which we don’t want."
},
{
"code": null,
"e": 3779,
"s": 3624,
"text": "And that’s it, it will take some time to download (300+ MB), but TensorFlow should now be installed on your machine. Let’s just quickly verify that claim:"
},
{
"code": null,
"e": 4006,
"s": 3779,
"text": "As you can see, I opened the Python shell inside the Command Prompt, imported TensorFlow and checked if GPU is available. The function called return True, and you can also see my GPU colored yellow on the bottom of the prompt."
},
{
"code": null,
"e": 4224,
"s": 4006,
"text": "Having a thin and light laptop is nice — you can go anywhere without messing up your back. But what’s even cooler than not having back issues is having a powerful laptop capable of training neural networks on the GPU."
},
{
"code": null,
"e": 4394,
"s": 4224,
"text": "This article shouldn’t take you more than 5 minutes to read front to back, and 15 minutes to install and configure everything, provided you have a decent internet speed."
},
{
"code": null,
"e": 4440,
"s": 4394,
"text": "Thanks for reading. Have fun — I know I will."
}
] |
Batch Script - Devices | Windows now has an improved library which can be used in Batch Script for working with devices attached to the system. This is known as the device console – DevCon.exe.
Windows driver developers and testers can use DevCon to verify that a driver is installed and configured correctly, including the proper INF files, driver stack, driver files, and driver package. You can also use the DevCon commands (enable, disable, install, start, stop, and continue) in scripts to test the driver. DevCon is a command-line tool that performs device management functions on local computers and remote computers.
Display driver and device info DevCon can display the following properties of drivers and devices on local computers, and remote computers (running Windows XP and earlier) −
Hardware IDs, compatible IDs, and device instance IDs. These identifiers are described in detail in device identification strings.
Hardware IDs, compatible IDs, and device instance IDs. These identifiers are described in detail in device identification strings.
Device setup classes.
Device setup classes.
The devices in a device setup class.
The devices in a device setup class.
INF files and device driver files.
INF files and device driver files.
Details of driver packages.
Details of driver packages.
Hardware resources.
Hardware resources.
Device status.
Device status.
Expected driver stack.
Expected driver stack.
Third-party driver packages in the driver store.
Third-party driver packages in the driver store.
Search for devices DevCon can search for installed and uninstalled devices on a local or remote computer by hardware ID, device instance ID, or device setup class.
Search for devices DevCon can search for installed and uninstalled devices on a local or remote computer by hardware ID, device instance ID, or device setup class.
Change device settings DevCon can change the status or configuration of Plug and Play (PnP) devices on the local computer in the following ways −
Enable a device.
Disable a device.
Update drivers (interactive and non-interactive).
Install a device (create a devnode and install software).
Remove a device from the device tree and delete its device stack.
Rescan for Plug and Play devices.
Add, delete, and reorder the hardware IDs of root-enumerated devices.
Change the upper and lower filter drivers for a device setup class.
Add and delete third-party driver packages from the driver store.
Change device settings DevCon can change the status or configuration of Plug and Play (PnP) devices on the local computer in the following ways −
Enable a device.
Enable a device.
Disable a device.
Disable a device.
Update drivers (interactive and non-interactive).
Update drivers (interactive and non-interactive).
Install a device (create a devnode and install software).
Install a device (create a devnode and install software).
Remove a device from the device tree and delete its device stack.
Remove a device from the device tree and delete its device stack.
Rescan for Plug and Play devices.
Rescan for Plug and Play devices.
Add, delete, and reorder the hardware IDs of root-enumerated devices.
Add, delete, and reorder the hardware IDs of root-enumerated devices.
Change the upper and lower filter drivers for a device setup class.
Change the upper and lower filter drivers for a device setup class.
Add and delete third-party driver packages from the driver store.
Add and delete third-party driver packages from the driver store.
DevCon (DevCon.exe) is included when you install the WDK, Visual Studio, and the Windows SDK for desktop apps. DevCon.exe kit is available in the following locations when installed.
%WindowsSdkDir%\tools\x64\devcon.exe
%WindowsSdkDir%\tools\x86\devcon.exe
%WindowsSdkDir%\tools\arm\devcon.exe
devcon [/m:\\computer] [/r] command [arguments]
wherein
/m:\\computer − Runs the command on the specified remote computer. The backslashes are required.
/m:\\computer − Runs the command on the specified remote computer. The backslashes are required.
/r − Conditional reboot. Reboots the system after completing an operation only if a reboot is required to make a change effective.
/r − Conditional reboot. Reboots the system after completing an operation only if a reboot is required to make a change effective.
command − Specifies a DevCon command.
command − Specifies a DevCon command.
To list and display information about devices on the computer, use the following commands −
DevCon HwIDs
DevCon Classes
DevCon ListClass
DevCon DriverFiles
DevCon DriverNodes
DevCon Resources
DevCon Stack
DevCon Status
DevCon Dp_enum
To list and display information about devices on the computer, use the following commands −
DevCon HwIDs
DevCon HwIDs
DevCon Classes
DevCon Classes
DevCon ListClass
DevCon ListClass
DevCon DriverFiles
DevCon DriverFiles
DevCon DriverNodes
DevCon DriverNodes
DevCon Resources
DevCon Resources
DevCon Stack
DevCon Stack
DevCon Status
DevCon Status
DevCon Dp_enum
DevCon Dp_enum
To search for information about devices on the computer, use the following commands −
DevCon Find
DevCon FindAll
To search for information about devices on the computer, use the following commands −
DevCon Find
DevCon Find
DevCon FindAll
DevCon FindAll
To manipulate the device or change its configuration, use the following commands −
DevCon Enable
DevCon Disable
DevCon Update
DevCon UpdateNI
DevCon Install
DevCon Remove
DevCon Rescan
DevCon Restart
DevCon Reboot
DevCon SetHwID
DevCon ClassFilter
DevCon Dp_add
DevCon Dp_delete
To manipulate the device or change its configuration, use the following commands −
DevCon Enable
DevCon Enable
DevCon Disable
DevCon Disable
DevCon Update
DevCon Update
DevCon UpdateNI
DevCon UpdateNI
DevCon Install
DevCon Install
DevCon Remove
DevCon Remove
DevCon Rescan
DevCon Rescan
DevCon Restart
DevCon Restart
DevCon Reboot
DevCon Reboot
DevCon SetHwID
DevCon SetHwID
DevCon ClassFilter
DevCon ClassFilter
DevCon Dp_add
DevCon Dp_add
DevCon Dp_delete
DevCon Dp_delete
Following are some examples on how the DevCon command is used.
List all driver files
The following command uses the DevCon DriverFiles operation to list the file names of drivers that devices on the system use. The command uses the wildcard character (*) to indicate all devices on the system. Because the output is extensive, the command uses the redirection character (>) to redirect the output to a reference file, driverfiles.txt.
devcon driverfiles * > driverfiles.txt
The following command uses the DevCon status operation to find the status of all devices on the local computer. It then saves the status in the status.txt file for logging or later review. The command uses the wildcard character (*) to represent all devices and the redirection character (>) to redirect the output to the status.txt file.
devcon status * > status.txt
The following command enables all printer devices on the computer by specifying the Printer setup class in a DevCon Enable command. The command includes the /r parameter, which reboots the system if it is necessary to make the enabling effective.
devcon /r enable = Printer
The following command uses the DevCon Install operation to install a keyboard device on the local computer. The command includes the full path to the INF file for the device (keyboard.inf) and a hardware ID (*PNP030b).
devcon /r install c:\windows\inf\keyboard.inf *PNP030b
The following command will scan the computer for new devices.
devcon scan
The following command will rescan the computer for new devices.
devcon rescan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2338,
"s": 2169,
"text": "Windows now has an improved library which can be used in Batch Script for working with devices attached to the system. This is known as the device console – DevCon.exe."
},
{
"code": null,
"e": 2769,
"s": 2338,
"text": "Windows driver developers and testers can use DevCon to verify that a driver is installed and configured correctly, including the proper INF files, driver stack, driver files, and driver package. You can also use the DevCon commands (enable, disable, install, start, stop, and continue) in scripts to test the driver. DevCon is a command-line tool that performs device management functions on local computers and remote computers."
},
{
"code": null,
"e": 2943,
"s": 2769,
"text": "Display driver and device info DevCon can display the following properties of drivers and devices on local computers, and remote computers (running Windows XP and earlier) −"
},
{
"code": null,
"e": 3074,
"s": 2943,
"text": "Hardware IDs, compatible IDs, and device instance IDs. These identifiers are described in detail in device identification strings."
},
{
"code": null,
"e": 3205,
"s": 3074,
"text": "Hardware IDs, compatible IDs, and device instance IDs. These identifiers are described in detail in device identification strings."
},
{
"code": null,
"e": 3227,
"s": 3205,
"text": "Device setup classes."
},
{
"code": null,
"e": 3249,
"s": 3227,
"text": "Device setup classes."
},
{
"code": null,
"e": 3286,
"s": 3249,
"text": "The devices in a device setup class."
},
{
"code": null,
"e": 3323,
"s": 3286,
"text": "The devices in a device setup class."
},
{
"code": null,
"e": 3358,
"s": 3323,
"text": "INF files and device driver files."
},
{
"code": null,
"e": 3393,
"s": 3358,
"text": "INF files and device driver files."
},
{
"code": null,
"e": 3421,
"s": 3393,
"text": "Details of driver packages."
},
{
"code": null,
"e": 3449,
"s": 3421,
"text": "Details of driver packages."
},
{
"code": null,
"e": 3469,
"s": 3449,
"text": "Hardware resources."
},
{
"code": null,
"e": 3489,
"s": 3469,
"text": "Hardware resources."
},
{
"code": null,
"e": 3504,
"s": 3489,
"text": "Device status."
},
{
"code": null,
"e": 3519,
"s": 3504,
"text": "Device status."
},
{
"code": null,
"e": 3542,
"s": 3519,
"text": "Expected driver stack."
},
{
"code": null,
"e": 3565,
"s": 3542,
"text": "Expected driver stack."
},
{
"code": null,
"e": 3614,
"s": 3565,
"text": "Third-party driver packages in the driver store."
},
{
"code": null,
"e": 3663,
"s": 3614,
"text": "Third-party driver packages in the driver store."
},
{
"code": null,
"e": 3827,
"s": 3663,
"text": "Search for devices DevCon can search for installed and uninstalled devices on a local or remote computer by hardware ID, device instance ID, or device setup class."
},
{
"code": null,
"e": 3991,
"s": 3827,
"text": "Search for devices DevCon can search for installed and uninstalled devices on a local or remote computer by hardware ID, device instance ID, or device setup class."
},
{
"code": null,
"e": 4587,
"s": 3991,
"text": "Change device settings DevCon can change the status or configuration of Plug and Play (PnP) devices on the local computer in the following ways −\n\nEnable a device.\nDisable a device.\nUpdate drivers (interactive and non-interactive).\nInstall a device (create a devnode and install software).\nRemove a device from the device tree and delete its device stack.\nRescan for Plug and Play devices.\nAdd, delete, and reorder the hardware IDs of root-enumerated devices.\nChange the upper and lower filter drivers for a device setup class.\nAdd and delete third-party driver packages from the driver store.\n\n"
},
{
"code": null,
"e": 4733,
"s": 4587,
"text": "Change device settings DevCon can change the status or configuration of Plug and Play (PnP) devices on the local computer in the following ways −"
},
{
"code": null,
"e": 4750,
"s": 4733,
"text": "Enable a device."
},
{
"code": null,
"e": 4767,
"s": 4750,
"text": "Enable a device."
},
{
"code": null,
"e": 4785,
"s": 4767,
"text": "Disable a device."
},
{
"code": null,
"e": 4803,
"s": 4785,
"text": "Disable a device."
},
{
"code": null,
"e": 4853,
"s": 4803,
"text": "Update drivers (interactive and non-interactive)."
},
{
"code": null,
"e": 4903,
"s": 4853,
"text": "Update drivers (interactive and non-interactive)."
},
{
"code": null,
"e": 4961,
"s": 4903,
"text": "Install a device (create a devnode and install software)."
},
{
"code": null,
"e": 5019,
"s": 4961,
"text": "Install a device (create a devnode and install software)."
},
{
"code": null,
"e": 5085,
"s": 5019,
"text": "Remove a device from the device tree and delete its device stack."
},
{
"code": null,
"e": 5151,
"s": 5085,
"text": "Remove a device from the device tree and delete its device stack."
},
{
"code": null,
"e": 5185,
"s": 5151,
"text": "Rescan for Plug and Play devices."
},
{
"code": null,
"e": 5219,
"s": 5185,
"text": "Rescan for Plug and Play devices."
},
{
"code": null,
"e": 5289,
"s": 5219,
"text": "Add, delete, and reorder the hardware IDs of root-enumerated devices."
},
{
"code": null,
"e": 5359,
"s": 5289,
"text": "Add, delete, and reorder the hardware IDs of root-enumerated devices."
},
{
"code": null,
"e": 5427,
"s": 5359,
"text": "Change the upper and lower filter drivers for a device setup class."
},
{
"code": null,
"e": 5495,
"s": 5427,
"text": "Change the upper and lower filter drivers for a device setup class."
},
{
"code": null,
"e": 5561,
"s": 5495,
"text": "Add and delete third-party driver packages from the driver store."
},
{
"code": null,
"e": 5627,
"s": 5561,
"text": "Add and delete third-party driver packages from the driver store."
},
{
"code": null,
"e": 5809,
"s": 5627,
"text": "DevCon (DevCon.exe) is included when you install the WDK, Visual Studio, and the Windows SDK for desktop apps. DevCon.exe kit is available in the following locations when installed."
},
{
"code": null,
"e": 5921,
"s": 5809,
"text": "%WindowsSdkDir%\\tools\\x64\\devcon.exe\n%WindowsSdkDir%\\tools\\x86\\devcon.exe\n%WindowsSdkDir%\\tools\\arm\\devcon.exe\n"
},
{
"code": null,
"e": 5970,
"s": 5921,
"text": "devcon [/m:\\\\computer] [/r] command [arguments]\n"
},
{
"code": null,
"e": 5978,
"s": 5970,
"text": "wherein"
},
{
"code": null,
"e": 6075,
"s": 5978,
"text": "/m:\\\\computer − Runs the command on the specified remote computer. The backslashes are required."
},
{
"code": null,
"e": 6172,
"s": 6075,
"text": "/m:\\\\computer − Runs the command on the specified remote computer. The backslashes are required."
},
{
"code": null,
"e": 6303,
"s": 6172,
"text": "/r − Conditional reboot. Reboots the system after completing an operation only if a reboot is required to make a change effective."
},
{
"code": null,
"e": 6434,
"s": 6303,
"text": "/r − Conditional reboot. Reboots the system after completing an operation only if a reboot is required to make a change effective."
},
{
"code": null,
"e": 6472,
"s": 6434,
"text": "command − Specifies a DevCon command."
},
{
"code": null,
"e": 6510,
"s": 6472,
"text": "command − Specifies a DevCon command."
},
{
"code": null,
"e": 6747,
"s": 6510,
"text": "To list and display information about devices on the computer, use the following commands −\n\nDevCon HwIDs\nDevCon Classes\nDevCon ListClass\nDevCon DriverFiles\nDevCon DriverNodes\nDevCon Resources\nDevCon Stack\nDevCon Status\nDevCon Dp_enum\n\n"
},
{
"code": null,
"e": 6839,
"s": 6747,
"text": "To list and display information about devices on the computer, use the following commands −"
},
{
"code": null,
"e": 6852,
"s": 6839,
"text": "DevCon HwIDs"
},
{
"code": null,
"e": 6865,
"s": 6852,
"text": "DevCon HwIDs"
},
{
"code": null,
"e": 6880,
"s": 6865,
"text": "DevCon Classes"
},
{
"code": null,
"e": 6895,
"s": 6880,
"text": "DevCon Classes"
},
{
"code": null,
"e": 6912,
"s": 6895,
"text": "DevCon ListClass"
},
{
"code": null,
"e": 6929,
"s": 6912,
"text": "DevCon ListClass"
},
{
"code": null,
"e": 6948,
"s": 6929,
"text": "DevCon DriverFiles"
},
{
"code": null,
"e": 6967,
"s": 6948,
"text": "DevCon DriverFiles"
},
{
"code": null,
"e": 6986,
"s": 6967,
"text": "DevCon DriverNodes"
},
{
"code": null,
"e": 7005,
"s": 6986,
"text": "DevCon DriverNodes"
},
{
"code": null,
"e": 7022,
"s": 7005,
"text": "DevCon Resources"
},
{
"code": null,
"e": 7039,
"s": 7022,
"text": "DevCon Resources"
},
{
"code": null,
"e": 7052,
"s": 7039,
"text": "DevCon Stack"
},
{
"code": null,
"e": 7065,
"s": 7052,
"text": "DevCon Stack"
},
{
"code": null,
"e": 7079,
"s": 7065,
"text": "DevCon Status"
},
{
"code": null,
"e": 7093,
"s": 7079,
"text": "DevCon Status"
},
{
"code": null,
"e": 7108,
"s": 7093,
"text": "DevCon Dp_enum"
},
{
"code": null,
"e": 7123,
"s": 7108,
"text": "DevCon Dp_enum"
},
{
"code": null,
"e": 7239,
"s": 7123,
"text": "To search for information about devices on the computer, use the following commands −\n\nDevCon Find\nDevCon FindAll\n\n"
},
{
"code": null,
"e": 7325,
"s": 7239,
"text": "To search for information about devices on the computer, use the following commands −"
},
{
"code": null,
"e": 7337,
"s": 7325,
"text": "DevCon Find"
},
{
"code": null,
"e": 7349,
"s": 7337,
"text": "DevCon Find"
},
{
"code": null,
"e": 7364,
"s": 7349,
"text": "DevCon FindAll"
},
{
"code": null,
"e": 7379,
"s": 7364,
"text": "DevCon FindAll"
},
{
"code": null,
"e": 7661,
"s": 7379,
"text": "To manipulate the device or change its configuration, use the following commands −\n\nDevCon Enable\nDevCon Disable\nDevCon Update\nDevCon UpdateNI\nDevCon Install\nDevCon Remove\nDevCon Rescan\nDevCon Restart\nDevCon Reboot\nDevCon SetHwID\nDevCon ClassFilter\nDevCon Dp_add\nDevCon Dp_delete\n\n"
},
{
"code": null,
"e": 7744,
"s": 7661,
"text": "To manipulate the device or change its configuration, use the following commands −"
},
{
"code": null,
"e": 7758,
"s": 7744,
"text": "DevCon Enable"
},
{
"code": null,
"e": 7772,
"s": 7758,
"text": "DevCon Enable"
},
{
"code": null,
"e": 7787,
"s": 7772,
"text": "DevCon Disable"
},
{
"code": null,
"e": 7802,
"s": 7787,
"text": "DevCon Disable"
},
{
"code": null,
"e": 7816,
"s": 7802,
"text": "DevCon Update"
},
{
"code": null,
"e": 7830,
"s": 7816,
"text": "DevCon Update"
},
{
"code": null,
"e": 7846,
"s": 7830,
"text": "DevCon UpdateNI"
},
{
"code": null,
"e": 7862,
"s": 7846,
"text": "DevCon UpdateNI"
},
{
"code": null,
"e": 7877,
"s": 7862,
"text": "DevCon Install"
},
{
"code": null,
"e": 7892,
"s": 7877,
"text": "DevCon Install"
},
{
"code": null,
"e": 7906,
"s": 7892,
"text": "DevCon Remove"
},
{
"code": null,
"e": 7920,
"s": 7906,
"text": "DevCon Remove"
},
{
"code": null,
"e": 7934,
"s": 7920,
"text": "DevCon Rescan"
},
{
"code": null,
"e": 7948,
"s": 7934,
"text": "DevCon Rescan"
},
{
"code": null,
"e": 7963,
"s": 7948,
"text": "DevCon Restart"
},
{
"code": null,
"e": 7978,
"s": 7963,
"text": "DevCon Restart"
},
{
"code": null,
"e": 7992,
"s": 7978,
"text": "DevCon Reboot"
},
{
"code": null,
"e": 8006,
"s": 7992,
"text": "DevCon Reboot"
},
{
"code": null,
"e": 8021,
"s": 8006,
"text": "DevCon SetHwID"
},
{
"code": null,
"e": 8036,
"s": 8021,
"text": "DevCon SetHwID"
},
{
"code": null,
"e": 8055,
"s": 8036,
"text": "DevCon ClassFilter"
},
{
"code": null,
"e": 8074,
"s": 8055,
"text": "DevCon ClassFilter"
},
{
"code": null,
"e": 8088,
"s": 8074,
"text": "DevCon Dp_add"
},
{
"code": null,
"e": 8102,
"s": 8088,
"text": "DevCon Dp_add"
},
{
"code": null,
"e": 8119,
"s": 8102,
"text": "DevCon Dp_delete"
},
{
"code": null,
"e": 8136,
"s": 8119,
"text": "DevCon Dp_delete"
},
{
"code": null,
"e": 8199,
"s": 8136,
"text": "Following are some examples on how the DevCon command is used."
},
{
"code": null,
"e": 8222,
"s": 8199,
"text": "List all driver files\n"
},
{
"code": null,
"e": 8572,
"s": 8222,
"text": "The following command uses the DevCon DriverFiles operation to list the file names of drivers that devices on the system use. The command uses the wildcard character (*) to indicate all devices on the system. Because the output is extensive, the command uses the redirection character (>) to redirect the output to a reference file, driverfiles.txt."
},
{
"code": null,
"e": 8612,
"s": 8572,
"text": "devcon driverfiles * > driverfiles.txt\n"
},
{
"code": null,
"e": 8951,
"s": 8612,
"text": "The following command uses the DevCon status operation to find the status of all devices on the local computer. It then saves the status in the status.txt file for logging or later review. The command uses the wildcard character (*) to represent all devices and the redirection character (>) to redirect the output to the status.txt file."
},
{
"code": null,
"e": 8981,
"s": 8951,
"text": "devcon status * > status.txt\n"
},
{
"code": null,
"e": 9228,
"s": 8981,
"text": "The following command enables all printer devices on the computer by specifying the Printer setup class in a DevCon Enable command. The command includes the /r parameter, which reboots the system if it is necessary to make the enabling effective."
},
{
"code": null,
"e": 9256,
"s": 9228,
"text": "devcon /r enable = Printer\n"
},
{
"code": null,
"e": 9475,
"s": 9256,
"text": "The following command uses the DevCon Install operation to install a keyboard device on the local computer. The command includes the full path to the INF file for the device (keyboard.inf) and a hardware ID (*PNP030b)."
},
{
"code": null,
"e": 9531,
"s": 9475,
"text": "devcon /r install c:\\windows\\inf\\keyboard.inf *PNP030b\n"
},
{
"code": null,
"e": 9593,
"s": 9531,
"text": "The following command will scan the computer for new devices."
},
{
"code": null,
"e": 9606,
"s": 9593,
"text": "devcon scan\n"
},
{
"code": null,
"e": 9670,
"s": 9606,
"text": "The following command will rescan the computer for new devices."
},
{
"code": null,
"e": 9685,
"s": 9670,
"text": "devcon rescan\n"
},
{
"code": null,
"e": 9692,
"s": 9685,
"text": " Print"
},
{
"code": null,
"e": 9703,
"s": 9692,
"text": " Add Notes"
}
] |
How to switch back from a frame to default in Selenium Webdriver? | We can switch back from a frame to default in Selenium webdriver using the switchTo().defaultContent() method. Initially, the webdriver control remains on the main web page.
In order to access elements within the frame, we have to shift the control from the main page to the frame with the help of the switchTo().frame and pass the frame name/id or webelement of the frame as a parameter to that method.
Finally, again we can switch the control to the main page with the switchTo().defaultContent() method. A frame is identified in the html code with the tag names – frame, iframe or frameset.
Let us identify the text Iframe which is inside a frame and the text click on the below link − which is outside a frame
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class FrameDefaultSwitch{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("http://www.uitestpractice.com/Students/Switchto");
// switch to frame
driver.switchTo().frame("iframe_a");
//identify element inside frame
WebElement d = driver.findElement(By.tagName("h1"));
System.out.println("Text inside frame: " + d.getText());
//switch to default
driver.switchTo().defaultContent();
//identify element outside frame
WebElement e = driver.findElement(By.tagName("h3"));
System.out.println("Text outside frame: " + e.getText());
driver.quit();}
} | [
{
"code": null,
"e": 1236,
"s": 1062,
"text": "We can switch back from a frame to default in Selenium webdriver using the switchTo().defaultContent() method. Initially, the webdriver control remains on the main web page."
},
{
"code": null,
"e": 1466,
"s": 1236,
"text": "In order to access elements within the frame, we have to shift the control from the main page to the frame with the help of the switchTo().frame and pass the frame name/id or webelement of the frame as a parameter to that method."
},
{
"code": null,
"e": 1656,
"s": 1466,
"text": "Finally, again we can switch the control to the main page with the switchTo().defaultContent() method. A frame is identified in the html code with the tag names – frame, iframe or frameset."
},
{
"code": null,
"e": 1776,
"s": 1656,
"text": "Let us identify the text Iframe which is inside a frame and the text click on the below link − which is outside a frame"
},
{
"code": null,
"e": 2815,
"s": 1776,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class FrameDefaultSwitch{\npublic static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"http://www.uitestpractice.com/Students/Switchto\");\n // switch to frame\n driver.switchTo().frame(\"iframe_a\");\n //identify element inside frame\n WebElement d = driver.findElement(By.tagName(\"h1\"));\n System.out.println(\"Text inside frame: \" + d.getText());\n //switch to default\n driver.switchTo().defaultContent();\n //identify element outside frame\n WebElement e = driver.findElement(By.tagName(\"h3\"));\n System.out.println(\"Text outside frame: \" + e.getText());\n driver.quit();}\n}"
}
] |
scipy stats.skew() | Python - GeeksforGeeks | 11 Feb, 2019
scipy.stats.skew(array, axis=0, bias=True) function calculates the skewness of the data set.
skewness = 0 : normally distributed.
skewness > 0 : more weight in the left tail of the distribution.
skewness < 0 : more weight in the right tail of the distribution.
Its formula –
Parameters :array : Input array or object having the elements.axis : Axis along which the skewness value is to be measured. By default axis = 0.bias : Bool; calculations are corrected for statistical bias, if set to False.
Returns : Skewness value of the data set, along the axis.
Code #1:
# Graph using numpy.linspace() # finding Skewness from scipy.stats import skewimport numpy as np import pylab as p x1 = np.linspace( -5, 5, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2 ) p.plot(x1, y1, '*') print( '\nSkewness for data : ', skew(y1))
Output :
Skewness for data : 1.1108237139164436
Code #2:
# Graph using numpy.linspace() # finding Skewness from scipy.stats import skewimport numpy as np import pylab as p x1 = np.linspace( -5, 12, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2 ) p.plot(x1, y1, '.') print( '\nSkewness for data : ', skew(y1))
Output :
Skewness for data : 1.917677776148478
Code #3: On Random data
# finding Skewness from scipy.stats import skewimport numpy as np # random values based on a normal distributionx = np.random.normal(0, 2, 10000) print ("X : \n", x) print('\nSkewness for data : ', skew(x))
Output :
X :
[ 0.03255323 -6.18574775 -0.58430139 ... 3.22112446 1.16543279
0.84083317]
Skewness for data : 0.03248837584866293
Python scipy-stats-functions
Python-scipy
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
Read a file line by line in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Stack in Python
Bar Plot in Matplotlib
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24762,
"s": 24734,
"text": "\n11 Feb, 2019"
},
{
"code": null,
"e": 24855,
"s": 24762,
"text": "scipy.stats.skew(array, axis=0, bias=True) function calculates the skewness of the data set."
},
{
"code": null,
"e": 25025,
"s": 24855,
"text": "skewness = 0 : normally distributed.\nskewness > 0 : more weight in the left tail of the distribution.\nskewness < 0 : more weight in the right tail of the distribution. \n"
},
{
"code": null,
"e": 25039,
"s": 25025,
"text": "Its formula –"
},
{
"code": null,
"e": 25262,
"s": 25039,
"text": "Parameters :array : Input array or object having the elements.axis : Axis along which the skewness value is to be measured. By default axis = 0.bias : Bool; calculations are corrected for statistical bias, if set to False."
},
{
"code": null,
"e": 25320,
"s": 25262,
"text": "Returns : Skewness value of the data set, along the axis."
},
{
"code": null,
"e": 25329,
"s": 25320,
"text": "Code #1:"
},
{
"code": "# Graph using numpy.linspace() # finding Skewness from scipy.stats import skewimport numpy as np import pylab as p x1 = np.linspace( -5, 5, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2 ) p.plot(x1, y1, '*') print( '\\nSkewness for data : ', skew(y1))",
"e": 25596,
"s": 25329,
"text": null
},
{
"code": null,
"e": 25605,
"s": 25596,
"text": "Output :"
},
{
"code": null,
"e": 25647,
"s": 25605,
"text": "\n\nSkewness for data : 1.1108237139164436\n"
},
{
"code": null,
"e": 25657,
"s": 25647,
"text": " Code #2:"
},
{
"code": "# Graph using numpy.linspace() # finding Skewness from scipy.stats import skewimport numpy as np import pylab as p x1 = np.linspace( -5, 12, 1000 )y1 = 1./(np.sqrt(2.*np.pi)) * np.exp( -.5*(x1)**2 ) p.plot(x1, y1, '.') print( '\\nSkewness for data : ', skew(y1))",
"e": 25927,
"s": 25657,
"text": null
},
{
"code": null,
"e": 25936,
"s": 25927,
"text": "Output :"
},
{
"code": null,
"e": 25977,
"s": 25936,
"text": "\n\nSkewness for data : 1.917677776148478\n"
},
{
"code": null,
"e": 26002,
"s": 25977,
"text": " Code #3: On Random data"
},
{
"code": "# finding Skewness from scipy.stats import skewimport numpy as np # random values based on a normal distributionx = np.random.normal(0, 2, 10000) print (\"X : \\n\", x) print('\\nSkewness for data : ', skew(x))",
"e": 26214,
"s": 26002,
"text": null
},
{
"code": null,
"e": 26223,
"s": 26214,
"text": "Output :"
},
{
"code": null,
"e": 26351,
"s": 26223,
"text": "X : \n [ 0.03255323 -6.18574775 -0.58430139 ... 3.22112446 1.16543279\n 0.84083317]\n\nSkewness for data : 0.03248837584866293\n"
},
{
"code": null,
"e": 26380,
"s": 26351,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 26393,
"s": 26380,
"text": "Python-scipy"
},
{
"code": null,
"e": 26400,
"s": 26393,
"text": "Python"
},
{
"code": null,
"e": 26498,
"s": 26400,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26507,
"s": 26498,
"text": "Comments"
},
{
"code": null,
"e": 26520,
"s": 26507,
"text": "Old Comments"
},
{
"code": null,
"e": 26538,
"s": 26520,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26560,
"s": 26538,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26595,
"s": 26560,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26616,
"s": 26595,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26658,
"s": 26616,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26683,
"s": 26658,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26715,
"s": 26683,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26731,
"s": 26715,
"text": "Stack in Python"
},
{
"code": null,
"e": 26754,
"s": 26731,
"text": "Bar Plot in Matplotlib"
}
] |
R Shiny authentication (incl. demo app) | by Thomas Filaire | Towards Data Science | Shiny is extremely powerful to quickly build interactive web applications. It’s also the preferred technological solution for many data scientists, because it’s R-native.
As not all web applications are meant to be public, the ability to control access should be part of the know-how of any aspiring data scientist.
This tutorial will introduce you to a few options to secure your Shiny apps through authentication layer.
Note: in order to get the most from this tutorial, interested reader should already be familiar with basic Shiny principles (e.g. reactivity, how to use a module), web development (e.g. html tags and css), and RStudio projects.
This tutorial comes with a R Shiny demo application which you can access here.
The complete code is also available on my bitbucket account.
This tutorial will cover several approaches to secure access to R Shiny web application.
First, I’ll cover the basics of authentication, building my own login form, making the app appear (and the login form disappear) in case of correct credentials provided by the user.Then, I’ll pack the login form and the corresponding server logic into a module. This will increase your application readability and maintainability, and make your login form easy to reuse across several applications.In a third step, I’ll leverage the shinyauthr package, which is basically an implementation of step 2 with a few additional functionalities, including password hashing (based on the sodium package).Lastly, I’ll briefly mention two other approaches.
First, I’ll cover the basics of authentication, building my own login form, making the app appear (and the login form disappear) in case of correct credentials provided by the user.
Then, I’ll pack the login form and the corresponding server logic into a module. This will increase your application readability and maintainability, and make your login form easy to reuse across several applications.
In a third step, I’ll leverage the shinyauthr package, which is basically an implementation of step 2 with a few additional functionalities, including password hashing (based on the sodium package).
Lastly, I’ll briefly mention two other approaches.
Note: for the sake of the demonstration, I created a table to store username and password straight from the Shiny server section. Keep in mind that credentials should be encrypted and stored in a database in the case of apps deployed in production (database connection is not covered in this particular post).
In this section, you will learn how to build your own login form, as show in the short illustration below:
I’ll cover both the design of the login form and the corresponding server logic. Code explanation is split into 3 steps:
Load required packages and build application backboneBuild your own, fully customizable, login formDefine server side
Load required packages and build application backbone
Build your own, fully customizable, login form
Define server side
I used the 4 following packages: shiny, shinythemes, shinyjs, and tidyverse
# 1 - SET THE SCENE# load required packages library(shiny) # web app framework library(shinyjs) # improve user experience with JavaScriptlibrary(shinythemes) # themes for shinylibrary(tidyverse) # data manipulation
Then I designed a simple application backbone using navbarPage:
# 2 - UI PART# app backboneui <- navbarPage( title = "R Shiny advanced tips series", collapsible = TRUE, windowTitle = "R Shiny tips - TFI", theme = shinytheme("readable"), tabPanel( title = "Demo", useShinyjs() # Include shinyjs ))# 3 - SERVER PARTserver <- function(input, output, session) {}# 4 - RUN APPshinyApp(ui = ui, server = server)
A login form requires the 3 following components:
a text input to capture user namea password input to capture password (similar to text input except that text is hidden)an action button to confirm/infirm access to the application
a text input to capture user name
a password input to capture password (similar to text input except that text is hidden)
an action button to confirm/infirm access to the application
Here is a simple code chunk you can adapt to your own preferences. In my case I mostly used basic bootstrap classes to make the text centered (“text-center”) and to add a light grey background to the login form (“well”).
Login form should be located in a dedicated div with class ‘container’.
Please also notice:
An id should be defined, so as to make the login form disappear in case of successful authentication. This part is defined just after in step 1.3
the use of the tagList() function to add an icon next to the text input and password input labels
div( id = "login-basic", style = "width: 500px; max-width: 100%; margin: 0 auto;", div( class = "well", h4(class = "text-center", "Please login"), p(class = "text-center", tags$small("First approach login form") ), textInput( inputId = "ti_user_name_basic", label = tagList(icon("user"), "User Name"), placeholder = "Enter user name" ), passwordInput( inputId = "ti_password_basic", label = tagList(icon("unlock-alt"), "Password"), placeholder = "Enter password" ), div( class = "text-center", actionButton( inputId = "ab_login_button_basic", label = "Log in", class = "btn-primary" ) ) ))
The server side is the place where developer can infuse intelligence into the application, define and control expected behaviors.
I first built a simple table to store users credential. In this example I granted access to only one user (“user_basic_1”), but you can of course define as many user x password combinations as you like.
# >> insert in server part# create userbaseuser_base_basic_tbl <- tibble( user_name = "user_basic_1", password = "pass_basic_1")
In a second step, I used the eventReactive() function to check user’s login and password against valid credentials (stored in the above userbase). This toggles a TRUE/FALSE boolean parameter accordingly as soon as user clicks the login button.
# >> insert in server part# check credentials vs tibblevalidate_password_basic <- eventReactive(input$ab_login_button_basic, { validate <- FALSE if (input$ti_user_name_basic == user_base_basic_tbl$user_name && input$ti_password_basic == user_base_basic_tbl$password {validate <- TRUE}})
Based on this boolean value:
Login form will hide, using the shinyjs::hide() function inside an observeEvent(). This requires an id to refer to the appropriate UI section to be hidden, thus my comment in step 1.2.Secured part of the app will appear, using a classic renderUI() + uiOutput() combination
Login form will hide, using the shinyjs::hide() function inside an observeEvent(). This requires an id to refer to the appropriate UI section to be hidden, thus my comment in step 1.2.
Secured part of the app will appear, using a classic renderUI() + uiOutput() combination
# >> insert in server part# hide form observeEvent(validate_password_basic(), { shinyjs::hide(id = "login-basic")})# show app output$display_content_basic <- renderUI({ req(validate_password_basic()) div( class = "bg-success", id = "success_basic", h4("Access confirmed!"), p("Welcome to your basically-secured application!") ) })
uiOutput should be inserted in the ui part
# app uiOutput(outputId = "display_content_basic")
Congratulations if you’ve been able to follow and reproduce this example so far. You’ve just built your first login component to secure your R Shiny application.
As this process requires a significant amount of code which makes your application harder to maintain on the long run, let’s package it into a module!
Now that you understand the basic underlying principles of authentication and that you have built your first login form, let’s make it more robust and easier to reuse across multiple applications. This can be achieved defining a dedicated module.
A Shiny module is a piece of a Shiny app. It can’t be directly run, as a Shiny app can. Instead, it is included as part of a larger app (or as part of a larger Shiny module — they are composable). — Wiston Chang — Software engineer, RStudio
Note: this tutorial will not cover in details how to create a module, and I assume the reader is somehow familiar with its key concept.
In a nutshell, a module is composed of two functions that represent 1) a piece of UI, and 2) a fragment of server logic that uses that UI — similar to the way that Shiny apps are split into UI and server logic.
View the short illustration below to get an idea of what will be built with this second approach; as you can see the UI part looks exactly the same as what I built in the first approach. However it differs under the hood:
Code explanation is split into 4 steps:
Build the moduleSource the moduleAdd login form + secured part of the app in the UI partDefine server side
Build the module
Source the module
Add login form + secured part of the app in the UI part
Define server side
This steps essentially consists in bringing together the custom UI and associated server logic I’ve implemented in the previous approach, into a single module_login.R file.
Key aspects to notice in the code chunk below:
UI part:
Use of NS(): All UI function bodies should start with this line when creating a module. It takes the string id and creates a namespace function. All id names must be encapsulated within ns(). More on this here for interested reader
The function takes another variable, title, to make it easy to customize login page title, should you need to use the module in the context of other future R Shiny applications
# UI componentlogin_ui <- function(id, title) { ns <- NS(id) # namespaced id # define ui part div( id = ns("login"), style = "width: 500px; max-width: 100%; margin: 0 auto;", div( class = "well", h4(class = "text-center", title), p(class = "text-center", tags$small("Second approach login form")), textInput( inputId = ns("ti_user_name_module"), label = tagList(icon("user"), "User Name"), placeholder = "Enter user name" ), passwordInput( inputId = ns("ti_password_module"), label = tagList( icon("unlock-alt"), "Password" ), placeholder = "Enter password" ), div( class = "text-center", actionButton( inputId = ns("ab_login_button_module"), label = "Log in", class = "btn-primary" ) ) ) )}
Server part:
use of {{ }} to use user-supplied expression within a function. More on this here for interested reader
call to shinyjs::hide() is embedded within the server part of the module, so there is no longer need to use an observeEvent as I did in the first approach
# SERVER componentvalidate_pwd <- function(input, output, session, data, user_col, pwd_col) { # get user and pwd from data/ user_col/ pwd_col information user <- data %>% pull({{ user_col }}) pwd <- data %>% pull({{ pwd_col }}) # check correctness eventReactive(input$ab_login_button_module, { validate <- FALSE if (input$ti_user_name_module == user && input$ti_password_module == pwd) { validate <- TRUE } # hide login form when user is confirmed if (validate) { shinyjs::hide(id = "login") } validate })}
Prior to using a particular module within your R Shiny application, be careful to source it appropriately (see my bitbucket account to understand the project structure):
# source module source("modules/module_login.R")
Both login form and secured part of your app can now be specified in the UI part with 2 lines of code, which ensure great readability and maintainability of your app on the long run.
# login form as defined in the modulelogin_ui(id = "module_login", title = "Please login"), # app uiOutput(outputId = "display_content_module")
This is very similar to section 1.3.
I first built a simple table to store users credential. In this illustration I granted access to only one user, but you can of course define as many user x password combinations as you like.
# >> insert in server part# create userbaseuser_base_module_tbl <- tibble( user_name = "user_module_1", password = "pass_module_1")
I then used the callModule() function to access the server side of my module, and passing information on where to search for login and passwords (via the data, user_col and pwd_col parameters to refer to the above userbase):
# check credentials vs tibble validate_password_module <- callModule( module = validate_pwd, id = "module_login", data = user_base_module_tbl, user_col = user_name, pwd_col = password)
Finally, and as in the first approach, I use a classic renderUI() + uiOutput() combination to display the secured part of the application whenever the boolean validate_password_module() defined above toggles appropriately:
# app output$display_content_module <- renderUI({ req(validate_password_module()) div( class = "bg-success", id = "success_module", h4("Access confirmed!"), p("Welcome to your module-secured application!") ) })
Congratulations if you’ve been able to follow and reproduce this example so far. You’ve been able to package your fully customizable login form into a module, which you can reuse with all your future web applications.
In the next section, we’ll leverage an existing module for authentication, available in the shinyauthr package. Main advantages compared to building your own module are:
No need for you to master the art of building modules, shinyauthr makes it ready for you to use
Ability to encrypt your password, via the sodium package. Sodium uses a hashing algorithm that is specifically designed to protect stored passwords from brute-force attacks
Shinyauthr is an R package providing module functions that can be used to add an authentication layer to your shiny apps. If you made it so far and successfully built your own module, this third approach should be easy to follow, and I recommend you use the package to speed up your future work.
View the short illustration below to get an idea of what will be built with this third approach; although it looks very similar to approaches 1 and 2, login form is slightly less customizable.
Code explanation below will specify new required packages, illustrate how to update the ui part and detail the server side. Remind that the entire code is available here.
In addition to the packages mentioned in previous approaches, you will need to load shinyauthr and sodium packages.
library(shinyauthr) # shiny authentication moduleslibrary(sodium) # crypto library
Both login form and secured part of your app can now be specified in the UI part with 2 lines of code, which ensure great readability and maintainability of your app on the long run.
loginUI() function from shinyauthr package is pretty similar to what you’ve built during second approach. Title (+ a few other parameters can be customized)
Secured part of the application is displayed through the uiOutput() function
# login formshinyauthr::loginUI( id = "authr_login", title = h4(class = "text-center", "Please login")), # app uiOutput(outputId = "display_content_authr"),
I first built a simple table to store users credential. In this illustration I granted access to only one user, but you can of course define as many user x password combinations as you like.
Notice the use of password_store() function from the sodium package to encrypt the password.
# >> insert in server part# create userbaseuuser_base_authr_tbl <- tibble( user_name = "user_authr_1", password = sodium::password_store("pass_authr_1"))
I then made a call to 2 modules that comes with the shinyauthr package (a login form + a logout form)
# >> insert in server partlogout_init <- callModule( module = shinyauthr::logout, id = "authr_logout", active = reactive(user_auth)) credentials <- callModule( module = shinyauthr::login, id = "authr_login", data = user_base_authr_tbl, user_col = user_name, pwd_col = password, sodium_hashed = TRUE, log_out = reactive(logout_init()))
When the login module is called, it returns a reactive list containing 2 elements:
user_auth (initial value is FALSE)
info (initial value is NULL)
I create reactive object on the server side to capture changes in these values (in particular, user_auth turns TRUE if the user supplies a matching user name and password.)
# >> insert in server partuser_auth <- reactive({ credentials()$user_auth}) user_data <- reactive({ credentials()$info})
Lastly, I need to define the secured part of the application within a renderUI() function, similarly to previous approaches.
# >> insert in server partoutput$display_content_authr <- renderUI({ req(user_auth()) div( class = "bg-success", id = "success_module", h4("Access confirmed!"), p("Welcome to your shinyauthr-secured application! Notice that password is encrypted.") ) })
Congratulations if you’ve made it this far, you are now equipped with a fast, powerful and easy way to secure your applications!
I usually implement one of the 3 above detailed approches.
However they are not the only ones and you might be interested in exploring other alternatives, such as:
shinymanager (very similar to shinyauthr)
polished a non-free solution providing you with several additional features on top of authentication, such as: custom login page, user management, single sign on, or user monitoring
I hope you found this tutorial useful, please feel free to leave comment to share your preferred (and possibly alternative) approach.
Want to learn more? This article is the second one of my advanced R Shiny tips series. First post is about building dynamic UI components.
shinymanager: simple and secure authentication mechanism for single Shiny applications.
shinyauthr: R package providing module functions that can be used to add an authentication layer to your shiny apps
polished: add authentication to your Shiny applications
Mastering Shiny: This book complements Shiny’s online documentation and is intended to help app authors develop a deeper understanding of Shiny
Business Science 202A — Build scalable applications using R: a great online courses | [
{
"code": null,
"e": 342,
"s": 171,
"text": "Shiny is extremely powerful to quickly build interactive web applications. It’s also the preferred technological solution for many data scientists, because it’s R-native."
},
{
"code": null,
"e": 487,
"s": 342,
"text": "As not all web applications are meant to be public, the ability to control access should be part of the know-how of any aspiring data scientist."
},
{
"code": null,
"e": 593,
"s": 487,
"text": "This tutorial will introduce you to a few options to secure your Shiny apps through authentication layer."
},
{
"code": null,
"e": 821,
"s": 593,
"text": "Note: in order to get the most from this tutorial, interested reader should already be familiar with basic Shiny principles (e.g. reactivity, how to use a module), web development (e.g. html tags and css), and RStudio projects."
},
{
"code": null,
"e": 900,
"s": 821,
"text": "This tutorial comes with a R Shiny demo application which you can access here."
},
{
"code": null,
"e": 961,
"s": 900,
"text": "The complete code is also available on my bitbucket account."
},
{
"code": null,
"e": 1050,
"s": 961,
"text": "This tutorial will cover several approaches to secure access to R Shiny web application."
},
{
"code": null,
"e": 1697,
"s": 1050,
"text": "First, I’ll cover the basics of authentication, building my own login form, making the app appear (and the login form disappear) in case of correct credentials provided by the user.Then, I’ll pack the login form and the corresponding server logic into a module. This will increase your application readability and maintainability, and make your login form easy to reuse across several applications.In a third step, I’ll leverage the shinyauthr package, which is basically an implementation of step 2 with a few additional functionalities, including password hashing (based on the sodium package).Lastly, I’ll briefly mention two other approaches."
},
{
"code": null,
"e": 1879,
"s": 1697,
"text": "First, I’ll cover the basics of authentication, building my own login form, making the app appear (and the login form disappear) in case of correct credentials provided by the user."
},
{
"code": null,
"e": 2097,
"s": 1879,
"text": "Then, I’ll pack the login form and the corresponding server logic into a module. This will increase your application readability and maintainability, and make your login form easy to reuse across several applications."
},
{
"code": null,
"e": 2296,
"s": 2097,
"text": "In a third step, I’ll leverage the shinyauthr package, which is basically an implementation of step 2 with a few additional functionalities, including password hashing (based on the sodium package)."
},
{
"code": null,
"e": 2347,
"s": 2296,
"text": "Lastly, I’ll briefly mention two other approaches."
},
{
"code": null,
"e": 2657,
"s": 2347,
"text": "Note: for the sake of the demonstration, I created a table to store username and password straight from the Shiny server section. Keep in mind that credentials should be encrypted and stored in a database in the case of apps deployed in production (database connection is not covered in this particular post)."
},
{
"code": null,
"e": 2764,
"s": 2657,
"text": "In this section, you will learn how to build your own login form, as show in the short illustration below:"
},
{
"code": null,
"e": 2885,
"s": 2764,
"text": "I’ll cover both the design of the login form and the corresponding server logic. Code explanation is split into 3 steps:"
},
{
"code": null,
"e": 3003,
"s": 2885,
"text": "Load required packages and build application backboneBuild your own, fully customizable, login formDefine server side"
},
{
"code": null,
"e": 3057,
"s": 3003,
"text": "Load required packages and build application backbone"
},
{
"code": null,
"e": 3104,
"s": 3057,
"text": "Build your own, fully customizable, login form"
},
{
"code": null,
"e": 3123,
"s": 3104,
"text": "Define server side"
},
{
"code": null,
"e": 3199,
"s": 3123,
"text": "I used the 4 following packages: shiny, shinythemes, shinyjs, and tidyverse"
},
{
"code": null,
"e": 3438,
"s": 3199,
"text": "# 1 - SET THE SCENE# load required packages library(shiny) # web app framework library(shinyjs) # improve user experience with JavaScriptlibrary(shinythemes) # themes for shinylibrary(tidyverse) # data manipulation"
},
{
"code": null,
"e": 3502,
"s": 3438,
"text": "Then I designed a simple application backbone using navbarPage:"
},
{
"code": null,
"e": 3891,
"s": 3502,
"text": "# 2 - UI PART# app backboneui <- navbarPage( title = \"R Shiny advanced tips series\", collapsible = TRUE, windowTitle = \"R Shiny tips - TFI\", theme = shinytheme(\"readable\"), tabPanel( title = \"Demo\", useShinyjs() # Include shinyjs ))# 3 - SERVER PARTserver <- function(input, output, session) {}# 4 - RUN APPshinyApp(ui = ui, server = server)"
},
{
"code": null,
"e": 3941,
"s": 3891,
"text": "A login form requires the 3 following components:"
},
{
"code": null,
"e": 4122,
"s": 3941,
"text": "a text input to capture user namea password input to capture password (similar to text input except that text is hidden)an action button to confirm/infirm access to the application"
},
{
"code": null,
"e": 4156,
"s": 4122,
"text": "a text input to capture user name"
},
{
"code": null,
"e": 4244,
"s": 4156,
"text": "a password input to capture password (similar to text input except that text is hidden)"
},
{
"code": null,
"e": 4305,
"s": 4244,
"text": "an action button to confirm/infirm access to the application"
},
{
"code": null,
"e": 4526,
"s": 4305,
"text": "Here is a simple code chunk you can adapt to your own preferences. In my case I mostly used basic bootstrap classes to make the text centered (“text-center”) and to add a light grey background to the login form (“well”)."
},
{
"code": null,
"e": 4598,
"s": 4526,
"text": "Login form should be located in a dedicated div with class ‘container’."
},
{
"code": null,
"e": 4618,
"s": 4598,
"text": "Please also notice:"
},
{
"code": null,
"e": 4764,
"s": 4618,
"text": "An id should be defined, so as to make the login form disappear in case of successful authentication. This part is defined just after in step 1.3"
},
{
"code": null,
"e": 4862,
"s": 4764,
"text": "the use of the tagList() function to add an icon next to the text input and password input labels"
},
{
"code": null,
"e": 5896,
"s": 4862,
"text": "div( id = \"login-basic\", style = \"width: 500px; max-width: 100%; margin: 0 auto;\", div( class = \"well\", h4(class = \"text-center\", \"Please login\"), p(class = \"text-center\", tags$small(\"First approach login form\") ), textInput( inputId = \"ti_user_name_basic\", label = tagList(icon(\"user\"), \"User Name\"), placeholder = \"Enter user name\" ), passwordInput( inputId = \"ti_password_basic\", label = tagList(icon(\"unlock-alt\"), \"Password\"), placeholder = \"Enter password\" ), div( class = \"text-center\", actionButton( inputId = \"ab_login_button_basic\", label = \"Log in\", class = \"btn-primary\" ) ) ))"
},
{
"code": null,
"e": 6026,
"s": 5896,
"text": "The server side is the place where developer can infuse intelligence into the application, define and control expected behaviors."
},
{
"code": null,
"e": 6229,
"s": 6026,
"text": "I first built a simple table to store users credential. In this example I granted access to only one user (“user_basic_1”), but you can of course define as many user x password combinations as you like."
},
{
"code": null,
"e": 6365,
"s": 6229,
"text": "# >> insert in server part# create userbaseuser_base_basic_tbl <- tibble( user_name = \"user_basic_1\", password = \"pass_basic_1\")"
},
{
"code": null,
"e": 6609,
"s": 6365,
"text": "In a second step, I used the eventReactive() function to check user’s login and password against valid credentials (stored in the above userbase). This toggles a TRUE/FALSE boolean parameter accordingly as soon as user clicks the login button."
},
{
"code": null,
"e": 6930,
"s": 6609,
"text": "# >> insert in server part# check credentials vs tibblevalidate_password_basic <- eventReactive(input$ab_login_button_basic, { validate <- FALSE if (input$ti_user_name_basic == user_base_basic_tbl$user_name && input$ti_password_basic == user_base_basic_tbl$password {validate <- TRUE}})"
},
{
"code": null,
"e": 6959,
"s": 6930,
"text": "Based on this boolean value:"
},
{
"code": null,
"e": 7232,
"s": 6959,
"text": "Login form will hide, using the shinyjs::hide() function inside an observeEvent(). This requires an id to refer to the appropriate UI section to be hidden, thus my comment in step 1.2.Secured part of the app will appear, using a classic renderUI() + uiOutput() combination"
},
{
"code": null,
"e": 7417,
"s": 7232,
"text": "Login form will hide, using the shinyjs::hide() function inside an observeEvent(). This requires an id to refer to the appropriate UI section to be hidden, thus my comment in step 1.2."
},
{
"code": null,
"e": 7506,
"s": 7417,
"text": "Secured part of the app will appear, using a classic renderUI() + uiOutput() combination"
},
{
"code": null,
"e": 7896,
"s": 7506,
"text": "# >> insert in server part# hide form observeEvent(validate_password_basic(), { shinyjs::hide(id = \"login-basic\")})# show app output$display_content_basic <- renderUI({ req(validate_password_basic()) div( class = \"bg-success\", id = \"success_basic\", h4(\"Access confirmed!\"), p(\"Welcome to your basically-secured application!\") ) })"
},
{
"code": null,
"e": 7939,
"s": 7896,
"text": "uiOutput should be inserted in the ui part"
},
{
"code": null,
"e": 7992,
"s": 7939,
"text": "# app uiOutput(outputId = \"display_content_basic\")"
},
{
"code": null,
"e": 8154,
"s": 7992,
"text": "Congratulations if you’ve been able to follow and reproduce this example so far. You’ve just built your first login component to secure your R Shiny application."
},
{
"code": null,
"e": 8305,
"s": 8154,
"text": "As this process requires a significant amount of code which makes your application harder to maintain on the long run, let’s package it into a module!"
},
{
"code": null,
"e": 8552,
"s": 8305,
"text": "Now that you understand the basic underlying principles of authentication and that you have built your first login form, let’s make it more robust and easier to reuse across multiple applications. This can be achieved defining a dedicated module."
},
{
"code": null,
"e": 8793,
"s": 8552,
"text": "A Shiny module is a piece of a Shiny app. It can’t be directly run, as a Shiny app can. Instead, it is included as part of a larger app (or as part of a larger Shiny module — they are composable). — Wiston Chang — Software engineer, RStudio"
},
{
"code": null,
"e": 8929,
"s": 8793,
"text": "Note: this tutorial will not cover in details how to create a module, and I assume the reader is somehow familiar with its key concept."
},
{
"code": null,
"e": 9140,
"s": 8929,
"text": "In a nutshell, a module is composed of two functions that represent 1) a piece of UI, and 2) a fragment of server logic that uses that UI — similar to the way that Shiny apps are split into UI and server logic."
},
{
"code": null,
"e": 9362,
"s": 9140,
"text": "View the short illustration below to get an idea of what will be built with this second approach; as you can see the UI part looks exactly the same as what I built in the first approach. However it differs under the hood:"
},
{
"code": null,
"e": 9402,
"s": 9362,
"text": "Code explanation is split into 4 steps:"
},
{
"code": null,
"e": 9509,
"s": 9402,
"text": "Build the moduleSource the moduleAdd login form + secured part of the app in the UI partDefine server side"
},
{
"code": null,
"e": 9526,
"s": 9509,
"text": "Build the module"
},
{
"code": null,
"e": 9544,
"s": 9526,
"text": "Source the module"
},
{
"code": null,
"e": 9600,
"s": 9544,
"text": "Add login form + secured part of the app in the UI part"
},
{
"code": null,
"e": 9619,
"s": 9600,
"text": "Define server side"
},
{
"code": null,
"e": 9792,
"s": 9619,
"text": "This steps essentially consists in bringing together the custom UI and associated server logic I’ve implemented in the previous approach, into a single module_login.R file."
},
{
"code": null,
"e": 9839,
"s": 9792,
"text": "Key aspects to notice in the code chunk below:"
},
{
"code": null,
"e": 9848,
"s": 9839,
"text": "UI part:"
},
{
"code": null,
"e": 10080,
"s": 9848,
"text": "Use of NS(): All UI function bodies should start with this line when creating a module. It takes the string id and creates a namespace function. All id names must be encapsulated within ns(). More on this here for interested reader"
},
{
"code": null,
"e": 10257,
"s": 10080,
"text": "The function takes another variable, title, to make it easy to customize login page title, should you need to use the module in the context of other future R Shiny applications"
},
{
"code": null,
"e": 11518,
"s": 10257,
"text": "# UI componentlogin_ui <- function(id, title) { ns <- NS(id) # namespaced id # define ui part div( id = ns(\"login\"), style = \"width: 500px; max-width: 100%; margin: 0 auto;\", div( class = \"well\", h4(class = \"text-center\", title), p(class = \"text-center\", tags$small(\"Second approach login form\")), textInput( inputId = ns(\"ti_user_name_module\"), label = tagList(icon(\"user\"), \"User Name\"), placeholder = \"Enter user name\" ), passwordInput( inputId = ns(\"ti_password_module\"), label = tagList( icon(\"unlock-alt\"), \"Password\" ), placeholder = \"Enter password\" ), div( class = \"text-center\", actionButton( inputId = ns(\"ab_login_button_module\"), label = \"Log in\", class = \"btn-primary\" ) ) ) )}"
},
{
"code": null,
"e": 11531,
"s": 11518,
"text": "Server part:"
},
{
"code": null,
"e": 11635,
"s": 11531,
"text": "use of {{ }} to use user-supplied expression within a function. More on this here for interested reader"
},
{
"code": null,
"e": 11790,
"s": 11635,
"text": "call to shinyjs::hide() is embedded within the server part of the module, so there is no longer need to use an observeEvent as I did in the first approach"
},
{
"code": null,
"e": 12465,
"s": 11790,
"text": "# SERVER componentvalidate_pwd <- function(input, output, session, data, user_col, pwd_col) { # get user and pwd from data/ user_col/ pwd_col information user <- data %>% pull({{ user_col }}) pwd <- data %>% pull({{ pwd_col }}) # check correctness eventReactive(input$ab_login_button_module, { validate <- FALSE if (input$ti_user_name_module == user && input$ti_password_module == pwd) { validate <- TRUE } # hide login form when user is confirmed if (validate) { shinyjs::hide(id = \"login\") } validate })}"
},
{
"code": null,
"e": 12635,
"s": 12465,
"text": "Prior to using a particular module within your R Shiny application, be careful to source it appropriately (see my bitbucket account to understand the project structure):"
},
{
"code": null,
"e": 12684,
"s": 12635,
"text": "# source module source(\"modules/module_login.R\")"
},
{
"code": null,
"e": 12867,
"s": 12684,
"text": "Both login form and secured part of your app can now be specified in the UI part with 2 lines of code, which ensure great readability and maintainability of your app on the long run."
},
{
"code": null,
"e": 13026,
"s": 12867,
"text": "# login form as defined in the modulelogin_ui(id = \"module_login\", title = \"Please login\"), # app uiOutput(outputId = \"display_content_module\")"
},
{
"code": null,
"e": 13063,
"s": 13026,
"text": "This is very similar to section 1.3."
},
{
"code": null,
"e": 13254,
"s": 13063,
"text": "I first built a simple table to store users credential. In this illustration I granted access to only one user, but you can of course define as many user x password combinations as you like."
},
{
"code": null,
"e": 13401,
"s": 13254,
"text": "# >> insert in server part# create userbaseuser_base_module_tbl <- tibble( user_name = \"user_module_1\", password = \"pass_module_1\")"
},
{
"code": null,
"e": 13626,
"s": 13401,
"text": "I then used the callModule() function to access the server side of my module, and passing information on where to search for login and passwords (via the data, user_col and pwd_col parameters to refer to the above userbase):"
},
{
"code": null,
"e": 13863,
"s": 13626,
"text": "# check credentials vs tibble validate_password_module <- callModule( module = validate_pwd, id = \"module_login\", data = user_base_module_tbl, user_col = user_name, pwd_col = password)"
},
{
"code": null,
"e": 14086,
"s": 13863,
"text": "Finally, and as in the first approach, I use a classic renderUI() + uiOutput() combination to display the secured part of the application whenever the boolean validate_password_module() defined above toggles appropriately:"
},
{
"code": null,
"e": 14357,
"s": 14086,
"text": "# app output$display_content_module <- renderUI({ req(validate_password_module()) div( class = \"bg-success\", id = \"success_module\", h4(\"Access confirmed!\"), p(\"Welcome to your module-secured application!\") ) })"
},
{
"code": null,
"e": 14575,
"s": 14357,
"text": "Congratulations if you’ve been able to follow and reproduce this example so far. You’ve been able to package your fully customizable login form into a module, which you can reuse with all your future web applications."
},
{
"code": null,
"e": 14745,
"s": 14575,
"text": "In the next section, we’ll leverage an existing module for authentication, available in the shinyauthr package. Main advantages compared to building your own module are:"
},
{
"code": null,
"e": 14841,
"s": 14745,
"text": "No need for you to master the art of building modules, shinyauthr makes it ready for you to use"
},
{
"code": null,
"e": 15014,
"s": 14841,
"text": "Ability to encrypt your password, via the sodium package. Sodium uses a hashing algorithm that is specifically designed to protect stored passwords from brute-force attacks"
},
{
"code": null,
"e": 15310,
"s": 15014,
"text": "Shinyauthr is an R package providing module functions that can be used to add an authentication layer to your shiny apps. If you made it so far and successfully built your own module, this third approach should be easy to follow, and I recommend you use the package to speed up your future work."
},
{
"code": null,
"e": 15503,
"s": 15310,
"text": "View the short illustration below to get an idea of what will be built with this third approach; although it looks very similar to approaches 1 and 2, login form is slightly less customizable."
},
{
"code": null,
"e": 15674,
"s": 15503,
"text": "Code explanation below will specify new required packages, illustrate how to update the ui part and detail the server side. Remind that the entire code is available here."
},
{
"code": null,
"e": 15790,
"s": 15674,
"text": "In addition to the packages mentioned in previous approaches, you will need to load shinyauthr and sodium packages."
},
{
"code": null,
"e": 15885,
"s": 15790,
"text": "library(shinyauthr) # shiny authentication moduleslibrary(sodium) # crypto library"
},
{
"code": null,
"e": 16068,
"s": 15885,
"text": "Both login form and secured part of your app can now be specified in the UI part with 2 lines of code, which ensure great readability and maintainability of your app on the long run."
},
{
"code": null,
"e": 16225,
"s": 16068,
"text": "loginUI() function from shinyauthr package is pretty similar to what you’ve built during second approach. Title (+ a few other parameters can be customized)"
},
{
"code": null,
"e": 16302,
"s": 16225,
"text": "Secured part of the application is displayed through the uiOutput() function"
},
{
"code": null,
"e": 16483,
"s": 16302,
"text": "# login formshinyauthr::loginUI( id = \"authr_login\", title = h4(class = \"text-center\", \"Please login\")), # app uiOutput(outputId = \"display_content_authr\"),"
},
{
"code": null,
"e": 16674,
"s": 16483,
"text": "I first built a simple table to store users credential. In this illustration I granted access to only one user, but you can of course define as many user x password combinations as you like."
},
{
"code": null,
"e": 16767,
"s": 16674,
"text": "Notice the use of password_store() function from the sodium package to encrypt the password."
},
{
"code": null,
"e": 16930,
"s": 16767,
"text": "# >> insert in server part# create userbaseuuser_base_authr_tbl <- tibble( user_name = \"user_authr_1\", password = sodium::password_store(\"pass_authr_1\"))"
},
{
"code": null,
"e": 17032,
"s": 16930,
"text": "I then made a call to 2 modules that comes with the shinyauthr package (a login form + a logout form)"
},
{
"code": null,
"e": 17440,
"s": 17032,
"text": "# >> insert in server partlogout_init <- callModule( module = shinyauthr::logout, id = \"authr_logout\", active = reactive(user_auth)) credentials <- callModule( module = shinyauthr::login, id = \"authr_login\", data = user_base_authr_tbl, user_col = user_name, pwd_col = password, sodium_hashed = TRUE, log_out = reactive(logout_init()))"
},
{
"code": null,
"e": 17523,
"s": 17440,
"text": "When the login module is called, it returns a reactive list containing 2 elements:"
},
{
"code": null,
"e": 17558,
"s": 17523,
"text": "user_auth (initial value is FALSE)"
},
{
"code": null,
"e": 17587,
"s": 17558,
"text": "info (initial value is NULL)"
},
{
"code": null,
"e": 17760,
"s": 17587,
"text": "I create reactive object on the server side to capture changes in these values (in particular, user_auth turns TRUE if the user supplies a matching user name and password.)"
},
{
"code": null,
"e": 17898,
"s": 17760,
"text": "# >> insert in server partuser_auth <- reactive({ credentials()$user_auth}) user_data <- reactive({ credentials()$info})"
},
{
"code": null,
"e": 18023,
"s": 17898,
"text": "Lastly, I need to define the secured part of the application within a renderUI() function, similarly to previous approaches."
},
{
"code": null,
"e": 18379,
"s": 18023,
"text": "# >> insert in server partoutput$display_content_authr <- renderUI({ req(user_auth()) div( class = \"bg-success\", id = \"success_module\", h4(\"Access confirmed!\"), p(\"Welcome to your shinyauthr-secured application! Notice that password is encrypted.\") ) })"
},
{
"code": null,
"e": 18508,
"s": 18379,
"text": "Congratulations if you’ve made it this far, you are now equipped with a fast, powerful and easy way to secure your applications!"
},
{
"code": null,
"e": 18567,
"s": 18508,
"text": "I usually implement one of the 3 above detailed approches."
},
{
"code": null,
"e": 18672,
"s": 18567,
"text": "However they are not the only ones and you might be interested in exploring other alternatives, such as:"
},
{
"code": null,
"e": 18714,
"s": 18672,
"text": "shinymanager (very similar to shinyauthr)"
},
{
"code": null,
"e": 18896,
"s": 18714,
"text": "polished a non-free solution providing you with several additional features on top of authentication, such as: custom login page, user management, single sign on, or user monitoring"
},
{
"code": null,
"e": 19030,
"s": 18896,
"text": "I hope you found this tutorial useful, please feel free to leave comment to share your preferred (and possibly alternative) approach."
},
{
"code": null,
"e": 19169,
"s": 19030,
"text": "Want to learn more? This article is the second one of my advanced R Shiny tips series. First post is about building dynamic UI components."
},
{
"code": null,
"e": 19257,
"s": 19169,
"text": "shinymanager: simple and secure authentication mechanism for single Shiny applications."
},
{
"code": null,
"e": 19373,
"s": 19257,
"text": "shinyauthr: R package providing module functions that can be used to add an authentication layer to your shiny apps"
},
{
"code": null,
"e": 19429,
"s": 19373,
"text": "polished: add authentication to your Shiny applications"
},
{
"code": null,
"e": 19573,
"s": 19429,
"text": "Mastering Shiny: This book complements Shiny’s online documentation and is intended to help app authors develop a deeper understanding of Shiny"
}
] |
Java Regex Example - Character \t Match | The character \t matches the tab character.
The following example shows the usage of character matching.
package com.tutorialspoint;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CharactersDemo {
private static final String REGEX = "\t";
private static final String INPUT = "abc\tabc";
public static void main(String[] args) {
// create a pattern
Pattern pattern = Pattern.compile(REGEX);
// get a matcher object
Matcher matcher = pattern.matcher(INPUT);
if(matcher.find()) {
//Prints the start index of the match.
System.out.println("Match String start(): "+matcher.start());
}
}
}
Let us compile and run the above program, this will produce the following result −
Match String start(): 3
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2168,
"s": 2124,
"text": "The character \\t matches the tab character."
},
{
"code": null,
"e": 2229,
"s": 2168,
"text": "The following example shows the usage of character matching."
},
{
"code": null,
"e": 2816,
"s": 2229,
"text": "package com.tutorialspoint;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class CharactersDemo {\n private static final String REGEX = \"\\t\";\n private static final String INPUT = \"abc\\tabc\";\n\n public static void main(String[] args) {\n // create a pattern\n Pattern pattern = Pattern.compile(REGEX);\n \n // get a matcher object\n Matcher matcher = pattern.matcher(INPUT); \n\n if(matcher.find()) {\n //Prints the start index of the match.\n System.out.println(\"Match String start(): \"+matcher.start());\n }\n }\n}"
},
{
"code": null,
"e": 2899,
"s": 2816,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 2924,
"s": 2899,
"text": "Match String start(): 3\n"
},
{
"code": null,
"e": 2931,
"s": 2924,
"text": " Print"
},
{
"code": null,
"e": 2942,
"s": 2931,
"text": " Add Notes"
}
] |
Lodash _.camelCase() Method - GeeksforGeeks | 09 Sep, 2020
The _.camelCase() method is used to convert a string into a camel case string. The string can be space-separated, dash-separated, or can be separated by underscores.
Syntax:
_.camelCase(string)
Parameters: This method accepts a single parameter as mentioned above and described below:
string: This parameter holds the string that needs to be converted into a camel case string.
Return Value: This method returns the camel case string.
Below example illustrate the Lodash _.camelCase() method in JavaScript:
Example 1:
Javascript
// Requiring the lodash library const _ = require('lodash'); // Use of _.camelCase() methodvar str1 = _.camelCase("Geeks for Geeks"); // Printing the output console.log(str1); // Use of _.camelCase() methodvar str2 = _.camelCase("GFG-Geeks"); // Printing the output console.log(str2);
Output:
geeksForGeeks
gfgGeeks
Example 2:
Javascript
// Requiring the lodash library const _ = require('lodash'); // Use of _.camelCase() methodvar str1 = _.camelCase("Geeks__for__Geeks"); // Printing the output console.log(str1); // Use of _.camelCase() methodvar str2 = _.camelCase("GFG--Geeks"); // Printing the output console.log(str2);
Output:
geeksForGeeks
gfgGeeks
JavaScript-Lodash
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
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 37356,
"s": 37328,
"text": "\n09 Sep, 2020"
},
{
"code": null,
"e": 37522,
"s": 37356,
"text": "The _.camelCase() method is used to convert a string into a camel case string. The string can be space-separated, dash-separated, or can be separated by underscores."
},
{
"code": null,
"e": 37530,
"s": 37522,
"text": "Syntax:"
},
{
"code": null,
"e": 37551,
"s": 37530,
"text": "_.camelCase(string)\n"
},
{
"code": null,
"e": 37642,
"s": 37551,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 37735,
"s": 37642,
"text": "string: This parameter holds the string that needs to be converted into a camel case string."
},
{
"code": null,
"e": 37792,
"s": 37735,
"text": "Return Value: This method returns the camel case string."
},
{
"code": null,
"e": 37864,
"s": 37792,
"text": "Below example illustrate the Lodash _.camelCase() method in JavaScript:"
},
{
"code": null,
"e": 37875,
"s": 37864,
"text": "Example 1:"
},
{
"code": null,
"e": 37886,
"s": 37875,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require('lodash'); // Use of _.camelCase() methodvar str1 = _.camelCase(\"Geeks for Geeks\"); // Printing the output console.log(str1); // Use of _.camelCase() methodvar str2 = _.camelCase(\"GFG-Geeks\"); // Printing the output console.log(str2);",
"e": 38176,
"s": 37886,
"text": null
},
{
"code": null,
"e": 38184,
"s": 38176,
"text": "Output:"
},
{
"code": null,
"e": 38208,
"s": 38184,
"text": "geeksForGeeks\ngfgGeeks\n"
},
{
"code": null,
"e": 38219,
"s": 38208,
"text": "Example 2:"
},
{
"code": null,
"e": 38230,
"s": 38219,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require('lodash'); // Use of _.camelCase() methodvar str1 = _.camelCase(\"Geeks__for__Geeks\"); // Printing the output console.log(str1); // Use of _.camelCase() methodvar str2 = _.camelCase(\"GFG--Geeks\"); // Printing the output console.log(str2);",
"e": 38523,
"s": 38230,
"text": null
},
{
"code": null,
"e": 38531,
"s": 38523,
"text": "Output:"
},
{
"code": null,
"e": 38555,
"s": 38531,
"text": "geeksForGeeks\ngfgGeeks\n"
},
{
"code": null,
"e": 38573,
"s": 38555,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 38584,
"s": 38573,
"text": "JavaScript"
},
{
"code": null,
"e": 38601,
"s": 38584,
"text": "Web Technologies"
},
{
"code": null,
"e": 38699,
"s": 38601,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38708,
"s": 38699,
"text": "Comments"
},
{
"code": null,
"e": 38721,
"s": 38708,
"text": "Old Comments"
},
{
"code": null,
"e": 38766,
"s": 38721,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 38835,
"s": 38766,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 38896,
"s": 38835,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 38968,
"s": 38896,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 38995,
"s": 38968,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 39037,
"s": 38995,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 39070,
"s": 39037,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 39132,
"s": 39070,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 39182,
"s": 39132,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
XAML - CheckBox | A CheckBox is a control that a user can select (check) or clear (uncheck). It provides a list of options that a user can select, such as a list of settings to apply to an application. The hierarchical inheritance of Checkbox class is as follows −
Background
Gets or sets a brush that provides the background of the control. (Inherited from Control)
BorderBrush
Gets or sets a brush that describes the border fill of a control. (Inherited from Control)
BorderThickness
Gets or sets the border thickness of a control. (Inherited from Control)
Content
Gets or sets the content of a ContentControl. (Inherited from ContentControl)
ClickMode
Gets or sets a value that indicates when the Click event occurs, in terms of device behavior. (Inherited from ButtonBase)
ContentTemplate
Gets or sets the data template that is used to display the content of the ContentControl. (Inherited from ContentControl)
FontFamily
Gets or sets the font used to display text in the control. (Inherited from Control)
FontSize
Gets or sets the size of the text in this control. (Inherited from Control)
FontStyle
Gets or sets the style in which the text is rendered. (Inherited from Control)
FontWeight
Gets or sets the thickness of the specified font. (Inherited from Control)
Foreground
Gets or sets a brush that describes the foreground color. (Inherited from Control)
Height
Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement)
HorizontalAlignment
Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement)
IsChecked
Gets or sets whether the ToggleButton is checked. (Inherited from ToggleButton)
IsEnabled
Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control)
IsPressed
Gets a value that indicates whether a ButtonBase is currently in a pressed state. (Inherited from ButtonBase)
IsThreeState
Gets or sets a value that indicates whether the control supports three states. (Inherited from ToggleButton)
Margin
Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement)
Name
Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement)
Opacity
Gets or sets the degree of the object's opacity. (Inherited from UIElement)
Resources
Gets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkElement. Resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement)
Style
Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement)
Template
Gets or sets a control template. The control template defines the visual appearance of a control in UI, and is defined in XAML markup. (Inherited from Control)
VerticalAlignment
Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement)
Visibility
Gets or sets the visibility of a UIElement. A UIElement that is not visible is not rendered and does not communicate its desired size to layout. (Inherited from UIElement)
Width
Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement)
ClearValue
Clears the local value of a dependency property. (Inherited from DependencyObject)
FindName
Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement)
OnApplyTemplate
Invoked whenever application code or internal processes (such as a rebuilding layout pass) call ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays in your app. Override this method to influence the default post-template logic of a class. (Inherited from FrameworkElement)
OnContentChanged
Invoked when the value of the Content property changes. (Inherited from ContentControl)
OnDragEnter
Called before the DragEnter event occurs. (Inherited from Control)
OnDragLeave
Called before the DragLeave event occurs. (Inherited from Control)
OnDragOver
Called before the DragOver event occurs. (Inherited from Control)
OnDrop
Called before the Drop event occurs. (Inherited from Control)
OnGotFocus
Called before the GotFocus event occurs. (Inherited from Control)
OnKeyDown
Called before the KeyDown event occurs. (Inherited from Control)
OnKeyUp
Called before the KeyUp event occurs. (Inherited from Control)
OnLostFocus
Called before the LostFocus event occurs. (Inherited from Control)
OnToggle
Called when the ToggleButton receives toggle stimulus. (Inherited from ToggleButton)
SetBinding
Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement)
Checked
Fires when a ToggleButton is checked. (Inherited from ToggleButton)
Click
Occurs when a button control is clicked. (Inherited from ButtonBase)
DataContextChanged
Occurs when the value of the FrameworkElement. DataContext property changes. (Inherited from FrameworkElement)
DragEnter
Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement)
DragLeave
Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)
DragOver
Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)
DragStarting
Occurs when a drag operation is initiated. (Inherited from UIElement)
GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)
Holding
Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement)
Intermediate
Fires when the state of a ToggleButton is switched to the indeterminate state. (Inherited from ToggleButton)
IsEnabledChanged
Occurs when the IsEnabled property changes. (Inherited from Control)
KeyDown
Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)
KeyUp
Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)
LostFocus
Occurs when a UIElement loses focus. (Inherited from UIElement)
SizeChanged
Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement)
Unchecked
Occurs when a ToggleButton is unchecked. (Inherited from ToggleButton)
The following example contains two checkboxes. The first checkbox has two states checked or unchecked. The second checkbox has 3 states which are checked, unchecked, and intermediate state. Both checkboxes display a message based on Checked, Unchecked, and Intermediate events.
Here is the XAML code in which two checkboxes have been created with some properties and events.
<Window x:Class = "XAMLCheckBox.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<StackPanel Orientation = "Vertical" >
<CheckBox x:Name = "cb1"
Content = "2 state CheckBox"
Checked = "HandleCheck"
Unchecked = "HandleUnchecked"
Margin = "10" />
<TextBlock x:Name = "text1" Margin = "10" />
<CheckBox x:Name = "cb2"
Content = "3 state CheckBox"
IsThreeState = "True"
Indeterminate = "HandleThirdState"
Checked = "HandleCheck"
Unchecked = "HandleUnchecked"
Margin = "10" />
<TextBlock x:Name = "text2" Margin = "10" />
</StackPanel>
</Grid>
</Window>
Here is the implementation in C# for different events −
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace XAMLCheckBox {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void HandleCheck(object sender, RoutedEventArgs e) {
CheckBox cb = sender as CheckBox;
if (cb.Name == "cb1") {
text1.Text = "2 state CheckBox is checked.";
} else {
text2.Text = "3 state CheckBox is checked.";
}
}
private void HandleUnchecked(object sender, RoutedEventArgs e) {
CheckBox cb = sender as CheckBox;
if (cb.Name == "cb1") {
text1.Text = "2 state CheckBox is unchecked.";
} else {
text2.Text = "3 state CheckBox is unchecked.";
}
}
private void HandleThirdState(object sender, RoutedEventArgs e) {
CheckBox cb = sender as CheckBox;
text2.Text = "3 state CheckBox is in indeterminate state.";
}
}
}
When you compile and execute the above code, it will produce the following output −
We recommend you to execute the above example code and experiment with some other properties and events
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2170,
"s": 1923,
"text": "A CheckBox is a control that a user can select (check) or clear (uncheck). It provides a list of options that a user can select, such as a list of settings to apply to an application. The hierarchical inheritance of Checkbox class is as follows −"
},
{
"code": null,
"e": 2181,
"s": 2170,
"text": "Background"
},
{
"code": null,
"e": 2272,
"s": 2181,
"text": "Gets or sets a brush that provides the background of the control. (Inherited from Control)"
},
{
"code": null,
"e": 2284,
"s": 2272,
"text": "BorderBrush"
},
{
"code": null,
"e": 2375,
"s": 2284,
"text": "Gets or sets a brush that describes the border fill of a control. (Inherited from Control)"
},
{
"code": null,
"e": 2391,
"s": 2375,
"text": "BorderThickness"
},
{
"code": null,
"e": 2464,
"s": 2391,
"text": "Gets or sets the border thickness of a control. (Inherited from Control)"
},
{
"code": null,
"e": 2472,
"s": 2464,
"text": "Content"
},
{
"code": null,
"e": 2550,
"s": 2472,
"text": "Gets or sets the content of a ContentControl. (Inherited from ContentControl)"
},
{
"code": null,
"e": 2560,
"s": 2550,
"text": "ClickMode"
},
{
"code": null,
"e": 2682,
"s": 2560,
"text": "Gets or sets a value that indicates when the Click event occurs, in terms of device behavior. (Inherited from ButtonBase)"
},
{
"code": null,
"e": 2698,
"s": 2682,
"text": "ContentTemplate"
},
{
"code": null,
"e": 2820,
"s": 2698,
"text": "Gets or sets the data template that is used to display the content of the ContentControl. (Inherited from ContentControl)"
},
{
"code": null,
"e": 2831,
"s": 2820,
"text": "FontFamily"
},
{
"code": null,
"e": 2915,
"s": 2831,
"text": "Gets or sets the font used to display text in the control. (Inherited from Control)"
},
{
"code": null,
"e": 2924,
"s": 2915,
"text": "FontSize"
},
{
"code": null,
"e": 3000,
"s": 2924,
"text": "Gets or sets the size of the text in this control. (Inherited from Control)"
},
{
"code": null,
"e": 3010,
"s": 3000,
"text": "FontStyle"
},
{
"code": null,
"e": 3089,
"s": 3010,
"text": "Gets or sets the style in which the text is rendered. (Inherited from Control)"
},
{
"code": null,
"e": 3100,
"s": 3089,
"text": "FontWeight"
},
{
"code": null,
"e": 3175,
"s": 3100,
"text": "Gets or sets the thickness of the specified font. (Inherited from Control)"
},
{
"code": null,
"e": 3186,
"s": 3175,
"text": "Foreground"
},
{
"code": null,
"e": 3269,
"s": 3186,
"text": "Gets or sets a brush that describes the foreground color. (Inherited from Control)"
},
{
"code": null,
"e": 3276,
"s": 3269,
"text": "Height"
},
{
"code": null,
"e": 3367,
"s": 3276,
"text": "Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 3387,
"s": 3367,
"text": "HorizontalAlignment"
},
{
"code": null,
"e": 3588,
"s": 3387,
"text": "Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 3598,
"s": 3588,
"text": "IsChecked"
},
{
"code": null,
"e": 3678,
"s": 3598,
"text": "Gets or sets whether the ToggleButton is checked. (Inherited from ToggleButton)"
},
{
"code": null,
"e": 3688,
"s": 3678,
"text": "IsEnabled"
},
{
"code": null,
"e": 3793,
"s": 3688,
"text": "Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control)"
},
{
"code": null,
"e": 3803,
"s": 3793,
"text": "IsPressed"
},
{
"code": null,
"e": 3913,
"s": 3803,
"text": "Gets a value that indicates whether a ButtonBase is currently in a pressed state. (Inherited from ButtonBase)"
},
{
"code": null,
"e": 3926,
"s": 3913,
"text": "IsThreeState"
},
{
"code": null,
"e": 4035,
"s": 3926,
"text": "Gets or sets a value that indicates whether the control supports three states. (Inherited from ToggleButton)"
},
{
"code": null,
"e": 4042,
"s": 4035,
"text": "Margin"
},
{
"code": null,
"e": 4129,
"s": 4042,
"text": "Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 4134,
"s": 4129,
"text": "Name"
},
{
"code": null,
"e": 4347,
"s": 4134,
"text": "Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 4355,
"s": 4347,
"text": "Opacity"
},
{
"code": null,
"e": 4431,
"s": 4355,
"text": "Gets or sets the degree of the object's opacity. (Inherited from UIElement)"
},
{
"code": null,
"e": 4441,
"s": 4431,
"text": "Resources"
},
{
"code": null,
"e": 4680,
"s": 4441,
"text": "Gets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkElement. Resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 4686,
"s": 4680,
"text": "Style"
},
{
"code": null,
"e": 4812,
"s": 4686,
"text": "Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 4821,
"s": 4812,
"text": "Template"
},
{
"code": null,
"e": 4981,
"s": 4821,
"text": "Gets or sets a control template. The control template defines the visual appearance of a control in UI, and is defined in XAML markup. (Inherited from Control)"
},
{
"code": null,
"e": 4999,
"s": 4981,
"text": "VerticalAlignment"
},
{
"code": null,
"e": 5197,
"s": 4999,
"text": "Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 5208,
"s": 5197,
"text": "Visibility"
},
{
"code": null,
"e": 5380,
"s": 5208,
"text": "Gets or sets the visibility of a UIElement. A UIElement that is not visible is not rendered and does not communicate its desired size to layout. (Inherited from UIElement)"
},
{
"code": null,
"e": 5386,
"s": 5380,
"text": "Width"
},
{
"code": null,
"e": 5466,
"s": 5386,
"text": "Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 5477,
"s": 5466,
"text": "ClearValue"
},
{
"code": null,
"e": 5560,
"s": 5477,
"text": "Clears the local value of a dependency property. (Inherited from DependencyObject)"
},
{
"code": null,
"e": 5569,
"s": 5560,
"text": "FindName"
},
{
"code": null,
"e": 5663,
"s": 5569,
"text": "Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 5679,
"s": 5663,
"text": "OnApplyTemplate"
},
{
"code": null,
"e": 6000,
"s": 5679,
"text": "Invoked whenever application code or internal processes (such as a rebuilding layout pass) call ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays in your app. Override this method to influence the default post-template logic of a class. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 6017,
"s": 6000,
"text": "OnContentChanged"
},
{
"code": null,
"e": 6105,
"s": 6017,
"text": "Invoked when the value of the Content property changes. (Inherited from ContentControl)"
},
{
"code": null,
"e": 6117,
"s": 6105,
"text": "OnDragEnter"
},
{
"code": null,
"e": 6184,
"s": 6117,
"text": "Called before the DragEnter event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 6196,
"s": 6184,
"text": "OnDragLeave"
},
{
"code": null,
"e": 6263,
"s": 6196,
"text": "Called before the DragLeave event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 6274,
"s": 6263,
"text": "OnDragOver"
},
{
"code": null,
"e": 6340,
"s": 6274,
"text": "Called before the DragOver event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 6347,
"s": 6340,
"text": "OnDrop"
},
{
"code": null,
"e": 6409,
"s": 6347,
"text": "Called before the Drop event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 6420,
"s": 6409,
"text": "OnGotFocus"
},
{
"code": null,
"e": 6486,
"s": 6420,
"text": "Called before the GotFocus event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 6496,
"s": 6486,
"text": "OnKeyDown"
},
{
"code": null,
"e": 6561,
"s": 6496,
"text": "Called before the KeyDown event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 6569,
"s": 6561,
"text": "OnKeyUp"
},
{
"code": null,
"e": 6632,
"s": 6569,
"text": "Called before the KeyUp event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 6644,
"s": 6632,
"text": "OnLostFocus"
},
{
"code": null,
"e": 6711,
"s": 6644,
"text": "Called before the LostFocus event occurs. (Inherited from Control)"
},
{
"code": null,
"e": 6720,
"s": 6711,
"text": "OnToggle"
},
{
"code": null,
"e": 6805,
"s": 6720,
"text": "Called when the ToggleButton receives toggle stimulus. (Inherited from ToggleButton)"
},
{
"code": null,
"e": 6816,
"s": 6805,
"text": "SetBinding"
},
{
"code": null,
"e": 6927,
"s": 6816,
"text": "Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 6935,
"s": 6927,
"text": "Checked"
},
{
"code": null,
"e": 7003,
"s": 6935,
"text": "Fires when a ToggleButton is checked. (Inherited from ToggleButton)"
},
{
"code": null,
"e": 7009,
"s": 7003,
"text": "Click"
},
{
"code": null,
"e": 7078,
"s": 7009,
"text": "Occurs when a button control is clicked. (Inherited from ButtonBase)"
},
{
"code": null,
"e": 7097,
"s": 7078,
"text": "DataContextChanged"
},
{
"code": null,
"e": 7208,
"s": 7097,
"text": "Occurs when the value of the FrameworkElement. DataContext property changes. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 7218,
"s": 7208,
"text": "DragEnter"
},
{
"code": null,
"e": 7340,
"s": 7218,
"text": "Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement)"
},
{
"code": null,
"e": 7350,
"s": 7340,
"text": "DragLeave"
},
{
"code": null,
"e": 7472,
"s": 7350,
"text": "Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)"
},
{
"code": null,
"e": 7481,
"s": 7472,
"text": "DragOver"
},
{
"code": null,
"e": 7618,
"s": 7481,
"text": "Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)"
},
{
"code": null,
"e": 7631,
"s": 7618,
"text": "DragStarting"
},
{
"code": null,
"e": 7701,
"s": 7631,
"text": "Occurs when a drag operation is initiated. (Inherited from UIElement)"
},
{
"code": null,
"e": 7710,
"s": 7701,
"text": "GotFocus"
},
{
"code": null,
"e": 7777,
"s": 7710,
"text": "Occurs when a UIElement receives focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 7785,
"s": 7777,
"text": "Holding"
},
{
"code": null,
"e": 7911,
"s": 7785,
"text": "Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement)"
},
{
"code": null,
"e": 7924,
"s": 7911,
"text": "Intermediate"
},
{
"code": null,
"e": 8033,
"s": 7924,
"text": "Fires when the state of a ToggleButton is switched to the indeterminate state. (Inherited from ToggleButton)"
},
{
"code": null,
"e": 8050,
"s": 8033,
"text": "IsEnabledChanged"
},
{
"code": null,
"e": 8119,
"s": 8050,
"text": "Occurs when the IsEnabled property changes. (Inherited from Control)"
},
{
"code": null,
"e": 8127,
"s": 8119,
"text": "KeyDown"
},
{
"code": null,
"e": 8223,
"s": 8127,
"text": "Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 8229,
"s": 8223,
"text": "KeyUp"
},
{
"code": null,
"e": 8326,
"s": 8229,
"text": "Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 8336,
"s": 8326,
"text": "LostFocus"
},
{
"code": null,
"e": 8400,
"s": 8336,
"text": "Occurs when a UIElement loses focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 8412,
"s": 8400,
"text": "SizeChanged"
},
{
"code": null,
"e": 8547,
"s": 8412,
"text": "Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 8557,
"s": 8547,
"text": "Unchecked"
},
{
"code": null,
"e": 8628,
"s": 8557,
"text": "Occurs when a ToggleButton is unchecked. (Inherited from ToggleButton)"
},
{
"code": null,
"e": 8906,
"s": 8628,
"text": "The following example contains two checkboxes. The first checkbox has two states checked or unchecked. The second checkbox has 3 states which are checked, unchecked, and intermediate state. Both checkboxes display a message based on Checked, Unchecked, and Intermediate events."
},
{
"code": null,
"e": 9003,
"s": 8906,
"text": "Here is the XAML code in which two checkboxes have been created with some properties and events."
},
{
"code": null,
"e": 9930,
"s": 9003,
"text": "<Window x:Class = \"XAMLCheckBox.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n \n <Grid> \n <StackPanel Orientation = \"Vertical\" > \n <CheckBox x:Name = \"cb1\" \n Content = \"2 state CheckBox\" \n Checked = \"HandleCheck\" \n Unchecked = \"HandleUnchecked\" \n Margin = \"10\" />\n\t\t\t\t\n <TextBlock x:Name = \"text1\" Margin = \"10\" /> \n\t\t\t\n <CheckBox x:Name = \"cb2\" \n Content = \"3 state CheckBox\" \n IsThreeState = \"True\" \n Indeterminate = \"HandleThirdState\" \n Checked = \"HandleCheck\" \n Unchecked = \"HandleUnchecked\" \n Margin = \"10\" />\n\t\t\t\t\n <TextBlock x:Name = \"text2\" Margin = \"10\" /> \n </StackPanel> \n </Grid>\n \n</Window>"
},
{
"code": null,
"e": 9986,
"s": 9930,
"text": "Here is the implementation in C# for different events −"
},
{
"code": null,
"e": 11128,
"s": 9986,
"text": "using System; \nusing System.Windows; \nusing System.Windows.Controls; \nusing System.Windows.Media;\n\nnamespace XAMLCheckBox {\n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary>\n\tpublic partial class MainWindow : Window { \n public MainWindow() { \n InitializeComponent(); \n } \n private void HandleCheck(object sender, RoutedEventArgs e) {\n CheckBox cb = sender as CheckBox; \n\t\t\t\n if (cb.Name == \"cb1\") {\n text1.Text = \"2 state CheckBox is checked.\";\n } else {\n text2.Text = \"3 state CheckBox is checked.\"; \n }\t\n }\n private void HandleUnchecked(object sender, RoutedEventArgs e) {\n CheckBox cb = sender as CheckBox; \n\t\t\t\n if (cb.Name == \"cb1\") {\n text1.Text = \"2 state CheckBox is unchecked.\"; \n } else {\n text2.Text = \"3 state CheckBox is unchecked.\"; \n }\n } \n private void HandleThirdState(object sender, RoutedEventArgs e) {\n CheckBox cb = sender as CheckBox; \n text2.Text = \"3 state CheckBox is in indeterminate state.\"; \n }\n } \n} "
},
{
"code": null,
"e": 11212,
"s": 11128,
"text": "When you compile and execute the above code, it will produce the following output −"
},
{
"code": null,
"e": 11316,
"s": 11212,
"text": "We recommend you to execute the above example code and experiment with some other properties and events"
},
{
"code": null,
"e": 11323,
"s": 11316,
"text": " Print"
},
{
"code": null,
"e": 11334,
"s": 11323,
"text": " Add Notes"
}
] |
How to be Pythonic and why you should care | by Robert Clark | Towards Data Science | I’ve officially been writing code for over a dozen years now with the last 5 as a full-time software engineer, and while I still have MUCH to learn (a lifetime of learning to be exact!), I have seen my fair share of software and have (dare I say) developed my skills immensely in the field during that time. I still remember some of the first programs I ever wrote, and cringe in bed at night as I relive the nightmares of my days as a beginner programmer. While I will never escape the crimes of my past (writing quintuple-nested loops is the biggest of those sins), perhaps I can partially redeem myself, even if only slightly, by helping other developers who are fresh into the field learn a few best practices to write faster, cleaner, and better code.
As with nearly every programming language, there are certain stylistic and conventional guidelines that are accepted by the Python community to promote unified, maintainable, and concise applications that are written the way the language intended them to be written. These guidelines range from proper variable, class, and module naming conventions, to looping structures, and even the proper way to wrap lines of code. The name “Pythonic” was coined to describe any program, function, or block of code that follows these guidelines and takes advantage of Python’s unique capabilities.
Why does all of this matter? This question is open to many interpretations, but a few key reasons why you should care come down to the clarity, efficiency, and credibility of the code. Let’s break these down further.
The clarity of your code is paramount to your success if you want to be a developer. As you grow in the field, you will likely work with others at some point in time, which will require peers to read your code. If your code is written poorly, it can be a nightmare for others to decipher your intentions, even in short chunks. Take the following example from the r/badcode subreddit:
Does this code work? Yup. Does the function name describe the function’s purpose? Sure does. Is it easy to identify what this code is supposed to accomplish if you changed the function name? Probably not without spending an hour analyzing it.
As is the case of every beginning developer I have known (myself included), there is a commonly-held mentality of “it works — don’t touch it” when it comes to code. The moment we can write something that solves our problem, we are afraid of doing anything to the code in fear that we will break everything and be unable to fix it again.
I would encourage any developer to break this mentality as early as possible (this goes for all languages). Even if you created the poorly-written code yourself, it is often difficult to return to it a week, month, or even a year later and attempt to unravel its mystery. To make matters worse, if you can’t decipher the code yourself, how do you expect fellow teammates or collaborators to uncover the meaning?
By writing programs the way the language was intended, developers should naturally be writing code that looks similar to that of their peers. This makes it easy to understand, easy to share, and easy to update.
Back when I was interning in college, one of my fellow interns I met on the job told me “don’t bother writing something that’s already been done in Python, because you won’t be able to write something better.” While I was originally frustrated by this depressing thought, I eventually realized there was some truth to his statement. Python has been around for nearly three decades at this point and has quickly become one of the most popular languages by developers around the world. Python is also known for containing an abundance of libraries that can do almost anything you want or need. Many of these libraries and features see thousands of members creating updates over several years, squeezing as much performance out of every line of code as possible. While you are certainly welcome to writing your own optimal string comparison function, chances are what you come up with won’t be any faster than what already exists, and the time spent developing the new function could have been spent working on the actual problem you are attempting to solve. In general, look for a built-in function or data type that achieves what you are looking for. Chances are, this will be the fastest way to complete a task. If not, check if there are any libraries or packages that can be installed which do what you need. If you still don’t have a solution, now’s the time to create your own!
For anyone who first learned how to program in a language other than Python, it’s generally clear which language the developer came from. Take the following problem as an example:
Find the sum of all numbers between 10 and 1,000
A C (or C++) developer would probably write something along the following lines:
int a = 10;int b = 1000;int total_sum = 0;while (b >= a) { total_sum += a; a++;}
A direct Python re-write of this would look very similar:
a = 10b = 1000total_sum = 0while b >= a: total_sum += a a += 1
While the above statement will yield the expected output, most Python developers would throw a fit over this code, complaining that it isn’t Pythonic and doesn’t leverage the language’s power. Starting fresh, here’s how you can solve the problem the Pythonic way:
total_sum = sum(range(10, 1001))
This single line of code generates the exact same result as above (for the record, I did intend to write 1001 in the code as Python’s range command has an inclusive lower bound and a non-inclusive upper bound, meaning the lower number will be a part of the loop, while the higher number will not). If you were to write Python code using the first example, your credibility as a Python developer would go down as the Python community is very passionate about writing code following the guidelines. Here’s another example:
Determine if a particular string is in an array
For most non-Python developers, the first solution would probably look something like this:
#include <stdbool.h>char * arr[] = {"apples", "oranges", "bananas", "grapes"};char * s = "cherries";bool found = false;int len = sizeof(arr) / sizeof(arr[0]);for (int i = 0; i < len; i++) { if (!strcmp(arr[i], s)) { found = true; }}
As before, a direct Python translation would be:
arr = ["apples", "oranges", "bananas", "grapes"]s = "cherries"found = Falsesize = len(arr)for i in range(0, size): if arr[i] == s: found = True
As I’m sure you guessed, there’s a much simpler way to write this in Python:
arr = ["apples", "oranges", "bananas", "grapes"]found = "cherries" in arr
No matter which method you choose above, found will always evaluate to False (or false) in the end. The last choice, however, is the clear champion when it comes to Pythonic code. It is concise and easily understandable. Even those that have never read Python (or any code for that matter) have a chance at comprehending the intention of this last block unlike the previous two.
The final example is one of my favorite tools in Python, list comprehension. This technique allows you to embed a loop inside a list to create a new list. Consider the following:
Double the value of every even value in an array
First, here’s the C code:
int[] arr = { 1, 2, 3, 4, 5, 6 };int length = sizeof(arr) / sizeof(arr[0]);for (int i = 0; i < length; i++) { if (arr[i] % 2 == 0) { arr[i] *= 2 }}
And the direct Python translation:
arr = [1, 2, 3, 4, 5, 6]length = len(arr)for i in range(0, length): if arr[i] % 2 == 0: arr[i] *= 2
Now the Pythonic way:
arr = [1, 2, 3, 4, 5, 6]arr = [x * 2 if x % 2 == 0 else x for x in arr]
This might look funny at first if you have never seen list comprehension in action. I’ve found it’s often easiest to look at list comprehension from right to left. First, it iterates through every element in the list for x in arr, then it checks if the element is even if x % 2 == 0. If so, it doubles the number x * 2, and stays the same if not else x. Whatever the element ends up as, it gets appended to a new list. In our case, we are overwriting the original value of arr with the new list.
These are just a few common ways to make code Pythonic. You likely noticed that all of these examples involved loops of some sort. While there are many ways to write Pythonic code, a great practice is to ask yourself if you truly need a loop or if it can be replaced with an idiomatic substitute.
If you care about your credibility in the software world and want to proudly call yourself a Python developer, make sure you know and use some of these techniques when applicable in your code.
Hopefully you now understand the importance of writing Pythonic code. At this point, you are likely wondering what some of the guidelines are and how you can follow them. Allow me to introduce you to the Python Enhancement Proposal #8 (PEP 8). For those that are unfamiliar with PEPs, they are proposals written by the community designed to improve some aspect of Python, ranging from performance, to new features, and documentation. The 8th proposal, specifically, provides recommendations on styling guidelines and conventions. This is an often cited resource on how to be Pythonic and I highly recommend giving it a read if you haven’t already. Here are some of the topics I find most important:
Naming conventions are important for any language to provide a common means of identifying types and objects. Here’s an abridged version of the naming conventions:
Packages/Modules: Must use all-lowercase. Underscores can be used if necessary, but are discouraged. Ex: package or module.py.
Classes: Must use CapWords. Recommended to not use the word Class in the name. Ex: class BasketballTeam:.
Constants: Must use screaming snake case. Ex: API_URL = '...'.
Functions/Variables: Must use standard snake case. Ex: home_team_points = ... or def final_boxscore(...).
Function/Method Arguments: Must use standard snake case. Ex: home_team_name.
Comments are an important aid to the clarity of code. I generally recommend adding a comment above any section of code who’s purpose wouldn’t be immediately obvious to someone else. In general, comments should be in complete sentences, located above code blocks, and written in English. Additionally, the usage of documentation strings (or “docstrings”) are recommended to record the purpose of functions as well describe the types, names, and descriptions of inputs and outputs, if applicable. PEP 257 contains great information on how to use docstrings.
One of the more controversial topics in Python development pertains to line wrapping. PEP 8 calls for every line of code to be less than or equal to 79 characters. Some embedded systems have limited screen sizes that can only display as many as 80 characters on a line, which would require ugly wrapping of code if it were any longer. Additionally, if a particular line of code is hundreds of characters long, it can get very difficult to read as many variables and function calls can be lost within the line.
While this likely won’t be an issue in most cases, sometimes a line of code requires lots of real estate, especially if it contains long variable names or complex list comprehensions. A few ways to combat this are to create a newline every time you use a comma in function calls. For example, replace
some_function(first_var, second_var, third_var, ... twelfth_var)
with
some_function(first_var, second_var, third_var, ... twelfth_var)
The two blocks above will be executed exactly the same. While within parenthesis (or a tuple), any code on a new-line after a comma will be included with the statement as the next parameter.
Python also allows the use of backslashes to separate code that isn’t contained in a tuple or other similar object. For example, replace
if first_boolean_variable == accepted_value and not second_boolean_variable: # This is all one line print('Accepted')
with
if first_boolean_variable == accepted_value and \ not second_boolean_variable: # This is a second line print('Accepted')
While these changes will add additional lines of code to your program, it becomes much easier to read, especially on a range of display types and sizes.
Another commonly referenced resource is the Zen of Python. The following short prose is the sole contents of PEP 20, written by Tim Peters:
Beautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren’t special enough to break the rules.Although practicality beats purity.Errors should never pass silently.Unless explicitly silenced.In the face of ambiguity, refuse the temptation to guess.There should be one — and preferably only one — obvious way to do it.Although that way may not be obvious at first unless you’re Dutch.Now is better than never.Although never is often better than *right* now.If the implementation is hard to explain, it’s a bad idea.If the implementation is easy to explain, it may be a good idea.Namespaces are one honking great idea — let’s do more of those!
While the lines above are fairly self-explanatory, the overarching theme can be summarized by the 7th note: “Readability counts.” To me, this means that code should be written in a way that any Python developer, regardless of his or her experience, should be able to read and understand the code. Python uses a simple syntax which is closer to natural English than nearly all other languages. As such, the code should be simple and beautiful. The best way to get a message across in English is to deliver it in a concise manner. The same goes for Python.
No matter what your code is working to achieve, always remember the Zen of Python. If your code doesn’t follow these principles, then it isn’t a truly Pythonic application.
We’ve now learned why Pythonic code is important, what some key principles are, and a few examples of Pythonic code. After all that, it’s time we learn how to actually apply these techniques. Luckily for us, there are several tools that we can use to check if our code adheres to Python’s guidelines. The first tool, pycodestyle (formerly pep8) checks any specified Python module to determine if it violates any of the guidelines listed in PEP 8. More information can be found on the GitHub repository.
Another commonly-used tool is pylint. The basic premise of pylint is the same as pycodestyle, but it goes several steps further and is more aggressive with its reach and suggestions. I personally prefer pycodestyle as I’ve encountered several false-positives in the past with pylint. While there are ways to combat these false-positives, I found it wasn’t worth it to continually alter my source code to work around and explain why certain lines didn’t pass but should.
I should also note that additional code validation and linting tools exist, but the two mentioned above are the most commonly used resources.
EDIT: Thanks to Tarun Chadha for mentioning that these tools can be integrated with popular IDEs, such as PyCharm and Visual Studio Code.
If you made it this far, you should now be armed with the knowledge to write faster, cleaner, and better Python applications. Not only will this aid your development skills, it will also command greater respect from the Python community. Practice this trade, and you just might be considered in the sacred realm of the great Python developers. | [
{
"code": null,
"e": 929,
"s": 172,
"text": "I’ve officially been writing code for over a dozen years now with the last 5 as a full-time software engineer, and while I still have MUCH to learn (a lifetime of learning to be exact!), I have seen my fair share of software and have (dare I say) developed my skills immensely in the field during that time. I still remember some of the first programs I ever wrote, and cringe in bed at night as I relive the nightmares of my days as a beginner programmer. While I will never escape the crimes of my past (writing quintuple-nested loops is the biggest of those sins), perhaps I can partially redeem myself, even if only slightly, by helping other developers who are fresh into the field learn a few best practices to write faster, cleaner, and better code."
},
{
"code": null,
"e": 1515,
"s": 929,
"text": "As with nearly every programming language, there are certain stylistic and conventional guidelines that are accepted by the Python community to promote unified, maintainable, and concise applications that are written the way the language intended them to be written. These guidelines range from proper variable, class, and module naming conventions, to looping structures, and even the proper way to wrap lines of code. The name “Pythonic” was coined to describe any program, function, or block of code that follows these guidelines and takes advantage of Python’s unique capabilities."
},
{
"code": null,
"e": 1732,
"s": 1515,
"text": "Why does all of this matter? This question is open to many interpretations, but a few key reasons why you should care come down to the clarity, efficiency, and credibility of the code. Let’s break these down further."
},
{
"code": null,
"e": 2116,
"s": 1732,
"text": "The clarity of your code is paramount to your success if you want to be a developer. As you grow in the field, you will likely work with others at some point in time, which will require peers to read your code. If your code is written poorly, it can be a nightmare for others to decipher your intentions, even in short chunks. Take the following example from the r/badcode subreddit:"
},
{
"code": null,
"e": 2359,
"s": 2116,
"text": "Does this code work? Yup. Does the function name describe the function’s purpose? Sure does. Is it easy to identify what this code is supposed to accomplish if you changed the function name? Probably not without spending an hour analyzing it."
},
{
"code": null,
"e": 2696,
"s": 2359,
"text": "As is the case of every beginning developer I have known (myself included), there is a commonly-held mentality of “it works — don’t touch it” when it comes to code. The moment we can write something that solves our problem, we are afraid of doing anything to the code in fear that we will break everything and be unable to fix it again."
},
{
"code": null,
"e": 3108,
"s": 2696,
"text": "I would encourage any developer to break this mentality as early as possible (this goes for all languages). Even if you created the poorly-written code yourself, it is often difficult to return to it a week, month, or even a year later and attempt to unravel its mystery. To make matters worse, if you can’t decipher the code yourself, how do you expect fellow teammates or collaborators to uncover the meaning?"
},
{
"code": null,
"e": 3319,
"s": 3108,
"text": "By writing programs the way the language was intended, developers should naturally be writing code that looks similar to that of their peers. This makes it easy to understand, easy to share, and easy to update."
},
{
"code": null,
"e": 4701,
"s": 3319,
"text": "Back when I was interning in college, one of my fellow interns I met on the job told me “don’t bother writing something that’s already been done in Python, because you won’t be able to write something better.” While I was originally frustrated by this depressing thought, I eventually realized there was some truth to his statement. Python has been around for nearly three decades at this point and has quickly become one of the most popular languages by developers around the world. Python is also known for containing an abundance of libraries that can do almost anything you want or need. Many of these libraries and features see thousands of members creating updates over several years, squeezing as much performance out of every line of code as possible. While you are certainly welcome to writing your own optimal string comparison function, chances are what you come up with won’t be any faster than what already exists, and the time spent developing the new function could have been spent working on the actual problem you are attempting to solve. In general, look for a built-in function or data type that achieves what you are looking for. Chances are, this will be the fastest way to complete a task. If not, check if there are any libraries or packages that can be installed which do what you need. If you still don’t have a solution, now’s the time to create your own!"
},
{
"code": null,
"e": 4881,
"s": 4701,
"text": "For anyone who first learned how to program in a language other than Python, it’s generally clear which language the developer came from. Take the following problem as an example:"
},
{
"code": null,
"e": 4930,
"s": 4881,
"text": "Find the sum of all numbers between 10 and 1,000"
},
{
"code": null,
"e": 5011,
"s": 4930,
"text": "A C (or C++) developer would probably write something along the following lines:"
},
{
"code": null,
"e": 5098,
"s": 5011,
"text": "int a = 10;int b = 1000;int total_sum = 0;while (b >= a) { total_sum += a; a++;}"
},
{
"code": null,
"e": 5156,
"s": 5098,
"text": "A direct Python re-write of this would look very similar:"
},
{
"code": null,
"e": 5225,
"s": 5156,
"text": "a = 10b = 1000total_sum = 0while b >= a: total_sum += a a += 1"
},
{
"code": null,
"e": 5489,
"s": 5225,
"text": "While the above statement will yield the expected output, most Python developers would throw a fit over this code, complaining that it isn’t Pythonic and doesn’t leverage the language’s power. Starting fresh, here’s how you can solve the problem the Pythonic way:"
},
{
"code": null,
"e": 5522,
"s": 5489,
"text": "total_sum = sum(range(10, 1001))"
},
{
"code": null,
"e": 6043,
"s": 5522,
"text": "This single line of code generates the exact same result as above (for the record, I did intend to write 1001 in the code as Python’s range command has an inclusive lower bound and a non-inclusive upper bound, meaning the lower number will be a part of the loop, while the higher number will not). If you were to write Python code using the first example, your credibility as a Python developer would go down as the Python community is very passionate about writing code following the guidelines. Here’s another example:"
},
{
"code": null,
"e": 6091,
"s": 6043,
"text": "Determine if a particular string is in an array"
},
{
"code": null,
"e": 6183,
"s": 6091,
"text": "For most non-Python developers, the first solution would probably look something like this:"
},
{
"code": null,
"e": 6429,
"s": 6183,
"text": "#include <stdbool.h>char * arr[] = {\"apples\", \"oranges\", \"bananas\", \"grapes\"};char * s = \"cherries\";bool found = false;int len = sizeof(arr) / sizeof(arr[0]);for (int i = 0; i < len; i++) { if (!strcmp(arr[i], s)) { found = true; }}"
},
{
"code": null,
"e": 6478,
"s": 6429,
"text": "As before, a direct Python translation would be:"
},
{
"code": null,
"e": 6632,
"s": 6478,
"text": "arr = [\"apples\", \"oranges\", \"bananas\", \"grapes\"]s = \"cherries\"found = Falsesize = len(arr)for i in range(0, size): if arr[i] == s: found = True"
},
{
"code": null,
"e": 6709,
"s": 6632,
"text": "As I’m sure you guessed, there’s a much simpler way to write this in Python:"
},
{
"code": null,
"e": 6783,
"s": 6709,
"text": "arr = [\"apples\", \"oranges\", \"bananas\", \"grapes\"]found = \"cherries\" in arr"
},
{
"code": null,
"e": 7162,
"s": 6783,
"text": "No matter which method you choose above, found will always evaluate to False (or false) in the end. The last choice, however, is the clear champion when it comes to Pythonic code. It is concise and easily understandable. Even those that have never read Python (or any code for that matter) have a chance at comprehending the intention of this last block unlike the previous two."
},
{
"code": null,
"e": 7341,
"s": 7162,
"text": "The final example is one of my favorite tools in Python, list comprehension. This technique allows you to embed a loop inside a list to create a new list. Consider the following:"
},
{
"code": null,
"e": 7390,
"s": 7341,
"text": "Double the value of every even value in an array"
},
{
"code": null,
"e": 7416,
"s": 7390,
"text": "First, here’s the C code:"
},
{
"code": null,
"e": 7577,
"s": 7416,
"text": "int[] arr = { 1, 2, 3, 4, 5, 6 };int length = sizeof(arr) / sizeof(arr[0]);for (int i = 0; i < length; i++) { if (arr[i] % 2 == 0) { arr[i] *= 2 }}"
},
{
"code": null,
"e": 7612,
"s": 7577,
"text": "And the direct Python translation:"
},
{
"code": null,
"e": 7722,
"s": 7612,
"text": "arr = [1, 2, 3, 4, 5, 6]length = len(arr)for i in range(0, length): if arr[i] % 2 == 0: arr[i] *= 2"
},
{
"code": null,
"e": 7744,
"s": 7722,
"text": "Now the Pythonic way:"
},
{
"code": null,
"e": 7816,
"s": 7744,
"text": "arr = [1, 2, 3, 4, 5, 6]arr = [x * 2 if x % 2 == 0 else x for x in arr]"
},
{
"code": null,
"e": 8312,
"s": 7816,
"text": "This might look funny at first if you have never seen list comprehension in action. I’ve found it’s often easiest to look at list comprehension from right to left. First, it iterates through every element in the list for x in arr, then it checks if the element is even if x % 2 == 0. If so, it doubles the number x * 2, and stays the same if not else x. Whatever the element ends up as, it gets appended to a new list. In our case, we are overwriting the original value of arr with the new list."
},
{
"code": null,
"e": 8609,
"s": 8312,
"text": "These are just a few common ways to make code Pythonic. You likely noticed that all of these examples involved loops of some sort. While there are many ways to write Pythonic code, a great practice is to ask yourself if you truly need a loop or if it can be replaced with an idiomatic substitute."
},
{
"code": null,
"e": 8802,
"s": 8609,
"text": "If you care about your credibility in the software world and want to proudly call yourself a Python developer, make sure you know and use some of these techniques when applicable in your code."
},
{
"code": null,
"e": 9501,
"s": 8802,
"text": "Hopefully you now understand the importance of writing Pythonic code. At this point, you are likely wondering what some of the guidelines are and how you can follow them. Allow me to introduce you to the Python Enhancement Proposal #8 (PEP 8). For those that are unfamiliar with PEPs, they are proposals written by the community designed to improve some aspect of Python, ranging from performance, to new features, and documentation. The 8th proposal, specifically, provides recommendations on styling guidelines and conventions. This is an often cited resource on how to be Pythonic and I highly recommend giving it a read if you haven’t already. Here are some of the topics I find most important:"
},
{
"code": null,
"e": 9665,
"s": 9501,
"text": "Naming conventions are important for any language to provide a common means of identifying types and objects. Here’s an abridged version of the naming conventions:"
},
{
"code": null,
"e": 9792,
"s": 9665,
"text": "Packages/Modules: Must use all-lowercase. Underscores can be used if necessary, but are discouraged. Ex: package or module.py."
},
{
"code": null,
"e": 9898,
"s": 9792,
"text": "Classes: Must use CapWords. Recommended to not use the word Class in the name. Ex: class BasketballTeam:."
},
{
"code": null,
"e": 9961,
"s": 9898,
"text": "Constants: Must use screaming snake case. Ex: API_URL = '...'."
},
{
"code": null,
"e": 10067,
"s": 9961,
"text": "Functions/Variables: Must use standard snake case. Ex: home_team_points = ... or def final_boxscore(...)."
},
{
"code": null,
"e": 10144,
"s": 10067,
"text": "Function/Method Arguments: Must use standard snake case. Ex: home_team_name."
},
{
"code": null,
"e": 10700,
"s": 10144,
"text": "Comments are an important aid to the clarity of code. I generally recommend adding a comment above any section of code who’s purpose wouldn’t be immediately obvious to someone else. In general, comments should be in complete sentences, located above code blocks, and written in English. Additionally, the usage of documentation strings (or “docstrings”) are recommended to record the purpose of functions as well describe the types, names, and descriptions of inputs and outputs, if applicable. PEP 257 contains great information on how to use docstrings."
},
{
"code": null,
"e": 11210,
"s": 10700,
"text": "One of the more controversial topics in Python development pertains to line wrapping. PEP 8 calls for every line of code to be less than or equal to 79 characters. Some embedded systems have limited screen sizes that can only display as many as 80 characters on a line, which would require ugly wrapping of code if it were any longer. Additionally, if a particular line of code is hundreds of characters long, it can get very difficult to read as many variables and function calls can be lost within the line."
},
{
"code": null,
"e": 11511,
"s": 11210,
"text": "While this likely won’t be an issue in most cases, sometimes a line of code requires lots of real estate, especially if it contains long variable names or complex list comprehensions. A few ways to combat this are to create a newline every time you use a comma in function calls. For example, replace"
},
{
"code": null,
"e": 11576,
"s": 11511,
"text": "some_function(first_var, second_var, third_var, ... twelfth_var)"
},
{
"code": null,
"e": 11581,
"s": 11576,
"text": "with"
},
{
"code": null,
"e": 11698,
"s": 11581,
"text": "some_function(first_var, second_var, third_var, ... twelfth_var)"
},
{
"code": null,
"e": 11889,
"s": 11698,
"text": "The two blocks above will be executed exactly the same. While within parenthesis (or a tuple), any code on a new-line after a comma will be included with the statement as the next parameter."
},
{
"code": null,
"e": 12026,
"s": 11889,
"text": "Python also allows the use of backslashes to separate code that isn’t contained in a tuple or other similar object. For example, replace"
},
{
"code": null,
"e": 12148,
"s": 12026,
"text": "if first_boolean_variable == accepted_value and not second_boolean_variable: # This is all one line print('Accepted')"
},
{
"code": null,
"e": 12153,
"s": 12148,
"text": "with"
},
{
"code": null,
"e": 12280,
"s": 12153,
"text": "if first_boolean_variable == accepted_value and \\ not second_boolean_variable: # This is a second line print('Accepted')"
},
{
"code": null,
"e": 12433,
"s": 12280,
"text": "While these changes will add additional lines of code to your program, it becomes much easier to read, especially on a range of display types and sizes."
},
{
"code": null,
"e": 12573,
"s": 12433,
"text": "Another commonly referenced resource is the Zen of Python. The following short prose is the sole contents of PEP 20, written by Tim Peters:"
},
{
"code": null,
"e": 13377,
"s": 12573,
"text": "Beautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren’t special enough to break the rules.Although practicality beats purity.Errors should never pass silently.Unless explicitly silenced.In the face of ambiguity, refuse the temptation to guess.There should be one — and preferably only one — obvious way to do it.Although that way may not be obvious at first unless you’re Dutch.Now is better than never.Although never is often better than *right* now.If the implementation is hard to explain, it’s a bad idea.If the implementation is easy to explain, it may be a good idea.Namespaces are one honking great idea — let’s do more of those!"
},
{
"code": null,
"e": 13932,
"s": 13377,
"text": "While the lines above are fairly self-explanatory, the overarching theme can be summarized by the 7th note: “Readability counts.” To me, this means that code should be written in a way that any Python developer, regardless of his or her experience, should be able to read and understand the code. Python uses a simple syntax which is closer to natural English than nearly all other languages. As such, the code should be simple and beautiful. The best way to get a message across in English is to deliver it in a concise manner. The same goes for Python."
},
{
"code": null,
"e": 14105,
"s": 13932,
"text": "No matter what your code is working to achieve, always remember the Zen of Python. If your code doesn’t follow these principles, then it isn’t a truly Pythonic application."
},
{
"code": null,
"e": 14608,
"s": 14105,
"text": "We’ve now learned why Pythonic code is important, what some key principles are, and a few examples of Pythonic code. After all that, it’s time we learn how to actually apply these techniques. Luckily for us, there are several tools that we can use to check if our code adheres to Python’s guidelines. The first tool, pycodestyle (formerly pep8) checks any specified Python module to determine if it violates any of the guidelines listed in PEP 8. More information can be found on the GitHub repository."
},
{
"code": null,
"e": 15078,
"s": 14608,
"text": "Another commonly-used tool is pylint. The basic premise of pylint is the same as pycodestyle, but it goes several steps further and is more aggressive with its reach and suggestions. I personally prefer pycodestyle as I’ve encountered several false-positives in the past with pylint. While there are ways to combat these false-positives, I found it wasn’t worth it to continually alter my source code to work around and explain why certain lines didn’t pass but should."
},
{
"code": null,
"e": 15220,
"s": 15078,
"text": "I should also note that additional code validation and linting tools exist, but the two mentioned above are the most commonly used resources."
},
{
"code": null,
"e": 15358,
"s": 15220,
"text": "EDIT: Thanks to Tarun Chadha for mentioning that these tools can be integrated with popular IDEs, such as PyCharm and Visual Studio Code."
}
] |
What are single row and multiple row subqueries? | A single-row subquery is used when the outer query's results are based on a single, unknown value. Although this query type is formally called "single-row," the name implies that the query returns multiple columns-but only one row of results. However, a single-row subquery can return only one row of results consisting of only one column to the outer query.
In the below SELECT query, inner MySQL returns only one row i.e. the minimum salary for the company. It, in turn, uses this value to compare the salary of all the employees and displays only those, whose salary is equal to minimum salary.
SELECT first_name, salary, department_id
FROM employees
WHERE salary = (SELECT MIN (salary)
FROM employees);
A HAVING clause is used when the group results of a query need to be restricted based on some condition. If a subquery's result must be compared with a group function, you must nest the inner query in the outer query's HAVING clause.
SELECT department_id, MIN (salary)
FROM employees
GROUP BY department_id
HAVING MIN (salary) < (SELECT AVG (salary)
FROM employees)
Multiple-row subqueries are nested queries that can return more than one row of results to the parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING clauses. Since it returns multiple rows, it must be handled by set comparison operators (IN, ALL, ANY).While IN operator holds the same meaning as discussed in the earlier chapter, ANY operator compares a specified value to each value returned by the subquery while ALL compares a value to every value returned by a subquery. The below query will show the error because single-row subquery returns multiple rows.
SELECT first_name, department_id FROM employees WHERE department_id = (SELECT department_id FROM employees WHERE LOCATION_ID = 100) | [
{
"code": null,
"e": 1421,
"s": 1062,
"text": "A single-row subquery is used when the outer query's results are based on a single, unknown value. Although this query type is formally called \"single-row,\" the name implies that the query returns multiple columns-but only one row of results. However, a single-row subquery can return only one row of results consisting of only one column to the outer query."
},
{
"code": null,
"e": 1660,
"s": 1421,
"text": "In the below SELECT query, inner MySQL returns only one row i.e. the minimum salary for the company. It, in turn, uses this value to compare the salary of all the employees and displays only those, whose salary is equal to minimum salary."
},
{
"code": null,
"e": 1769,
"s": 1660,
"text": "SELECT first_name, salary, department_id\nFROM employees\nWHERE salary = (SELECT MIN (salary)\nFROM employees);"
},
{
"code": null,
"e": 2003,
"s": 1769,
"text": "A HAVING clause is used when the group results of a query need to be restricted based on some condition. If a subquery's result must be compared with a group function, you must nest the inner query in the outer query's HAVING clause."
},
{
"code": null,
"e": 2135,
"s": 2003,
"text": "SELECT department_id, MIN (salary)\nFROM employees\nGROUP BY department_id\nHAVING MIN (salary) < (SELECT AVG (salary)\nFROM employees)"
},
{
"code": null,
"e": 2724,
"s": 2135,
"text": "Multiple-row subqueries are nested queries that can return more than one row of results to the parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING clauses. Since it returns multiple rows, it must be handled by set comparison operators (IN, ALL, ANY).While IN operator holds the same meaning as discussed in the earlier chapter, ANY operator compares a specified value to each value returned by the subquery while ALL compares a value to every value returned by a subquery. The below query will show the error because single-row subquery returns multiple rows."
},
{
"code": null,
"e": 2856,
"s": 2724,
"text": "SELECT first_name, department_id FROM employees WHERE department_id = (SELECT department_id FROM employees WHERE LOCATION_ID = 100)"
}
] |
jQuery - removeClass( class ) Method | The removeClass( class ) method removes all or the specified class(es) from the set of matched elements.
Here is the simple syntax to use this method −
selector.removeClass( class )
Here is the description of all the parameters used by this method −
class − The name of CSS class.
class − The name of CSS class.
Following example would remove class red from the first para −
<html>
<head>
<title>The Selecter Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("p#pid1").removeClass("red");
});
</script>
<style>
.red { color:red; }
.green { color:green; }
</style>
</head>
<body>
<p class = "red" id = "pid1">This is first paragraph.</p>
<p class = "green" id = "pid2">This is second paragraph.</p>
</body>
</html>
This will produce following result −
This is first paragraph.
This is second paragraph.
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2427,
"s": 2322,
"text": "The removeClass( class ) method removes all or the specified class(es) from the set of matched elements."
},
{
"code": null,
"e": 2474,
"s": 2427,
"text": "Here is the simple syntax to use this method −"
},
{
"code": null,
"e": 2505,
"s": 2474,
"text": "selector.removeClass( class )\n"
},
{
"code": null,
"e": 2573,
"s": 2505,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 2604,
"s": 2573,
"text": "class − The name of CSS class."
},
{
"code": null,
"e": 2635,
"s": 2604,
"text": "class − The name of CSS class."
},
{
"code": null,
"e": 2698,
"s": 2635,
"text": "Following example would remove class red from the first para −"
},
{
"code": null,
"e": 3344,
"s": 2698,
"text": "<html>\n <head>\n <title>The Selecter Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n \n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"p#pid1\").removeClass(\"red\");\n });\n </script>\n\t\t\n <style>\n .red { color:red; }\n .green { color:green; }\n </style>\n </head>\n\t\n <body>\n <p class = \"red\" id = \"pid1\">This is first paragraph.</p>\n <p class = \"green\" id = \"pid2\">This is second paragraph.</p>\n </body>\n</html>"
},
{
"code": null,
"e": 3381,
"s": 3344,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3406,
"s": 3381,
"text": "This is first paragraph."
},
{
"code": null,
"e": 3432,
"s": 3406,
"text": "This is second paragraph."
},
{
"code": null,
"e": 3465,
"s": 3432,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3479,
"s": 3465,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 3514,
"s": 3479,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3528,
"s": 3514,
"text": " Pratik Singh"
},
{
"code": null,
"e": 3563,
"s": 3528,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3580,
"s": 3563,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3613,
"s": 3580,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 3641,
"s": 3613,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3674,
"s": 3641,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3695,
"s": 3674,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 3727,
"s": 3695,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 3744,
"s": 3727,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 3751,
"s": 3744,
"text": " Print"
},
{
"code": null,
"e": 3762,
"s": 3751,
"text": " Add Notes"
}
] |
How to open MySQL command line on Windows10? | To open the MySQL command line from cmd, you need to use username root with your password.
Follow the below given steps. The syntax is as follows −
cd \> press enter key
cd Program Files\MySQL\MySQL Server 8.0\bin> press enter key
C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -uroot -p press enter key
Enter password: ******
Here is the step by step instruction to open MySQL command line. First, Go to START > RUN or Open Run using Windows+R command −
Type CMD and hit OK button −
After pressing OK button, the CMD will open −
Now you need to follow the above instruction. First reach your bin directory and follow the below given steps −
Step 1 −
Step 2 −
Now write the below command to open MySQL command line.
Step 3 −
Now press the enter button.
Step 4 −
After that you need to provide the password.
Step 5 −
After that you need to press enter key to open the MySQL command line − | [
{
"code": null,
"e": 1153,
"s": 1062,
"text": "To open the MySQL command line from cmd, you need to use username root with your password."
},
{
"code": null,
"e": 1210,
"s": 1153,
"text": "Follow the below given steps. The syntax is as follows −"
},
{
"code": null,
"e": 1392,
"s": 1210,
"text": "cd \\> press enter key\ncd Program Files\\MySQL\\MySQL Server 8.0\\bin> press enter key\nC:\\Program Files\\MySQL\\MySQL Server 8.0\\bin>mysql -uroot -p press enter key\nEnter password: ******"
},
{
"code": null,
"e": 1520,
"s": 1392,
"text": "Here is the step by step instruction to open MySQL command line. First, Go to START > RUN or Open Run using Windows+R command −"
},
{
"code": null,
"e": 1549,
"s": 1520,
"text": "Type CMD and hit OK button −"
},
{
"code": null,
"e": 1595,
"s": 1549,
"text": "After pressing OK button, the CMD will open −"
},
{
"code": null,
"e": 1707,
"s": 1595,
"text": "Now you need to follow the above instruction. First reach your bin directory and follow the below given steps −"
},
{
"code": null,
"e": 1716,
"s": 1707,
"text": "Step 1 −"
},
{
"code": null,
"e": 1725,
"s": 1716,
"text": "Step 2 −"
},
{
"code": null,
"e": 1781,
"s": 1725,
"text": "Now write the below command to open MySQL command line."
},
{
"code": null,
"e": 1790,
"s": 1781,
"text": "Step 3 −"
},
{
"code": null,
"e": 1818,
"s": 1790,
"text": "Now press the enter button."
},
{
"code": null,
"e": 1827,
"s": 1818,
"text": "Step 4 −"
},
{
"code": null,
"e": 1872,
"s": 1827,
"text": "After that you need to provide the password."
},
{
"code": null,
"e": 1881,
"s": 1872,
"text": "Step 5 −"
},
{
"code": null,
"e": 1953,
"s": 1881,
"text": "After that you need to press enter key to open the MySQL command line −"
}
] |
Explain widening with objects in Java. | Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) namely, boolean, byte, char, short, int, long, float, double and, reference datatypes (arrays and objects).
Type Casting/type conversion − Converting one primitive datatype into another is known as type casting (type conversion) in Java. You can cast the primitive datatypes in two ways namely, Widening and, Narrowing.
Widening − Converting a lower datatype to a higher datatype is known as widening. In this case the casting/conversion is done automatically therefore, it is known as implicit type casting. In this case both datatypes should be compatible with each other.
public class WideningExample {
public static void main(String args[]){
char ch = 'C';
int i = ch;
System.out.println(i);
}
}
Integer value of the given character: 67
you can cast the reference(object) of one (class) type to other. But, one of the two classes should inherit the other.
Therefore, if a class inherits the properties of the other conversion of sub class object in to super class type is considered as widening with respect to objects.
In the following Java example, we have two classes namely Person and Student. The Person class has two instance variables name and age and one instance method displayPerson() which displays the name and age.
The Student extends the person class and in addition to the inherited name and age it has two more variables branch and student_id. It has a method displayData() which displays all four values.
In the main method, objects of the both classes created separately and, the super class object is converted in to sub class object.
class Person{
private String name;
private int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
}
}
public class Student extends Person {
public String branch;
public int Student_id;
public Student(String name, int age, String branch, int Student_id){
super(name, age);
this.branch = branch;
this.Student_id = Student_id;
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Branch: "+this.branch);
System.out.println("Student ID: "+this.Student_id);
}
public static void main(String[] args) {
//Creating an object of the Student class
Student student = new Student("Krishna", 20, "IT", 1256);
//Converting the object of Student to Person
Person person = new Person("Krishna", 20);
//Converting the object of student to person
person = (Student) student;
person.displayPerson();
}
}
Data of the Person class:
Name: Krishna
Age: 20
In short, super class reference variable can hold the sub class object. But, using this reference you can access the members of super class only, if you try to access the sub class members a compile time error will be generated.
public static void main(String[] args) {
Person person = new Student("Krishna", 20, "IT", 1256);
person.displayStudent();
}
Student.java:33: error: cannot find symbol
person.dispalyStudent();
^
symbol: method dispalyStudent()
location: variable person of type Person
1 error | [
{
"code": null,
"e": 1289,
"s": 1062,
"text": "Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) namely, boolean, byte, char, short, int, long, float, double and, reference datatypes (arrays and objects)."
},
{
"code": null,
"e": 1501,
"s": 1289,
"text": "Type Casting/type conversion − Converting one primitive datatype into another is known as type casting (type conversion) in Java. You can cast the primitive datatypes in two ways namely, Widening and, Narrowing."
},
{
"code": null,
"e": 1756,
"s": 1501,
"text": "Widening − Converting a lower datatype to a higher datatype is known as widening. In this case the casting/conversion is done automatically therefore, it is known as implicit type casting. In this case both datatypes should be compatible with each other."
},
{
"code": null,
"e": 1905,
"s": 1756,
"text": "public class WideningExample {\n public static void main(String args[]){\n char ch = 'C';\n int i = ch;\n System.out.println(i);\n }\n}"
},
{
"code": null,
"e": 1946,
"s": 1905,
"text": "Integer value of the given character: 67"
},
{
"code": null,
"e": 2065,
"s": 1946,
"text": "you can cast the reference(object) of one (class) type to other. But, one of the two classes should inherit the other."
},
{
"code": null,
"e": 2229,
"s": 2065,
"text": "Therefore, if a class inherits the properties of the other conversion of sub class object in to super class type is considered as widening with respect to objects."
},
{
"code": null,
"e": 2437,
"s": 2229,
"text": "In the following Java example, we have two classes namely Person and Student. The Person class has two instance variables name and age and one instance method displayPerson() which displays the name and age."
},
{
"code": null,
"e": 2631,
"s": 2437,
"text": "The Student extends the person class and in addition to the inherited name and age it has two more variables branch and student_id. It has a method displayData() which displays all four values."
},
{
"code": null,
"e": 2763,
"s": 2631,
"text": "In the main method, objects of the both classes created separately and, the super class object is converted in to sub class object."
},
{
"code": null,
"e": 4024,
"s": 2763,
"text": "class Person{\n private String name;\n private int age;\n public Person(String name, int age){\n this.name = name;\n this.age = age;\n }\n public void displayPerson() {\n System.out.println(\"Data of the Person class: \");\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n }\n}\npublic class Student extends Person {\n public String branch;\n public int Student_id;\n public Student(String name, int age, String branch, int Student_id){\n super(name, age);\n this.branch = branch;\n this.Student_id = Student_id;\n }\n public void displayStudent() {\n System.out.println(\"Data of the Student class: \");\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n System.out.println(\"Branch: \"+this.branch);\n System.out.println(\"Student ID: \"+this.Student_id);\n }\n public static void main(String[] args) {\n //Creating an object of the Student class\n Student student = new Student(\"Krishna\", 20, \"IT\", 1256);\n //Converting the object of Student to Person\n Person person = new Person(\"Krishna\", 20);\n //Converting the object of student to person\n person = (Student) student;\n person.displayPerson();\n }\n}"
},
{
"code": null,
"e": 4072,
"s": 4024,
"text": "Data of the Person class:\nName: Krishna\nAge: 20"
},
{
"code": null,
"e": 4301,
"s": 4072,
"text": "In short, super class reference variable can hold the sub class object. But, using this reference you can access the members of super class only, if you try to access the sub class members a compile time error will be generated."
},
{
"code": null,
"e": 4431,
"s": 4301,
"text": "public static void main(String[] args) {\n Person person = new Student(\"Krishna\", 20, \"IT\", 1256);\n person.displayStudent();\n}"
},
{
"code": null,
"e": 4601,
"s": 4431,
"text": "Student.java:33: error: cannot find symbol\n person.dispalyStudent();\n ^\n symbol: method dispalyStudent()\n location: variable person of type Person\n1 error"
}
] |
Access Data from Twitter API using R and Python | by Michael Galarnyk | Towards Data Science | NOTE: There is an updated version of this tutorial that goes over setting up the Twitter Developer Account and the tweepy library (Python) here.
Using the Twitter API should be an easy thing, but sometimes pictures and simple code can save you that extra 5 minutes. I previously covered how to Access Data from Twitter API using R, but the process has changed as of July 2018.
This post goes first goes over how to setup your Twitter developer account then goes over how you can search tweets using R and Python.
1-) Create a twitter account if you do not already have one.
2-) Apply for a twitter developer account.
3-) Enter phone number if you don’t have one associated with your twitter.
4-) Add account details. Click on continue.
5-) Describe in your own words what you are building. Click on continue.
6-) Submit application.
7-) Check your email associated with your twitter and click Confirm your email.
8-) On the welcome screen, click on Create an app.
9-) Fill out your App details and click on Create (its at the bottom of the page). Make sure you don’t try to make a appName that is already taken.
Review Developer Terms and click on Create.
10-) First, click on Keys and tokens. Second, click on create to get access token and access token secret.
Save your API key, API secret key, Access token, and Access token secret somewhere safe. I should note that you should not try and copy my keys as I regenerated them after this tutorial.
If you want to use R, you can use twitteR (make sure you install first install the twitteR package). twitteR is an R package which provides access to the Twitter API. Most functionality of the API is supported, with a bias towards API calls that are more useful in data analysis as opposed to daily interaction. Read the user vignette if you want to learn more about how to use the package for your various needs. The code below uses the Twitter search API.
#install.packages("twitteR")library(twitteR) # Change consumer_key, consume_secret, access_token, and # access_secret based on your own keysconsumer_key <- ""consumer_secret <-""access_token <- ""access_secret <- "" setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_secret)tw = searchTwitter('@GalarnykMichael', n = 25)d = twListToDF(tw)
The code below uses the python-twitter package (you can install using pip install python-twitter) for searching. You can learn how to make your own query here.
import twitter"""Change ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY and CONSUMER_SECRETto your own. """ACCESS_TOKEN = ''ACCESS_SECRET = ''CONSUMER_KEY = ''CONSUMER_SECRET = ''t = twitter.Api(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, access_token_key=ACCESS_TOKEN, access_token_secret=ACCESS_SECRET)results = t.GetSearch(raw_query="q=from%3AGalarnykMichael&src=typd")
This tutorial was about getting you started with the Twitter API. If you have any questions or thoughts on the tutorial, feel free to reach out in the comments below or through Twitter. If you want to learn how to utilize the Pandas, Matplotlib, or Seaborn libraries, please consider taking my Python for Data Visualization LinkedIn Learning course. | [
{
"code": null,
"e": 317,
"s": 172,
"text": "NOTE: There is an updated version of this tutorial that goes over setting up the Twitter Developer Account and the tweepy library (Python) here."
},
{
"code": null,
"e": 549,
"s": 317,
"text": "Using the Twitter API should be an easy thing, but sometimes pictures and simple code can save you that extra 5 minutes. I previously covered how to Access Data from Twitter API using R, but the process has changed as of July 2018."
},
{
"code": null,
"e": 685,
"s": 549,
"text": "This post goes first goes over how to setup your Twitter developer account then goes over how you can search tweets using R and Python."
},
{
"code": null,
"e": 746,
"s": 685,
"text": "1-) Create a twitter account if you do not already have one."
},
{
"code": null,
"e": 789,
"s": 746,
"text": "2-) Apply for a twitter developer account."
},
{
"code": null,
"e": 864,
"s": 789,
"text": "3-) Enter phone number if you don’t have one associated with your twitter."
},
{
"code": null,
"e": 908,
"s": 864,
"text": "4-) Add account details. Click on continue."
},
{
"code": null,
"e": 981,
"s": 908,
"text": "5-) Describe in your own words what you are building. Click on continue."
},
{
"code": null,
"e": 1005,
"s": 981,
"text": "6-) Submit application."
},
{
"code": null,
"e": 1085,
"s": 1005,
"text": "7-) Check your email associated with your twitter and click Confirm your email."
},
{
"code": null,
"e": 1136,
"s": 1085,
"text": "8-) On the welcome screen, click on Create an app."
},
{
"code": null,
"e": 1284,
"s": 1136,
"text": "9-) Fill out your App details and click on Create (its at the bottom of the page). Make sure you don’t try to make a appName that is already taken."
},
{
"code": null,
"e": 1328,
"s": 1284,
"text": "Review Developer Terms and click on Create."
},
{
"code": null,
"e": 1435,
"s": 1328,
"text": "10-) First, click on Keys and tokens. Second, click on create to get access token and access token secret."
},
{
"code": null,
"e": 1622,
"s": 1435,
"text": "Save your API key, API secret key, Access token, and Access token secret somewhere safe. I should note that you should not try and copy my keys as I regenerated them after this tutorial."
},
{
"code": null,
"e": 2080,
"s": 1622,
"text": "If you want to use R, you can use twitteR (make sure you install first install the twitteR package). twitteR is an R package which provides access to the Twitter API. Most functionality of the API is supported, with a bias towards API calls that are more useful in data analysis as opposed to daily interaction. Read the user vignette if you want to learn more about how to use the package for your various needs. The code below uses the Twitter search API."
},
{
"code": null,
"e": 2440,
"s": 2080,
"text": "#install.packages(\"twitteR\")library(twitteR) # Change consumer_key, consume_secret, access_token, and # access_secret based on your own keysconsumer_key <- \"\"consumer_secret <-\"\"access_token <- \"\"access_secret <- \"\" setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_secret)tw = searchTwitter('@GalarnykMichael', n = 25)d = twListToDF(tw)"
},
{
"code": null,
"e": 2600,
"s": 2440,
"text": "The code below uses the python-twitter package (you can install using pip install python-twitter) for searching. You can learn how to make your own query here."
},
{
"code": null,
"e": 3028,
"s": 2600,
"text": "import twitter\"\"\"Change ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY and CONSUMER_SECRETto your own. \"\"\"ACCESS_TOKEN = ''ACCESS_SECRET = ''CONSUMER_KEY = ''CONSUMER_SECRET = ''t = twitter.Api(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, access_token_key=ACCESS_TOKEN, access_token_secret=ACCESS_SECRET)results = t.GetSearch(raw_query=\"q=from%3AGalarnykMichael&src=typd\")"
}
] |
forward_list::begin() and forward_list::end() in C++ STL | In this article we will be discussing the working, syntax and examples of forward_list::begin() and forward_list::end() functions in C++.
Forward list are sequence containers that allow constant time insert and erase operations anywhere within the sequence. Forward list are implement as a singly-linked lists. The ordering is kept by the association to each element of a link to the next element in the sequence.
forward_list::begin() is an inbuilt function in C++ STL which is declared in header file. begin() returns the iterator which is referred to the first element in the forward_list container. Mostly we use begin() and end() together to give the range of an forward_list container.
forwardlist_container.begin();
This function accepts no parameter.
This function returns a bidirectional iterator pointing to the first element of the container.
Live Demo
#include <bits/stdc++.h>
using namespace std;
int main(){
//creating a forward list
forward_list<int> forwardList = { 4, 1, 2, 7 };
cout<<"Printing the elements of a forward List\n";
//calling begin() to point to the first element
for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
cout << ' ' << *i;
return 0;
}
If we run the above code it will generate the following output
Printing the elements of a forward List
4 1 2 7
forward_list::end() is an inbuilt function in C++ STL which is declared in header file. end() returns the iterator which is referred to the last element in the forward_list container. Mostly we use begin() and end() together to give the range of an forward_list container.
forwardlist_container.end();
This function accepts no parameter.
This function returns a bidirectional iterator pointing to the first element of the container.
Live Demo
#include <bits/stdc++.h>
using namespace std;
int main(){
//creating a forward list
forward_list<int> forwardList = { 4, 1, 2, 7 };
cout<<"Printing the elements of a forward List\n";
//calling begin() to point to the first element
for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
cout << ' ' << *i;
return 0;
}
If we run the above code it will generate the following output
Printing the elements of a forward List
4 1 2 7 | [
{
"code": null,
"e": 1200,
"s": 1062,
"text": "In this article we will be discussing the working, syntax and examples of forward_list::begin() and forward_list::end() functions in C++."
},
{
"code": null,
"e": 1476,
"s": 1200,
"text": "Forward list are sequence containers that allow constant time insert and erase operations anywhere within the sequence. Forward list are implement as a singly-linked lists. The ordering is kept by the association to each element of a link to the next element in the sequence."
},
{
"code": null,
"e": 1754,
"s": 1476,
"text": "forward_list::begin() is an inbuilt function in C++ STL which is declared in header file. begin() returns the iterator which is referred to the first element in the forward_list container. Mostly we use begin() and end() together to give the range of an forward_list container."
},
{
"code": null,
"e": 1785,
"s": 1754,
"text": "forwardlist_container.begin();"
},
{
"code": null,
"e": 1821,
"s": 1785,
"text": "This function accepts no parameter."
},
{
"code": null,
"e": 1916,
"s": 1821,
"text": "This function returns a bidirectional iterator pointing to the first element of the container."
},
{
"code": null,
"e": 1927,
"s": 1916,
"text": " Live Demo"
},
{
"code": null,
"e": 2277,
"s": 1927,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n //creating a forward list\n forward_list<int> forwardList = { 4, 1, 2, 7 };\n cout<<\"Printing the elements of a forward List\\n\";\n //calling begin() to point to the first element\n for (auto i = forwardList.begin(); i != forwardList.end(); ++i)\n cout << ' ' << *i;\n return 0;\n}"
},
{
"code": null,
"e": 2340,
"s": 2277,
"text": "If we run the above code it will generate the following output"
},
{
"code": null,
"e": 2388,
"s": 2340,
"text": "Printing the elements of a forward List\n4 1 2 7"
},
{
"code": null,
"e": 2661,
"s": 2388,
"text": "forward_list::end() is an inbuilt function in C++ STL which is declared in header file. end() returns the iterator which is referred to the last element in the forward_list container. Mostly we use begin() and end() together to give the range of an forward_list container."
},
{
"code": null,
"e": 2690,
"s": 2661,
"text": "forwardlist_container.end();"
},
{
"code": null,
"e": 2726,
"s": 2690,
"text": "This function accepts no parameter."
},
{
"code": null,
"e": 2821,
"s": 2726,
"text": "This function returns a bidirectional iterator pointing to the first element of the container."
},
{
"code": null,
"e": 2832,
"s": 2821,
"text": " Live Demo"
},
{
"code": null,
"e": 3182,
"s": 2832,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n //creating a forward list\n forward_list<int> forwardList = { 4, 1, 2, 7 };\n cout<<\"Printing the elements of a forward List\\n\";\n //calling begin() to point to the first element\n for (auto i = forwardList.begin(); i != forwardList.end(); ++i)\n cout << ' ' << *i;\n return 0;\n}"
},
{
"code": null,
"e": 3245,
"s": 3182,
"text": "If we run the above code it will generate the following output"
},
{
"code": null,
"e": 3293,
"s": 3245,
"text": "Printing the elements of a forward List\n4 1 2 7"
}
] |
How to find specific row with a MySQL query? | Let us first create a table −
mysql> create table DemoTable
(
UserId int,
UserName varchar(100)
);
Query OK, 0 rows affected (0.66 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(101,'Bob');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable values(102,'David');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(103,'Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(104,'Sam');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+----------+
| UserId | UserName |
+--------+----------+
| 100 | Chris |
| 101 | Bob |
| 102 | David |
| 103 | Mike |
| 104 | Sam |
+--------+----------+
5 rows in set (0.00 sec)
Following is the query to find the specific row and display the record of that row −
mysql> select *from DemoTable where UserId=102 and UserName='David';
This will produce the following output −
+--------+----------+
| UserId | UserName |
+--------+----------+
| 102 | David |
+--------+----------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1204,
"s": 1092,
"text": "mysql> create table DemoTable\n(\n UserId int,\n UserName varchar(100)\n);\nQuery OK, 0 rows affected (0.66 sec)"
},
{
"code": null,
"e": 1260,
"s": 1204,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1685,
"s": 1260,
"text": "mysql> insert into DemoTable values(100,'Chris');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values(101,'Bob');\nQuery OK, 1 row affected (0.07 sec)\nmysql> insert into DemoTable values(102,'David');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(103,'Mike');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(104,'Sam');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1745,
"s": 1685,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1776,
"s": 1745,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1817,
"s": 1776,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2040,
"s": 1817,
"text": "+--------+----------+\n| UserId | UserName |\n+--------+----------+\n| 100 | Chris |\n| 101 | Bob |\n| 102 | David |\n| 103 | Mike |\n| 104 | Sam |\n+--------+----------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2125,
"s": 2040,
"text": "Following is the query to find the specific row and display the record of that row −"
},
{
"code": null,
"e": 2194,
"s": 2125,
"text": "mysql> select *from DemoTable where UserId=102 and UserName='David';"
},
{
"code": null,
"e": 2235,
"s": 2194,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2369,
"s": 2235,
"text": "+--------+----------+\n| UserId | UserName |\n+--------+----------+\n| 102 | David |\n+--------+----------+\n1 row in set (0.00 sec)"
}
] |
C++ Program to Check Whether an Undirected Graph Contains a Eulerian Path | The Euler path is a path; by which we can visit every node exactly once. We can use the same edges for multiple times. The Euler Circuit is a special type of Euler path. When the starting vertex of the Euler path is also connected with the ending vertex of that path.
To detect the Euler Path, we have to follow these conditions
The graph must be connected.
Now when no vertices of an undirected graph have odd degree, then it is a Euler Circuit, which is also one Euler path.
When exactly two vertices have odd degree, it is a Euler Path.
Both of the graphs has Euler paths.
Input : The start node u and the visited node to mark which node is visited.
Output : Traverse all connected vertices.
Begin
mark u as visited
for all vertex v, if it is adjacent with u, do
if v is not visited, then
traverse(v, visited)
done
End
Input : The graph.
Output : True if the graph is connected.
Begin
define visited array
for all vertices u in the graph, do
make all nodes unvisited
traverse(u, visited)
if any unvisited node is still remaining, then
return false
done
return true
End
Input : The given Graph.
Output : Returns 1, when Eulerian circuit or path, and returns 0 when it has no Euler Path.
Begin
if isConnected() is false, then
return false
define list of degree for each node
oddDegree := 0
for all vertex i in the graph, do
for all vertex j which are connected with i, do
increase degree
done
if degree of vertex i is odd, then
increase oddDegree
done
if oddDegree > 0, then
return 0
else return 1
End
#include<iostream>
#include<vector>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {{0, 1, 1, 1, 0},
{1, 0, 1, 0, 0},
{1, 1, 0, 0, 0},
{1, 0, 0, 0, 1},
{0, 0, 0, 1, 0}};
/*int graph[NODE][NODE] = {{0, 1, 1, 1, 1},
{1, 0, 1, 0, 0},
{1, 1, 0, 0, 0},
{1, 0, 0, 0, 1},
{1, 0, 0, 1, 0}};*/ //uncomment to check Euler Circuit as well as path
/*int graph[NODE][NODE] = {{0, 1, 1, 1, 0},
{1, 0, 1, 1, 0},
{1, 1, 0, 0, 0},
{1, 1, 0, 0, 1},
{0, 0, 0, 1, 0}};*/ //Uncomment to check Non Eulerian Graph
void traverse(int u, bool visited[]) {
visited[u] = true; //mark v as visited
for(int v = 0; v<NODE; v++) {
if(graph[u][v]) {
if(!visited[v])
traverse(v, visited);
}
}
}
bool isConnected() {
bool *vis = new bool[NODE];
//for all vertex u as start point, check whether all nodes are visible or not
for(int u; u < NODE; u++) {
for(int i = 0; i<NODE; i++)
vis[i] = false; //initialize as no node is visited
traverse(u, vis);
for(int i = 0; i<NODE; i++){
if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
return false;
}
}
return true;
}
int isEulerian() {
if(isConnected() == false) //when graph is not connected
return 0;
vector<int> degree(NODE, 0);
int oddDegree = 0;
for(int i = 0; i<NODE; i++) {
for(int j = 0; j<NODE; j++) {
if(graph[i][j])
degree[i]++; //increase degree, when connected edge found
}
if(degree[i] % 2 != 0) //when degree of vertices are odd
oddDegree++; //count odd degree vertices
}
if(oddDegree > 2) //when vertices with odd degree greater than 2
return 0;
return 1; //when oddDegree is 0, it is Euler circuit, and when 2, it is Euler path
}
int main() {
if(isEulerian() != 0) {
cout << "The graph has Eulerian path." << endl;
} else {
cout << "The graph has No Eulerian path." << endl;
}
}
The graph has Eulerian path. | [
{
"code": null,
"e": 1330,
"s": 1062,
"text": "The Euler path is a path; by which we can visit every node exactly once. We can use the same edges for multiple times. The Euler Circuit is a special type of Euler path. When the starting vertex of the Euler path is also connected with the ending vertex of that path."
},
{
"code": null,
"e": 1391,
"s": 1330,
"text": "To detect the Euler Path, we have to follow these conditions"
},
{
"code": null,
"e": 1420,
"s": 1391,
"text": "The graph must be connected."
},
{
"code": null,
"e": 1539,
"s": 1420,
"text": "Now when no vertices of an undirected graph have odd degree, then it is a Euler Circuit, which is also one Euler path."
},
{
"code": null,
"e": 1602,
"s": 1539,
"text": "When exactly two vertices have odd degree, it is a Euler Path."
},
{
"code": null,
"e": 1638,
"s": 1602,
"text": "Both of the graphs has Euler paths."
},
{
"code": null,
"e": 1715,
"s": 1638,
"text": "Input : The start node u and the visited node to mark which node is visited."
},
{
"code": null,
"e": 1757,
"s": 1715,
"text": "Output : Traverse all connected vertices."
},
{
"code": null,
"e": 1911,
"s": 1757,
"text": "Begin\n mark u as visited\n for all vertex v, if it is adjacent with u, do\n if v is not visited, then\n traverse(v, visited)\n done\nEnd"
},
{
"code": null,
"e": 1930,
"s": 1911,
"text": "Input : The graph."
},
{
"code": null,
"e": 1971,
"s": 1930,
"text": "Output : True if the graph is connected."
},
{
"code": null,
"e": 2203,
"s": 1971,
"text": "Begin\n define visited array\n for all vertices u in the graph, do\n make all nodes unvisited\n traverse(u, visited)\n if any unvisited node is still remaining, then\n return false\n done\n return true\nEnd"
},
{
"code": null,
"e": 2228,
"s": 2203,
"text": "Input : The given Graph."
},
{
"code": null,
"e": 2320,
"s": 2228,
"text": "Output : Returns 1, when Eulerian circuit or path, and returns 0 when it has no Euler Path."
},
{
"code": null,
"e": 2706,
"s": 2320,
"text": "Begin\n if isConnected() is false, then\n return false\n define list of degree for each node\n oddDegree := 0\n for all vertex i in the graph, do\n for all vertex j which are connected with i, do\n increase degree\n done\n if degree of vertex i is odd, then\n increase oddDegree\n done\n if oddDegree > 0, then\n return 0\n else return 1\nEnd"
},
{
"code": null,
"e": 4717,
"s": 2706,
"text": "#include<iostream>\n#include<vector>\n#define NODE 5\nusing namespace std;\nint graph[NODE][NODE] = {{0, 1, 1, 1, 0},\n {1, 0, 1, 0, 0},\n {1, 1, 0, 0, 0},\n {1, 0, 0, 0, 1},\n {0, 0, 0, 1, 0}};\n/*int graph[NODE][NODE] = {{0, 1, 1, 1, 1},\n {1, 0, 1, 0, 0},\n {1, 1, 0, 0, 0},\n {1, 0, 0, 0, 1},\n {1, 0, 0, 1, 0}};*/ //uncomment to check Euler Circuit as well as path\n/*int graph[NODE][NODE] = {{0, 1, 1, 1, 0},\n {1, 0, 1, 1, 0},\n {1, 1, 0, 0, 0},\n {1, 1, 0, 0, 1},\n {0, 0, 0, 1, 0}};*/ //Uncomment to check Non Eulerian Graph\nvoid traverse(int u, bool visited[]) {\n visited[u] = true; //mark v as visited\n for(int v = 0; v<NODE; v++) {\n if(graph[u][v]) {\n if(!visited[v])\n traverse(v, visited);\n }\n }\n}\nbool isConnected() {\n bool *vis = new bool[NODE];\n //for all vertex u as start point, check whether all nodes are visible or not\n for(int u; u < NODE; u++) {\n for(int i = 0; i<NODE; i++)\n vis[i] = false; //initialize as no node is visited\n traverse(u, vis);\n for(int i = 0; i<NODE; i++){\n if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected\n return false;\n }\n }\n return true;\n}\nint isEulerian() {\n if(isConnected() == false) //when graph is not connected\n return 0;\n vector<int> degree(NODE, 0);\n int oddDegree = 0;\n for(int i = 0; i<NODE; i++) {\n for(int j = 0; j<NODE; j++) {\n if(graph[i][j])\n degree[i]++; //increase degree, when connected edge found\n }\n if(degree[i] % 2 != 0) //when degree of vertices are odd\n oddDegree++; //count odd degree vertices\n }\n if(oddDegree > 2) //when vertices with odd degree greater than 2\n return 0;\n return 1; //when oddDegree is 0, it is Euler circuit, and when 2, it is Euler path\n}\nint main() {\n if(isEulerian() != 0) {\n cout << \"The graph has Eulerian path.\" << endl;\n } else {\n cout << \"The graph has No Eulerian path.\" << endl;\n }\n}"
},
{
"code": null,
"e": 4746,
"s": 4717,
"text": "The graph has Eulerian path."
}
] |
Logistic Regression as a Nonlinear Classifier | by Ashok Chilakapati | Towards Data Science | Logistic Regression has traditionally been used as a linear classifier, i.e. when the classes can be separated in the feature space by linear boundaries. That can be remedied however if we happen to have a better idea as to the shape of the decision boundary...
Logistic regression is known and used as a linear classifier. It is used to come up with a hyperplane in feature space to separate observations that belong to a class from all the other observations that do not belong to that class. The decision boundary is thus linear. Robust and efficient implementations are readily available (e.g. scikit-learn) to use logistic regression as a linear classifier.
While logistic regression makes core assumptions about the observations such as IID (each observation is independent of the others and they all have an identical probability distribution), the use of a linear decision boundary is not one of them. The linear decision boundary is used for reasons of simplicity following the Zen mantra — when in doubt simplify. In those cases where we suspect the decision boundary to be nonlinear, it may make sense to formulate logistic regression with a nonlinear model and evaluate how much better we can do. That is what this post is about. Here is the outline. We go through some code snippets here but the full code for reproducing the results can be downloaded from github.
Briefly review the formulation of the likelihood function and its maximization. To keep the algebra at bay we stick to 2 classes, in a 2-d feature space. A point [x, y] in the feature space can belong to only one of the classes, and the function f (x,y; c) = 0 defines the decision boundary as shown in Figure 1 below.
Consider a decision boundary that can be expressed as a polynomial in feature variables but linear in the weights/coefficients. This case lends itself to be modeled within the (linear) framework using the API from scikit-learn.
Consider a generic nonlinear decision boundary that cannot be expressed as a polynomial. Here we are on our own to find the model parameters that maximize the likelihood function. There is excellent API in the scipy.optimize module that helps us out here.
Logistic regression is an exercise in predicting (regressing to — one can say) discrete outcomes from a continuous and/or categorical set of observations. Each observation is independent and the probability p that an observation belongs to the class is some ( & same!) function of the features describing that observation. Consider a set of n observations [x_i, y_i; Z_i] where x_i, y_i are the feature values for the ith observation. Z_i equals 1 if the ith observation belongs to the class, and equals 0 otherwise. The likelihood of having obtained n such observations is simply the product of the probability p(x_i, y_i) of obtaining each one of them separately.
The ratio p/(1-p) (known as the odds ratio) would be unity along the decision boundary as p = 1-p = 0.5. If we define a function f(x,y; c) as:
then f(x,y; c) =0 would be the decision boundary. c are the m parameters in the function f. And log-likelihood in terms of f would be:
All that is left to be done now is to find a set of values for the parameters c that maximize log(L) in Equation 3. We can either apply an optimization technique or solve the coupled set of m nonlinear equations d log(L)/dc = 0 for c.
Either way, having c in hand completes the definition of f and allows us find out the class of any point in the feature space. That is logistic regression in a nut shell.
Would any function for f work in Equation 2? Most certainly not. As p goes from 0 to 1, log(p/(1-p)) goes from -inf to +inf. So we need f to be unbounded as well in both directions. The possibilities for f are endless so long as we make sure that f has a range from -inf to +inf.
Choosing a linear form such as
will work for sure and that leads to traditional logistic regression as available for use in scikit-learn and the reason logistic regression is known as a linear classifier.
An easy extension Equation 5 would be to use a higher degree polynomial. A 2nd order one would simply be:
Note that the above formulation is identical to the linear case, if we treat x2, xy, and y2 as three additional independent features of the problem. The impetus for doing so would be that we can then directly apply the API from scikit-learn to get an estimate for c. We see however in the results section that the c obtained this way is not as good as directly solving Equation 4 for c. It is a bit of a mystery as to why. But in any case solving Equation 4 is easy enough with modules from scipy. The derivatives we need for Equation 4 fall out simply as
A periodic form like f(x,y; c) = sin(c_0x + c_2y) = 0 will not work as its range is limited. But the following will.
We can again evaluate the derivatives and solve for the roots of Equation 4 but sometimes it is simpler to just directly maximize log(L) in Equation 3, and that is what we will do in the simulations to follow.
We generate equal number of points in the x, y feature space that belong to a class (Z = 0 when f(x,y; c) > small_value) and those that do not belong (Z = 1 when f(x, y; c) < small_value) as we know the explicit functional form of f(x,y; c).
The data is split 80/20 for train vs test. We use the API from scikit-learn for the linear case that we want to compare with.
We use the scipy.optimize module when choosing to solve the Equations in 4 for c or for maximizing the likelihood in Equation 3. LL and dLLbydc in the code snippet below are simply implementing Equations 3 and 4 respectively. The scipy routines are for minimization so we negate the sign in each case as we want to maximize the likelihood.
Finally we solve for c starting with a small initial guess close to 0.
We look at the polynomial and the other generic case separately.
We get an ellipse as the decision boundary for the following c values
We generate 1000 data points for each class based on the above function and apply logistic regression to that data to see what it predicts for the decision boundary.
pipenv run python ./polynomial.py 1000 2.25 -3.0 -18.0 35.0 -64.0 50.0
Figure 2 below shows the data distribution and the decision boundaries obtained by the different approaches. The contour traced by green triangles separates the data perfectly, i.e. gets an F1 score of 1. It is obtained by solving Equation 4 for c. The red line is obtained by the traditional logistic regression approach — clearly a straight line. It tries to do the best it can given the nonlinearities and gets an F1 score of well 0.5... The contour traced by the blue triangles is interesting. It is obtained by applying traditional logistic regression on the augmented feature space. That is “x2”, “x*y”, and “y2” are treated as three additional features thereby linearizing f for use with scikit-learn. It gets an F1 score of 0.89 which is not bad. But it is not entirely clear why it should be worse than solving dlog(LL)/dc = 0.
The actual values for the coefficients are shown in Table 1 below. c_0 is scaled to unity so we can compare. Clearly the coefficients obtained solving dlog(LL)/dc = 0 are closest to the actual values used in generating the data.
Figure 3 shows the data distribution and the predicted boundaries upon running the simulation with
pipenv run python ./generic.py 1000 1.0 -1.0 1.0 -1.0
The straight line from traditional logistic regression obtains an F1 score of 0.675 whereas the direct minimization of log(LL) gets a perfect score.
Table 2 below compares the values for the coefficients obtained in the simulation. It is interesting to note that the signs of c_1 and c_2 are opposite between the actual and those predicted by minimization. That is fine because sin(-k) = -sin(k).
Logistic regression has traditionally been used to come up with a hyperplane that separates the feature space into classes. But if we suspect that the decision boundary is nonlinear we may get better results by attempting some nonlinear functional forms for the logit function. Solving for the model parameters can be more challenging but the optimization modules in scipy can help.
Originally published at xplordat.com on March 13, 2019. | [
{
"code": null,
"e": 434,
"s": 172,
"text": "Logistic Regression has traditionally been used as a linear classifier, i.e. when the classes can be separated in the feature space by linear boundaries. That can be remedied however if we happen to have a better idea as to the shape of the decision boundary..."
},
{
"code": null,
"e": 835,
"s": 434,
"text": "Logistic regression is known and used as a linear classifier. It is used to come up with a hyperplane in feature space to separate observations that belong to a class from all the other observations that do not belong to that class. The decision boundary is thus linear. Robust and efficient implementations are readily available (e.g. scikit-learn) to use logistic regression as a linear classifier."
},
{
"code": null,
"e": 1550,
"s": 835,
"text": "While logistic regression makes core assumptions about the observations such as IID (each observation is independent of the others and they all have an identical probability distribution), the use of a linear decision boundary is not one of them. The linear decision boundary is used for reasons of simplicity following the Zen mantra — when in doubt simplify. In those cases where we suspect the decision boundary to be nonlinear, it may make sense to formulate logistic regression with a nonlinear model and evaluate how much better we can do. That is what this post is about. Here is the outline. We go through some code snippets here but the full code for reproducing the results can be downloaded from github."
},
{
"code": null,
"e": 1869,
"s": 1550,
"text": "Briefly review the formulation of the likelihood function and its maximization. To keep the algebra at bay we stick to 2 classes, in a 2-d feature space. A point [x, y] in the feature space can belong to only one of the classes, and the function f (x,y; c) = 0 defines the decision boundary as shown in Figure 1 below."
},
{
"code": null,
"e": 2097,
"s": 1869,
"text": "Consider a decision boundary that can be expressed as a polynomial in feature variables but linear in the weights/coefficients. This case lends itself to be modeled within the (linear) framework using the API from scikit-learn."
},
{
"code": null,
"e": 2353,
"s": 2097,
"text": "Consider a generic nonlinear decision boundary that cannot be expressed as a polynomial. Here we are on our own to find the model parameters that maximize the likelihood function. There is excellent API in the scipy.optimize module that helps us out here."
},
{
"code": null,
"e": 3019,
"s": 2353,
"text": "Logistic regression is an exercise in predicting (regressing to — one can say) discrete outcomes from a continuous and/or categorical set of observations. Each observation is independent and the probability p that an observation belongs to the class is some ( & same!) function of the features describing that observation. Consider a set of n observations [x_i, y_i; Z_i] where x_i, y_i are the feature values for the ith observation. Z_i equals 1 if the ith observation belongs to the class, and equals 0 otherwise. The likelihood of having obtained n such observations is simply the product of the probability p(x_i, y_i) of obtaining each one of them separately."
},
{
"code": null,
"e": 3162,
"s": 3019,
"text": "The ratio p/(1-p) (known as the odds ratio) would be unity along the decision boundary as p = 1-p = 0.5. If we define a function f(x,y; c) as:"
},
{
"code": null,
"e": 3297,
"s": 3162,
"text": "then f(x,y; c) =0 would be the decision boundary. c are the m parameters in the function f. And log-likelihood in terms of f would be:"
},
{
"code": null,
"e": 3532,
"s": 3297,
"text": "All that is left to be done now is to find a set of values for the parameters c that maximize log(L) in Equation 3. We can either apply an optimization technique or solve the coupled set of m nonlinear equations d log(L)/dc = 0 for c."
},
{
"code": null,
"e": 3703,
"s": 3532,
"text": "Either way, having c in hand completes the definition of f and allows us find out the class of any point in the feature space. That is logistic regression in a nut shell."
},
{
"code": null,
"e": 3983,
"s": 3703,
"text": "Would any function for f work in Equation 2? Most certainly not. As p goes from 0 to 1, log(p/(1-p)) goes from -inf to +inf. So we need f to be unbounded as well in both directions. The possibilities for f are endless so long as we make sure that f has a range from -inf to +inf."
},
{
"code": null,
"e": 4014,
"s": 3983,
"text": "Choosing a linear form such as"
},
{
"code": null,
"e": 4188,
"s": 4014,
"text": "will work for sure and that leads to traditional logistic regression as available for use in scikit-learn and the reason logistic regression is known as a linear classifier."
},
{
"code": null,
"e": 4294,
"s": 4188,
"text": "An easy extension Equation 5 would be to use a higher degree polynomial. A 2nd order one would simply be:"
},
{
"code": null,
"e": 4850,
"s": 4294,
"text": "Note that the above formulation is identical to the linear case, if we treat x2, xy, and y2 as three additional independent features of the problem. The impetus for doing so would be that we can then directly apply the API from scikit-learn to get an estimate for c. We see however in the results section that the c obtained this way is not as good as directly solving Equation 4 for c. It is a bit of a mystery as to why. But in any case solving Equation 4 is easy enough with modules from scipy. The derivatives we need for Equation 4 fall out simply as"
},
{
"code": null,
"e": 4967,
"s": 4850,
"text": "A periodic form like f(x,y; c) = sin(c_0x + c_2y) = 0 will not work as its range is limited. But the following will."
},
{
"code": null,
"e": 5177,
"s": 4967,
"text": "We can again evaluate the derivatives and solve for the roots of Equation 4 but sometimes it is simpler to just directly maximize log(L) in Equation 3, and that is what we will do in the simulations to follow."
},
{
"code": null,
"e": 5419,
"s": 5177,
"text": "We generate equal number of points in the x, y feature space that belong to a class (Z = 0 when f(x,y; c) > small_value) and those that do not belong (Z = 1 when f(x, y; c) < small_value) as we know the explicit functional form of f(x,y; c)."
},
{
"code": null,
"e": 5545,
"s": 5419,
"text": "The data is split 80/20 for train vs test. We use the API from scikit-learn for the linear case that we want to compare with."
},
{
"code": null,
"e": 5885,
"s": 5545,
"text": "We use the scipy.optimize module when choosing to solve the Equations in 4 for c or for maximizing the likelihood in Equation 3. LL and dLLbydc in the code snippet below are simply implementing Equations 3 and 4 respectively. The scipy routines are for minimization so we negate the sign in each case as we want to maximize the likelihood."
},
{
"code": null,
"e": 5956,
"s": 5885,
"text": "Finally we solve for c starting with a small initial guess close to 0."
},
{
"code": null,
"e": 6021,
"s": 5956,
"text": "We look at the polynomial and the other generic case separately."
},
{
"code": null,
"e": 6091,
"s": 6021,
"text": "We get an ellipse as the decision boundary for the following c values"
},
{
"code": null,
"e": 6257,
"s": 6091,
"text": "We generate 1000 data points for each class based on the above function and apply logistic regression to that data to see what it predicts for the decision boundary."
},
{
"code": null,
"e": 6328,
"s": 6257,
"text": "pipenv run python ./polynomial.py 1000 2.25 -3.0 -18.0 35.0 -64.0 50.0"
},
{
"code": null,
"e": 7165,
"s": 6328,
"text": "Figure 2 below shows the data distribution and the decision boundaries obtained by the different approaches. The contour traced by green triangles separates the data perfectly, i.e. gets an F1 score of 1. It is obtained by solving Equation 4 for c. The red line is obtained by the traditional logistic regression approach — clearly a straight line. It tries to do the best it can given the nonlinearities and gets an F1 score of well 0.5... The contour traced by the blue triangles is interesting. It is obtained by applying traditional logistic regression on the augmented feature space. That is “x2”, “x*y”, and “y2” are treated as three additional features thereby linearizing f for use with scikit-learn. It gets an F1 score of 0.89 which is not bad. But it is not entirely clear why it should be worse than solving dlog(LL)/dc = 0."
},
{
"code": null,
"e": 7394,
"s": 7165,
"text": "The actual values for the coefficients are shown in Table 1 below. c_0 is scaled to unity so we can compare. Clearly the coefficients obtained solving dlog(LL)/dc = 0 are closest to the actual values used in generating the data."
},
{
"code": null,
"e": 7493,
"s": 7394,
"text": "Figure 3 shows the data distribution and the predicted boundaries upon running the simulation with"
},
{
"code": null,
"e": 7547,
"s": 7493,
"text": "pipenv run python ./generic.py 1000 1.0 -1.0 1.0 -1.0"
},
{
"code": null,
"e": 7696,
"s": 7547,
"text": "The straight line from traditional logistic regression obtains an F1 score of 0.675 whereas the direct minimization of log(LL) gets a perfect score."
},
{
"code": null,
"e": 7944,
"s": 7696,
"text": "Table 2 below compares the values for the coefficients obtained in the simulation. It is interesting to note that the signs of c_1 and c_2 are opposite between the actual and those predicted by minimization. That is fine because sin(-k) = -sin(k)."
},
{
"code": null,
"e": 8327,
"s": 7944,
"text": "Logistic regression has traditionally been used to come up with a hyperplane that separates the feature space into classes. But if we suspect that the decision boundary is nonlinear we may get better results by attempting some nonlinear functional forms for the logit function. Solving for the model parameters can be more challenging but the optimization modules in scipy can help."
}
] |
C++ Program For Stock Buy Sell To Maximize Profit - GeeksforGeeks | 22 Dec, 2021
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.
Naive approach: A simple approach is to try buying the stocks and selling them on every single day when profitable and keep updating the maximum profit so far.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum profit// that can be made after buying and// selling the given stocksint maxProfit(int price[], int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = max(profit, curr_profit); } } } return profit;} // Driver codeint main(){ int price[] = {100, 180, 260, 310, 40, 535, 695}; int n = sizeof(price) / sizeof(price[0]); cout << maxProfit(price, 0, n - 1); return 0;}
Output:
865
Efficient approach: If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. Following is the algorithm for this problem.
Find the local minima and store it as starting index. If not exists, return.Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index.Update the solution (Increment count of buy-sell pairs)Repeat the above steps if the end is not reached.
Find the local minima and store it as starting index. If not exists, return.
Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index.
Update the solution (Increment count of buy-sell pairs)
Repeat the above steps if the end is not reached.
C++
// C++ Program to find best buying // and selling days#include <bits/stdc++.h>using namespace std; // This function finds the buy sell// schedule for maximum profitvoid stockBuySell(int price[], int n){ // Prices must be given for at // least two days if (n == 1) return; // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima // Note that the limit is (n-2) as we are // comparing present element to the next element while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break // as no further solution possible if (i == n - 1) break; // Store the index of minima int buy = i++; // Find Local Maxima // Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima int sell = i - 1; cout << "Buy on day: " << buy << " Sell on day: " << sell << endl; }} // Driver codeint main(){ // Stock prices on consecutive days int price[] = {100, 180, 260, 310, 40, 535, 695}; int n = sizeof(price) / sizeof(price[0]); // Function call stockBuySell(price, n); return 0;} // This is code is contributed by rathbhupendra
Output:
Buy on day: 0 Sell on day: 3
Buy on day: 4 Sell on day: 6
Time Complexity: The outer loop runs till I become n-1. The inner two loops increment value of I in every iteration. So overall time complexity is O(n)
Valley Peak Approach:
In this approach, we just need to find the next greater element and subtract it from the current element so that the difference keeps increasing until we reach a minimum. If the sequence is a decreasing sequence so the maximum profit possible is 0.
C++
// C++ program to implement// the above approach#include <iostream>using namespace std; // Preprocessing helps the code // run faster#define fl(i, a, b) for (int i = a; i < b; i++) // Function that returnint maxProfit(int* prices, int size){ // maxProfit adds up the difference // between adjacent elements if they // are in increasing order int maxProfit = 0; // The loop starts from 1 as its // comparing with the previous fl(i, 1, size) if (prices[i] > prices[i - 1]) maxProfit += prices[i] - prices[i - 1]; return maxProfit;} // Driver codeint main(){ int prices[] = {100, 180, 260, 310, 40, 535, 695}; int N = sizeof(prices) / sizeof(prices[0]); cout << maxProfit(prices, N) << endl; return 0;}// This code is contributed by Kingshuk Deb
Output:
865
Time Complexity: O(n)Auxiliary Space: O(1)
Please refer complete article on Stock Buy Sell to Maximize Profit for more details!
Accolite
Amazon
Directi
Flipkart
Goldman Sachs
Hike
MakeMyTrip
Microsoft
Morgan Stanley
Ola Cabs
Oracle
Paytm
Pubmatic
Quikr
Samsung
SAP Labs
Sapient
Swiggy
Walmart
Arrays
C++ Programs
Paytm
Flipkart
Morgan Stanley
Accolite
Amazon
Microsoft
Samsung
Hike
MakeMyTrip
Ola Cabs
Oracle
Walmart
Goldman Sachs
Directi
SAP Labs
Quikr
Pubmatic
Sapient
Swiggy
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Trapping Rain Water
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
Window Sliding Technique
Header files in C/C++ and its uses
C++ Program for QuickSort
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
CSV file management using C++ | [
{
"code": null,
"e": 24742,
"s": 24714,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 25145,
"s": 24742,
"text": "The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all."
},
{
"code": null,
"e": 25305,
"s": 25145,
"text": "Naive approach: A simple approach is to try buying the stocks and selling them on every single day when profitable and keep updating the maximum profit so far."
},
{
"code": null,
"e": 25356,
"s": 25305,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25360,
"s": 25356,
"text": "C++"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum profit// that can be made after buying and// selling the given stocksint maxProfit(int price[], int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = max(profit, curr_profit); } } } return profit;} // Driver codeint main(){ int price[] = {100, 180, 260, 310, 40, 535, 695}; int n = sizeof(price) / sizeof(price[0]); cout << maxProfit(price, 0, n - 1); return 0;}",
"e": 26755,
"s": 25360,
"text": null
},
{
"code": null,
"e": 26763,
"s": 26755,
"text": "Output:"
},
{
"code": null,
"e": 26767,
"s": 26763,
"text": "865"
},
{
"code": null,
"e": 27009,
"s": 26767,
"text": "Efficient approach: If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. Following is the algorithm for this problem. "
},
{
"code": null,
"e": 27299,
"s": 27009,
"text": "Find the local minima and store it as starting index. If not exists, return.Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index.Update the solution (Increment count of buy-sell pairs)Repeat the above steps if the end is not reached."
},
{
"code": null,
"e": 27376,
"s": 27299,
"text": "Find the local minima and store it as starting index. If not exists, return."
},
{
"code": null,
"e": 27486,
"s": 27376,
"text": "Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index."
},
{
"code": null,
"e": 27542,
"s": 27486,
"text": "Update the solution (Increment count of buy-sell pairs)"
},
{
"code": null,
"e": 27592,
"s": 27542,
"text": "Repeat the above steps if the end is not reached."
},
{
"code": null,
"e": 27596,
"s": 27592,
"text": "C++"
},
{
"code": "// C++ Program to find best buying // and selling days#include <bits/stdc++.h>using namespace std; // This function finds the buy sell// schedule for maximum profitvoid stockBuySell(int price[], int n){ // Prices must be given for at // least two days if (n == 1) return; // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima // Note that the limit is (n-2) as we are // comparing present element to the next element while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break // as no further solution possible if (i == n - 1) break; // Store the index of minima int buy = i++; // Find Local Maxima // Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima int sell = i - 1; cout << \"Buy on day: \" << buy << \" Sell on day: \" << sell << endl; }} // Driver codeint main(){ // Stock prices on consecutive days int price[] = {100, 180, 260, 310, 40, 535, 695}; int n = sizeof(price) / sizeof(price[0]); // Function call stockBuySell(price, n); return 0;} // This is code is contributed by rathbhupendra",
"e": 29052,
"s": 27596,
"text": null
},
{
"code": null,
"e": 29060,
"s": 29052,
"text": "Output:"
},
{
"code": null,
"e": 29126,
"s": 29060,
"text": "Buy on day: 0 Sell on day: 3\nBuy on day: 4 Sell on day: 6"
},
{
"code": null,
"e": 29278,
"s": 29126,
"text": "Time Complexity: The outer loop runs till I become n-1. The inner two loops increment value of I in every iteration. So overall time complexity is O(n)"
},
{
"code": null,
"e": 29300,
"s": 29278,
"text": "Valley Peak Approach:"
},
{
"code": null,
"e": 29549,
"s": 29300,
"text": "In this approach, we just need to find the next greater element and subtract it from the current element so that the difference keeps increasing until we reach a minimum. If the sequence is a decreasing sequence so the maximum profit possible is 0."
},
{
"code": null,
"e": 29553,
"s": 29549,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Preprocessing helps the code // run faster#define fl(i, a, b) for (int i = a; i < b; i++) // Function that returnint maxProfit(int* prices, int size){ // maxProfit adds up the difference // between adjacent elements if they // are in increasing order int maxProfit = 0; // The loop starts from 1 as its // comparing with the previous fl(i, 1, size) if (prices[i] > prices[i - 1]) maxProfit += prices[i] - prices[i - 1]; return maxProfit;} // Driver codeint main(){ int prices[] = {100, 180, 260, 310, 40, 535, 695}; int N = sizeof(prices) / sizeof(prices[0]); cout << maxProfit(prices, N) << endl; return 0;}// This code is contributed by Kingshuk Deb",
"e": 30367,
"s": 29553,
"text": null
},
{
"code": null,
"e": 30375,
"s": 30367,
"text": "Output:"
},
{
"code": null,
"e": 30379,
"s": 30375,
"text": "865"
},
{
"code": null,
"e": 30422,
"s": 30379,
"text": "Time Complexity: O(n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30507,
"s": 30422,
"text": "Please refer complete article on Stock Buy Sell to Maximize Profit for more details!"
},
{
"code": null,
"e": 30516,
"s": 30507,
"text": "Accolite"
},
{
"code": null,
"e": 30523,
"s": 30516,
"text": "Amazon"
},
{
"code": null,
"e": 30531,
"s": 30523,
"text": "Directi"
},
{
"code": null,
"e": 30540,
"s": 30531,
"text": "Flipkart"
},
{
"code": null,
"e": 30554,
"s": 30540,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 30559,
"s": 30554,
"text": "Hike"
},
{
"code": null,
"e": 30570,
"s": 30559,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 30580,
"s": 30570,
"text": "Microsoft"
},
{
"code": null,
"e": 30595,
"s": 30580,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 30604,
"s": 30595,
"text": "Ola Cabs"
},
{
"code": null,
"e": 30611,
"s": 30604,
"text": "Oracle"
},
{
"code": null,
"e": 30617,
"s": 30611,
"text": "Paytm"
},
{
"code": null,
"e": 30626,
"s": 30617,
"text": "Pubmatic"
},
{
"code": null,
"e": 30632,
"s": 30626,
"text": "Quikr"
},
{
"code": null,
"e": 30640,
"s": 30632,
"text": "Samsung"
},
{
"code": null,
"e": 30649,
"s": 30640,
"text": "SAP Labs"
},
{
"code": null,
"e": 30657,
"s": 30649,
"text": "Sapient"
},
{
"code": null,
"e": 30664,
"s": 30657,
"text": "Swiggy"
},
{
"code": null,
"e": 30672,
"s": 30664,
"text": "Walmart"
},
{
"code": null,
"e": 30679,
"s": 30672,
"text": "Arrays"
},
{
"code": null,
"e": 30692,
"s": 30679,
"text": "C++ Programs"
},
{
"code": null,
"e": 30698,
"s": 30692,
"text": "Paytm"
},
{
"code": null,
"e": 30707,
"s": 30698,
"text": "Flipkart"
},
{
"code": null,
"e": 30722,
"s": 30707,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 30731,
"s": 30722,
"text": "Accolite"
},
{
"code": null,
"e": 30738,
"s": 30731,
"text": "Amazon"
},
{
"code": null,
"e": 30748,
"s": 30738,
"text": "Microsoft"
},
{
"code": null,
"e": 30756,
"s": 30748,
"text": "Samsung"
},
{
"code": null,
"e": 30761,
"s": 30756,
"text": "Hike"
},
{
"code": null,
"e": 30772,
"s": 30761,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 30781,
"s": 30772,
"text": "Ola Cabs"
},
{
"code": null,
"e": 30788,
"s": 30781,
"text": "Oracle"
},
{
"code": null,
"e": 30796,
"s": 30788,
"text": "Walmart"
},
{
"code": null,
"e": 30810,
"s": 30796,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 30818,
"s": 30810,
"text": "Directi"
},
{
"code": null,
"e": 30827,
"s": 30818,
"text": "SAP Labs"
},
{
"code": null,
"e": 30833,
"s": 30827,
"text": "Quikr"
},
{
"code": null,
"e": 30842,
"s": 30833,
"text": "Pubmatic"
},
{
"code": null,
"e": 30850,
"s": 30842,
"text": "Sapient"
},
{
"code": null,
"e": 30857,
"s": 30850,
"text": "Swiggy"
},
{
"code": null,
"e": 30864,
"s": 30857,
"text": "Arrays"
},
{
"code": null,
"e": 30962,
"s": 30864,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30971,
"s": 30962,
"text": "Comments"
},
{
"code": null,
"e": 30984,
"s": 30971,
"text": "Old Comments"
},
{
"code": null,
"e": 31004,
"s": 30984,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 31053,
"s": 31004,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31091,
"s": 31053,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 31149,
"s": 31091,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 31174,
"s": 31149,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31209,
"s": 31174,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 31235,
"s": 31209,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 31279,
"s": 31235,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 31338,
"s": 31279,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Count equal element pairs in the given array - GeeksforGeeks | 25 May, 2021
Given an array arr[] of N integers representing the lengths of the gloves, the task is to count the maximum possible pairs of gloves from the given array. Note that a glove can only pair with a same-sized glove and it can only be part of a single pair.
Examples:
Input: arr[] = {6, 5, 2, 3, 5, 2, 2, 1} Output: 2 (arr[1], arr[4]) and (arr[2], arr[5]) are the only possible pairs.
Input: arr[] = {1, 2, 3, 1, 2} Output: 2
Simple Approach: Sort the given array so that all the equal elements are adjacent to each other. Now, traverse the array and for every element if it equal to the element next to it then it is a valid pair and skip these two elements. Else the current element doesn’t make a valid pair with any other element and hence only skip the current element.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum// possible pairs of glovesint cntgloves(int arr[], int n){ // To store the required count int count = 0; // Sort the original array sort(arr, arr + n); for (int i = 0; i < n - 1;) { // A valid pair is found if (arr[i] == arr[i + 1]) { count++; // Skip the elements of // the current pair i = i + 2; } // Current elements doesn't make // a valid pair with any other element else { i++; } } return count;} // Driver codeint main(){ int arr[] = { 6, 5, 2, 3, 5, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << cntgloves(arr, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG { // Function to return the maximum // possible pairs of gloves static int cntgloves(int arr[], int n) { // Sort the original array Arrays.sort(arr); int res = 0; int i = 0; while (i < n) { // take first number int number = arr[i]; int count = 1; i++; // Count all duplicates while (i < n && arr[i] == number) { count++; i++; } // If we spotted number just 2 // times, increment // result if (count >= 2) { res = res + count / 2; } } return res; } // Driver code public static void main(String[] args) { int arr[] = {6, 5, 2, 3, 5, 2, 2, 1}; int n = arr.length; // Function call System.out.println(cntgloves(arr, n)); }} // This code is contributed by Lakhan murmu
# Python3 implementation of the approach # Function to return the maximum# possible pairs of gloves def cntgloves(arr, n): # To store the required count count = 0 # Sort the original array arr.sort() i = 0 while i < (n-1): # A valid pair is found if (arr[i] == arr[i + 1]): count += 1 # Skip the elements of # the current pair i = i + 2 # Current elements doesn't make # a valid pair with any other element else: i += 1 return count # Driver codeif __name__ == "__main__": arr = [6, 5, 2, 3, 5, 2, 2, 1] n = len(arr) # Function call print(cntgloves(arr, n)) # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG { // Function to return the maximum // possible pairs of gloves static int cntgloves(int[] arr, int n) { // To store the required count int count = 0; // Sort the original array Array.Sort(arr); for (int i = 0; i < n - 1;) { // A valid pair is found if (arr[i] == arr[i + 1]) { count++; // Skip the elements of // the current pair i = i + 2; } // Current elements doesn't make // a valid pair with any other element else { i++; } } return count; } // Driver code public static void Main(String[] args) { int[] arr = { 6, 5, 2, 3, 5, 2, 2, 1 }; int n = arr.Length; // Function call Console.WriteLine(cntgloves(arr, n)); }} // This code is contributed by Princi Singh
<script> // Javascript implementation of the approach // Function to return the maximum // possible pairs of gloves function cntgloves(arr, n) { // Sort the original array arr.sort(); let res = 0; let i = 0; while (i < n) { // take first number let number = arr[i]; let count = 1; i++; // Count all duplicates while (i < n && arr[i] == number) { count++; i++; } // If we spotted number just 2 // times, increment // result if (count >= 2) { res = res + Math.floor(count / 2); } } return res; } // Driver code let arr = [6, 5, 2, 3, 5, 2, 2, 1]; let n = arr.length; // Function call document.write(cntgloves(arr, n)); // This code is contributed by susmitakundugoaldanga.</script>
2
Efficient Approach 1) Create an empty hash table (unordered_map in C++, HashMap in Java, Dictionary in Python) 2) Store frequencies of all elements. 3) Traverse through the hash table. For every element, find its frequency. Increment the result by frequency/2 for every element,
ankthon
princiraj1992
princi singh
lakhanmurmu
ashwinrajrao
susmitakundugoaldanga
Arrays
Hash
Sorting
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Linear Search
Multidimensional Arrays in Java
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)
Most frequent element in an array | [
{
"code": null,
"e": 25006,
"s": 24978,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 25259,
"s": 25006,
"text": "Given an array arr[] of N integers representing the lengths of the gloves, the task is to count the maximum possible pairs of gloves from the given array. Note that a glove can only pair with a same-sized glove and it can only be part of a single pair."
},
{
"code": null,
"e": 25270,
"s": 25259,
"text": "Examples: "
},
{
"code": null,
"e": 25387,
"s": 25270,
"text": "Input: arr[] = {6, 5, 2, 3, 5, 2, 2, 1} Output: 2 (arr[1], arr[4]) and (arr[2], arr[5]) are the only possible pairs."
},
{
"code": null,
"e": 25429,
"s": 25387,
"text": "Input: arr[] = {1, 2, 3, 1, 2} Output: 2 "
},
{
"code": null,
"e": 25778,
"s": 25429,
"text": "Simple Approach: Sort the given array so that all the equal elements are adjacent to each other. Now, traverse the array and for every element if it equal to the element next to it then it is a valid pair and skip these two elements. Else the current element doesn’t make a valid pair with any other element and hence only skip the current element."
},
{
"code": null,
"e": 25831,
"s": 25778,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25837,
"s": 25831,
"text": "C++14"
},
{
"code": null,
"e": 25842,
"s": 25837,
"text": "Java"
},
{
"code": null,
"e": 25850,
"s": 25842,
"text": "Python3"
},
{
"code": null,
"e": 25853,
"s": 25850,
"text": "C#"
},
{
"code": null,
"e": 25864,
"s": 25853,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum// possible pairs of glovesint cntgloves(int arr[], int n){ // To store the required count int count = 0; // Sort the original array sort(arr, arr + n); for (int i = 0; i < n - 1;) { // A valid pair is found if (arr[i] == arr[i + 1]) { count++; // Skip the elements of // the current pair i = i + 2; } // Current elements doesn't make // a valid pair with any other element else { i++; } } return count;} // Driver codeint main(){ int arr[] = { 6, 5, 2, 3, 5, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << cntgloves(arr, n); return 0;}",
"e": 26690,
"s": 25864,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG { // Function to return the maximum // possible pairs of gloves static int cntgloves(int arr[], int n) { // Sort the original array Arrays.sort(arr); int res = 0; int i = 0; while (i < n) { // take first number int number = arr[i]; int count = 1; i++; // Count all duplicates while (i < n && arr[i] == number) { count++; i++; } // If we spotted number just 2 // times, increment // result if (count >= 2) { res = res + count / 2; } } return res; } // Driver code public static void main(String[] args) { int arr[] = {6, 5, 2, 3, 5, 2, 2, 1}; int n = arr.length; // Function call System.out.println(cntgloves(arr, n)); }} // This code is contributed by Lakhan murmu",
"e": 27745,
"s": 26690,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the maximum# possible pairs of gloves def cntgloves(arr, n): # To store the required count count = 0 # Sort the original array arr.sort() i = 0 while i < (n-1): # A valid pair is found if (arr[i] == arr[i + 1]): count += 1 # Skip the elements of # the current pair i = i + 2 # Current elements doesn't make # a valid pair with any other element else: i += 1 return count # Driver codeif __name__ == \"__main__\": arr = [6, 5, 2, 3, 5, 2, 2, 1] n = len(arr) # Function call print(cntgloves(arr, n)) # This code is contributed by AnkitRai01",
"e": 28481,
"s": 27745,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG { // Function to return the maximum // possible pairs of gloves static int cntgloves(int[] arr, int n) { // To store the required count int count = 0; // Sort the original array Array.Sort(arr); for (int i = 0; i < n - 1;) { // A valid pair is found if (arr[i] == arr[i + 1]) { count++; // Skip the elements of // the current pair i = i + 2; } // Current elements doesn't make // a valid pair with any other element else { i++; } } return count; } // Driver code public static void Main(String[] args) { int[] arr = { 6, 5, 2, 3, 5, 2, 2, 1 }; int n = arr.Length; // Function call Console.WriteLine(cntgloves(arr, n)); }} // This code is contributed by Princi Singh",
"e": 29471,
"s": 28481,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the maximum // possible pairs of gloves function cntgloves(arr, n) { // Sort the original array arr.sort(); let res = 0; let i = 0; while (i < n) { // take first number let number = arr[i]; let count = 1; i++; // Count all duplicates while (i < n && arr[i] == number) { count++; i++; } // If we spotted number just 2 // times, increment // result if (count >= 2) { res = res + Math.floor(count / 2); } } return res; } // Driver code let arr = [6, 5, 2, 3, 5, 2, 2, 1]; let n = arr.length; // Function call document.write(cntgloves(arr, n)); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 30481,
"s": 29471,
"text": null
},
{
"code": null,
"e": 30483,
"s": 30481,
"text": "2"
},
{
"code": null,
"e": 30764,
"s": 30485,
"text": "Efficient Approach 1) Create an empty hash table (unordered_map in C++, HashMap in Java, Dictionary in Python) 2) Store frequencies of all elements. 3) Traverse through the hash table. For every element, find its frequency. Increment the result by frequency/2 for every element,"
},
{
"code": null,
"e": 30772,
"s": 30764,
"text": "ankthon"
},
{
"code": null,
"e": 30786,
"s": 30772,
"text": "princiraj1992"
},
{
"code": null,
"e": 30799,
"s": 30786,
"text": "princi singh"
},
{
"code": null,
"e": 30811,
"s": 30799,
"text": "lakhanmurmu"
},
{
"code": null,
"e": 30824,
"s": 30811,
"text": "ashwinrajrao"
},
{
"code": null,
"e": 30846,
"s": 30824,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 30853,
"s": 30846,
"text": "Arrays"
},
{
"code": null,
"e": 30858,
"s": 30853,
"text": "Hash"
},
{
"code": null,
"e": 30866,
"s": 30858,
"text": "Sorting"
},
{
"code": null,
"e": 30873,
"s": 30866,
"text": "Arrays"
},
{
"code": null,
"e": 30878,
"s": 30873,
"text": "Hash"
},
{
"code": null,
"e": 30886,
"s": 30878,
"text": "Sorting"
},
{
"code": null,
"e": 30984,
"s": 30886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30993,
"s": 30984,
"text": "Comments"
},
{
"code": null,
"e": 31006,
"s": 30993,
"text": "Old Comments"
},
{
"code": null,
"e": 31054,
"s": 31006,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 31098,
"s": 31054,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 31121,
"s": 31098,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 31135,
"s": 31121,
"text": "Linear Search"
},
{
"code": null,
"e": 31167,
"s": 31135,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31203,
"s": 31167,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 31234,
"s": 31203,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 31268,
"s": 31234,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 31304,
"s": 31268,
"text": "Hashing | Set 2 (Separate Chaining)"
}
] |
Operating Systems | Memory Management | Question 9 - GeeksforGeeks | 28 Jun, 2021
A computer uses 46–bit virtual address, 32–bit physical address, and a three–level paged page table organization. The page table base register stores the base address of the first–level table (T1), which occupies exactly one page. Each entry of T1 stores the base address of a page of the second–level table (T2). Each entry of T2 stores the base address of a page of the third–level table (T3). Each entry of T3 stores a page table entry (PTE). The PTE is 32 bits in size. The processor used in the computer has a 1 MB 16 way set associative virtually indexed physically tagged cache. The cache block size is 64 bytes.
What is the size of a page in KB in this computer? (GATE 2013)(A) 2(B) 4(C) 8(D) 16Answer: (C)Explanation:
Let the page size is of 'x' bits
Size of T1 = 2 ^ x bytes
(This is because T1 occupies exactly one page)
Now, number of entries in T1 = (2^x) / 4
(This is because each page table entry is 32 bits
or 4 bytes in size)
Number of entries in T1 = Number of second level
page tables
(Because each I-level page table entry stores the
base address of page of II-level page table)
Total size of second level page tables = ((2^x) / 4) * (2^x)
Similarly, number of entries in II-level page tables = Number
of III level page tables = ((2^x) / 4) * ((2^x) / 4)
Total size of third level page tables = ((2^x) / 4) *
((2^x) / 4) * (2^x)
Similarly, total number of entries (pages) in all III-level
page tables = ((2^x) / 4) * ((2^x) / 4) * ((2^x) / 4)
= 2^(3x - 6)
Size of virtual memory = 2^46
Number of pages in virtual memory = (2^46) / (2^x) = 2^(46 - x)
Total number the pages in the III-level page tables =
Number of pages in virtual memory
2^(3x - 6) = 2^(46 - x)
3x - 6 = 46 - x
4x = 52
x = 13
That means, page size is of 13 bits
or Page size = 2^13 bytes = 8 KB
Quiz of this Question
memory-management
Operating Systems-Memory Management
Operating Systems Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scheduling in Greedy Algorithms
Introduction and Installation of Git
CPU Scheduling Numerical Questions
Operating Systems | CPU Scheduling | Question 4
Operating Systems | Input Output Systems | Question 2
Operating Systems | CPU Scheduling | Question 5
Operating Systems | CPU Scheduling | Question 3
File System Inconsistency
Operating Systems | Deadlock | Question 1
Program to show that Linux provides time sharing environment to processes | [
{
"code": null,
"e": 24607,
"s": 24579,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25227,
"s": 24607,
"text": "A computer uses 46–bit virtual address, 32–bit physical address, and a three–level paged page table organization. The page table base register stores the base address of the first–level table (T1), which occupies exactly one page. Each entry of T1 stores the base address of a page of the second–level table (T2). Each entry of T2 stores the base address of a page of the third–level table (T3). Each entry of T3 stores a page table entry (PTE). The PTE is 32 bits in size. The processor used in the computer has a 1 MB 16 way set associative virtually indexed physically tagged cache. The cache block size is 64 bytes."
},
{
"code": null,
"e": 25334,
"s": 25227,
"text": "What is the size of a page in KB in this computer? (GATE 2013)(A) 2(B) 4(C) 8(D) 16Answer: (C)Explanation:"
},
{
"code": null,
"e": 26498,
"s": 25334,
"text": "Let the page size is of 'x' bits\n\nSize of T1 = 2 ^ x bytes\n\n(This is because T1 occupies exactly one page)\n\nNow, number of entries in T1 = (2^x) / 4\n\n(This is because each page table entry is 32 bits\n or 4 bytes in size)\n\nNumber of entries in T1 = Number of second level \npage tables\n\n(Because each I-level page table entry stores the \n base address of page of II-level page table)\n\nTotal size of second level page tables = ((2^x) / 4) * (2^x)\n\nSimilarly, number of entries in II-level page tables = Number\n of III level page tables = ((2^x) / 4) * ((2^x) / 4)\n\nTotal size of third level page tables = ((2^x) / 4) * \n ((2^x) / 4) * (2^x)\n\nSimilarly, total number of entries (pages) in all III-level \npage tables = ((2^x) / 4) * ((2^x) / 4) * ((2^x) / 4)\n = 2^(3x - 6)\n\nSize of virtual memory = 2^46\n\nNumber of pages in virtual memory = (2^46) / (2^x) = 2^(46 - x)\n\nTotal number the pages in the III-level page tables = \n Number of pages in virtual memory\n\n2^(3x - 6) = 2^(46 - x)\n\n3x - 6 = 46 - x\n\n4x = 52\nx = 13\n\nThat means, page size is of 13 bits\nor Page size = 2^13 bytes = 8 KB "
},
{
"code": null,
"e": 26520,
"s": 26498,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26538,
"s": 26520,
"text": "memory-management"
},
{
"code": null,
"e": 26574,
"s": 26538,
"text": "Operating Systems-Memory Management"
},
{
"code": null,
"e": 26602,
"s": 26574,
"text": "Operating Systems Questions"
},
{
"code": null,
"e": 26700,
"s": 26602,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26709,
"s": 26700,
"text": "Comments"
},
{
"code": null,
"e": 26722,
"s": 26709,
"text": "Old Comments"
},
{
"code": null,
"e": 26754,
"s": 26722,
"text": "Scheduling in Greedy Algorithms"
},
{
"code": null,
"e": 26791,
"s": 26754,
"text": "Introduction and Installation of Git"
},
{
"code": null,
"e": 26826,
"s": 26791,
"text": "CPU Scheduling Numerical Questions"
},
{
"code": null,
"e": 26874,
"s": 26826,
"text": "Operating Systems | CPU Scheduling | Question 4"
},
{
"code": null,
"e": 26928,
"s": 26874,
"text": "Operating Systems | Input Output Systems | Question 2"
},
{
"code": null,
"e": 26976,
"s": 26928,
"text": "Operating Systems | CPU Scheduling | Question 5"
},
{
"code": null,
"e": 27024,
"s": 26976,
"text": "Operating Systems | CPU Scheduling | Question 3"
},
{
"code": null,
"e": 27050,
"s": 27024,
"text": "File System Inconsistency"
},
{
"code": null,
"e": 27092,
"s": 27050,
"text": "Operating Systems | Deadlock | Question 1"
}
] |
Target Sum | Practice | GeeksforGeeks | Given an array of integers A[] of length N and an integer target.
You want to build an expression out of A by adding one of the symbols '+' and '-' before each integer in A and then concatenate all the integers.
For example, if arr = {2, 1}, you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
Return the number of different expressions that can be built, which evaluates to target.
Example 1:
Input:
N = 5
A[] = {1, 1, 1, 1, 1}
target = 3
Output:
5
Explanation:
There are 5 ways to assign symbols to
make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
Example 2:
Input:
N = 1
A[] = {1}
target = 1
Output:
1
Your Task:
The task is to complete the function findTargetSumWays() which finds and returns the number of different expressions that can be built.
Expected Time Complexity: O(N*sum), where sum refers to the range of sum possible.
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ N ≤ 20
0 ≤ A[i] ≤ 1000
0 <= sum(A[i]) <= 104
-1000 <= target <= 1000
0
uratabhi3 weeks ago
class Solution { public: int findTargetSumWays(vector<int>&A ,int target) { int sum = std::accumulate(A.begin(), A.end(), 0); if((target+sum)%2!=0) return 0; int s1 = (target+sum)/2; vector<int> arr; int zeros(0); for(auto &i : A){ if(!i) zeros++; else arr.push_back(i); } int n = int(arr.size()); int dp[n+1][s1+1]; memset(dp, -1, sizeof(dp));
for(int i=0; i<=s1; i++){ dp[0][i] = 0; } for(int i=0; i<=n; i++){ dp[i][0] = 1; }
for(int i=1; i<=n; i++){ for(int j=1; j<=s1; j++){ if(arr[i-1]<=j){ dp[i][j] = dp[i-1][j-arr[i-1]] + dp[i-1][j]; } else{ dp[i][j] = dp[i-1][j]; } } } return (1<<zeros)*dp[n][s1]; }
0
gulshan991 month ago
class Solution {
public:
int dp[21][20001];
int dfs(int index,vector<int>&A,int target,int sum)
{
if(index==A.size())return sum==target?1:0;
if(dp[index][sum]!=-1)return dp[index][sum];
int count=0;
count+= dfs(index+1,A,target,sum+A[index]);
count+= dfs(index+1,A,target,sum-A[index]);
return dp[index][sum] = count;
}
int findTargetSumWays(vector<int>&A ,int target) {
//Your code here
memset(dp,-1,sizeof(dp));
return dfs(0,A,target,0);
}
};
+1
adityasingh1091 month ago
int findTargetSumWays(vector<int>&nums ,int target) {
int sum=0;
for(int i=0;i<nums.size();i++)
sum=sum+nums[i];
if (target<-sum || target>sum)
return 0;
vector<vector<int>> dp(nums.size() + 1, vector<int>(sum*2 + 1, 0));
//int dp[nums.size()+1][sum*2+1];
dp[0][sum]=1;
for(int i=1;i<=nums.size();i++)
{
for(int j=0;j<sum*2+1;j++)
{
if(j+nums[i-1]<sum*2+1)
dp[i][j]=dp[i][j]+dp[i-1][j+nums[i-1]];
if(j-nums[i-1]>=0)
dp[i][j]=dp[i][j]+dp[i-1][j-nums[i-1]];
}
}
return dp[nums.size()][sum+target];
}
0
ar08051 month ago
LOGIC USED
Let Two Subset be S1 and S2,Whose difference is equal to target as given in question.
Now
S1-S2=Target (1)
S1+S2=Total_Sum_Of_Array (2)
Subtracting Equation 1 from Equation 2.We will get:
2*S2 = Total_Sum_Of_Array-Target
Now Total_Sum_Of_Array-Target have to Even as it is equal to 2*S2 if It not Even return 0.
Now Applying Logic of Subset sum equal to given sum Logic where Target is S2,We will get Our count(Ans).
class Solution {
public:
int count(vector<int>& v, int tar,int n,vector<vector<int>>&t)
{
if(n==0 and tar==0)
{
return 1;
}
if(n==0)
{
return 0;
}
if(t[n][tar]!=-1)
{
return t[n][tar];
}
if(v[n-1]<=tar)
{
return(t[n][tar]=count(v,tar-v[n-1],n-1,t) + count(v,tar,n-1,t));
}
else
{
return(t[n][tar]=count(v,tar,n-1,t));
}
}
int findTargetSumWays(vector<int>& nums, int target) {
int sum=accumulate(nums.begin(),nums.end(),0);
int dif = (sum-target);
if(target>sum || (dif)%2!=0)
{
return 0;
}
vector<vector<int>>t(nums.size()+1,vector<int>((dif)/2+1,-1));
return(count(nums,(dif)/2,nums.size(),t));
}
};
-1
sougataroy8932 months ago
c++
int find(vector<int> a,int n,int t){ if(n==0 && t==0) return 1; if(n==0) return 0; return find(a,n-1,t-a[n-1])+find(a,n-1,t+a[n-1]); } int findTargetSumWays(vector<int>&A ,int target) { return find(A,A.size(),target); }
0
darsisriguruaakash2 months ago
class Solution:
def findTargetSumWays(self, arr, N, target):
# code here
sum_in = sum(arr)
sum_to = (target+sum_in)
if sum_to%2 != 0:
return 0
sum_to //=2
dp = [[0 for i in range(sum_to+1)] for i in range(N+1)]
for i in range(N+1):
dp[i][0] = 1
for i in range(1,sum_to+1):
dp[0][i] = 0
for i in range(1,N+1):
for j in range(1,sum_to+1):
if arr[i-1]>j:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = dp[i-1][j]+dp[i-1][j-arr[i-1]]
return dp[N][sum_to]
0
shariprakash3382 months ago
DP Solution
Similiar to O(1) Knapsack type: counting target sum till Subset of any + ve or -ve taken having subset sum till (Sum+target)/2
class Solution { public: int findTargetSumWays(vector<int>&A ,int target) { int sum = 0; int n = A.size(); for(int i = 0;i<A.size();i++){ sum += A[i]; } if((sum+target)%2!=0) return 0; int new_target = (sum + target)/2; int dp[n+1][new_target+1]; for(int i = 0;i<=n;i++){ for(int j = 0;j<=new_target; j++){ if(j==0) dp[i][j] = 1; else if(i==0) dp[i][j] = 0; else if(A[i-1]>j){ dp[i][j] = dp[i-1][j]; } else{ dp[i][j] = dp[i-1][j] + dp[i-1][j-A[i-1]]; } } } return dp[n][new_target]; }};
-1
code_rama3 months ago
static int findTargetSumWays(int[] arr , int N, int target) { // code here int arraysum = 0; int zeroes = 0; for(int i = 0; i < N; i++){ arraysum += arr[i]; } if((target + arraysum) % 2 == 1){ return 0; } int sum = (target + arraysum) / 2; sum = Math.abs(sum); int dp[][] = new int[N + 1][sum + 1]; for(int i = 0; i <= N; i++){ dp[i][0] = 1; } for(int i = 1; i <= N; i++){ for(int j = 1; j <= sum; j++){ if(arr[i - 1] <= j){ dp[i][j] = dp[i - 1][j - arr[i - 1]] + dp[i - 1][j]; }else{ dp[i][j] = dp[i - 1][j]; } } } return dp[N][sum]; }
+20
mukulbansal4213 months ago
Aditya verma OP
0
sandeep55213 months ago
C++ 10 lines DP Solution.
class Solution {
public:
map<pair<int,int>,int> mp;
int func(vector<int> v,int n,int tar)
{
if(!n and !tar) return 1;
if(!n) return 0;
if(mp.find({n,tar})!=mp.end())
return mp[{n,tar}];
mp[{n,tar}]=func(v,n-1,tar+v[n-1])+func(v,n-1,tar-v[n-1]);
return mp[{n,tar}];
}
int findTargetSumWays(vector<int>&A ,int target) {
return func(A,A.size(),target);
}
};
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": 450,
"s": 238,
"text": "Given an array of integers A[] of length N and an integer target.\nYou want to build an expression out of A by adding one of the symbols '+' and '-' before each integer in A and then concatenate all the integers."
},
{
"code": null,
"e": 579,
"s": 450,
"text": "For example, if arr = {2, 1}, you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression \"+2-1\"."
},
{
"code": null,
"e": 668,
"s": 579,
"text": "Return the number of different expressions that can be built, which evaluates to target."
},
{
"code": null,
"e": 680,
"s": 668,
"text": "\nExample 1:"
},
{
"code": null,
"e": 939,
"s": 680,
"text": "Input:\nN = 5\nA[] = {1, 1, 1, 1, 1}\ntarget = 3\nOutput:\n5\nExplanation:\nThere are 5 ways to assign symbols to \nmake the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3\n\n"
},
{
"code": null,
"e": 950,
"s": 939,
"text": "Example 2:"
},
{
"code": null,
"e": 996,
"s": 950,
"text": "Input:\nN = 1\nA[] = {1}\ntarget = 1\nOutput:\n1\n\n"
},
{
"code": null,
"e": 1143,
"s": 996,
"text": "Your Task:\nThe task is to complete the function findTargetSumWays() which finds and returns the number of different expressions that can be built."
},
{
"code": null,
"e": 1260,
"s": 1145,
"text": "Expected Time Complexity: O(N*sum), where sum refers to the range of sum possible.\nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 1348,
"s": 1262,
"text": "Constraints:\n1 ≤ N ≤ 20\n0 ≤ A[i] ≤ 1000\n0 <= sum(A[i]) <= 104\n-1000 <= target <= 1000"
},
{
"code": null,
"e": 1350,
"s": 1348,
"text": "0"
},
{
"code": null,
"e": 1370,
"s": 1350,
"text": "uratabhi3 weeks ago"
},
{
"code": null,
"e": 1799,
"s": 1370,
"text": "class Solution { public: int findTargetSumWays(vector<int>&A ,int target) { int sum = std::accumulate(A.begin(), A.end(), 0); if((target+sum)%2!=0) return 0; int s1 = (target+sum)/2; vector<int> arr; int zeros(0); for(auto &i : A){ if(!i) zeros++; else arr.push_back(i); } int n = int(arr.size()); int dp[n+1][s1+1]; memset(dp, -1, sizeof(dp));"
},
{
"code": null,
"e": 1922,
"s": 1799,
"text": " for(int i=0; i<=s1; i++){ dp[0][i] = 0; } for(int i=0; i<=n; i++){ dp[i][0] = 1; }"
},
{
"code": null,
"e": 2222,
"s": 1922,
"text": " for(int i=1; i<=n; i++){ for(int j=1; j<=s1; j++){ if(arr[i-1]<=j){ dp[i][j] = dp[i-1][j-arr[i-1]] + dp[i-1][j]; } else{ dp[i][j] = dp[i-1][j]; } } } return (1<<zeros)*dp[n][s1]; }"
},
{
"code": null,
"e": 2224,
"s": 2222,
"text": "0"
},
{
"code": null,
"e": 2245,
"s": 2224,
"text": "gulshan991 month ago"
},
{
"code": null,
"e": 2790,
"s": 2245,
"text": "class Solution {\n public:\n int dp[21][20001];\n int dfs(int index,vector<int>&A,int target,int sum)\n {\n if(index==A.size())return sum==target?1:0;\n if(dp[index][sum]!=-1)return dp[index][sum];\n int count=0;\n count+= dfs(index+1,A,target,sum+A[index]);\n count+= dfs(index+1,A,target,sum-A[index]);\n return dp[index][sum] = count;\n }\n int findTargetSumWays(vector<int>&A ,int target) {\n //Your code here\n memset(dp,-1,sizeof(dp));\n return dfs(0,A,target,0);\n }\n};\n"
},
{
"code": null,
"e": 2793,
"s": 2790,
"text": "+1"
},
{
"code": null,
"e": 2819,
"s": 2793,
"text": "adityasingh1091 month ago"
},
{
"code": null,
"e": 3560,
"s": 2819,
"text": "int findTargetSumWays(vector<int>&nums ,int target) {\n int sum=0;\n for(int i=0;i<nums.size();i++)\n sum=sum+nums[i];\n \n if (target<-sum || target>sum) \n return 0;\n \n vector<vector<int>> dp(nums.size() + 1, vector<int>(sum*2 + 1, 0));\n //int dp[nums.size()+1][sum*2+1];\n dp[0][sum]=1;\n for(int i=1;i<=nums.size();i++)\n {\n for(int j=0;j<sum*2+1;j++)\n {\n if(j+nums[i-1]<sum*2+1)\n dp[i][j]=dp[i][j]+dp[i-1][j+nums[i-1]];\n if(j-nums[i-1]>=0)\n dp[i][j]=dp[i][j]+dp[i-1][j-nums[i-1]];\n }\n }\n return dp[nums.size()][sum+target];\n }"
},
{
"code": null,
"e": 3562,
"s": 3560,
"text": "0"
},
{
"code": null,
"e": 3580,
"s": 3562,
"text": "ar08051 month ago"
},
{
"code": null,
"e": 5003,
"s": 3580,
"text": "LOGIC USED\n\nLet Two Subset be S1 and S2,Whose difference is equal to target as given in question.\nNow\n\nS1-S2=Target (1)\n\nS1+S2=Total_Sum_Of_Array (2)\n\nSubtracting Equation 1 from Equation 2.We will get:\n\n2*S2 = Total_Sum_Of_Array-Target\n\nNow Total_Sum_Of_Array-Target have to Even as it is equal to 2*S2 if It not Even return 0.\n\nNow Applying Logic of Subset sum equal to given sum Logic where Target is S2,We will get Our count(Ans).\n\nclass Solution {\npublic:\n \n int count(vector<int>& v, int tar,int n,vector<vector<int>>&t)\n {\n \n if(n==0 and tar==0)\n {\n return 1;\n }\n if(n==0)\n {\n return 0;\n }\n if(t[n][tar]!=-1)\n {\n return t[n][tar];\n }\n \n if(v[n-1]<=tar)\n {\n return(t[n][tar]=count(v,tar-v[n-1],n-1,t) + count(v,tar,n-1,t));\n }\n else\n {\n return(t[n][tar]=count(v,tar,n-1,t));\n }\n \n \n \n }\n \n \n \n int findTargetSumWays(vector<int>& nums, int target) {\n \n int sum=accumulate(nums.begin(),nums.end(),0);\n \n \n \n int dif = (sum-target);\n if(target>sum || (dif)%2!=0)\n {\n return 0;\n }\n vector<vector<int>>t(nums.size()+1,vector<int>((dif)/2+1,-1));\n \n return(count(nums,(dif)/2,nums.size(),t));\n \n }\n};"
},
{
"code": null,
"e": 5006,
"s": 5003,
"text": "-1"
},
{
"code": null,
"e": 5032,
"s": 5006,
"text": "sougataroy8932 months ago"
},
{
"code": null,
"e": 5036,
"s": 5032,
"text": "c++"
},
{
"code": null,
"e": 5286,
"s": 5036,
"text": "int find(vector<int> a,int n,int t){ if(n==0 && t==0) return 1; if(n==0) return 0; return find(a,n-1,t-a[n-1])+find(a,n-1,t+a[n-1]); } int findTargetSumWays(vector<int>&A ,int target) { return find(A,A.size(),target); }"
},
{
"code": null,
"e": 5288,
"s": 5286,
"text": "0"
},
{
"code": null,
"e": 5319,
"s": 5288,
"text": "darsisriguruaakash2 months ago"
},
{
"code": null,
"e": 5959,
"s": 5319,
"text": "class Solution:\n def findTargetSumWays(self, arr, N, target):\n # code here \n sum_in = sum(arr)\n sum_to = (target+sum_in)\n if sum_to%2 != 0:\n return 0\n sum_to //=2\n dp = [[0 for i in range(sum_to+1)] for i in range(N+1)]\n for i in range(N+1):\n dp[i][0] = 1 \n for i in range(1,sum_to+1):\n dp[0][i] = 0 \n \n for i in range(1,N+1):\n for j in range(1,sum_to+1):\n if arr[i-1]>j:\n dp[i][j] = dp[i-1][j]\n else:\n dp[i][j] = dp[i-1][j]+dp[i-1][j-arr[i-1]]\n return dp[N][sum_to]\n"
},
{
"code": null,
"e": 5961,
"s": 5959,
"text": "0"
},
{
"code": null,
"e": 5989,
"s": 5961,
"text": "shariprakash3382 months ago"
},
{
"code": null,
"e": 6002,
"s": 5989,
"text": "DP Solution "
},
{
"code": null,
"e": 6130,
"s": 6002,
"text": "Similiar to O(1) Knapsack type: counting target sum till Subset of any + ve or -ve taken having subset sum till (Sum+target)/2"
},
{
"code": null,
"e": 6846,
"s": 6130,
"text": "class Solution { public: int findTargetSumWays(vector<int>&A ,int target) { int sum = 0; int n = A.size(); for(int i = 0;i<A.size();i++){ sum += A[i]; } if((sum+target)%2!=0) return 0; int new_target = (sum + target)/2; int dp[n+1][new_target+1]; for(int i = 0;i<=n;i++){ for(int j = 0;j<=new_target; j++){ if(j==0) dp[i][j] = 1; else if(i==0) dp[i][j] = 0; else if(A[i-1]>j){ dp[i][j] = dp[i-1][j]; } else{ dp[i][j] = dp[i-1][j] + dp[i-1][j-A[i-1]]; } } } return dp[n][new_target]; }};"
},
{
"code": null,
"e": 6851,
"s": 6848,
"text": "-1"
},
{
"code": null,
"e": 6873,
"s": 6851,
"text": "code_rama3 months ago"
},
{
"code": null,
"e": 7648,
"s": 6873,
"text": "static int findTargetSumWays(int[] arr , int N, int target) { // code here int arraysum = 0; int zeroes = 0; for(int i = 0; i < N; i++){ arraysum += arr[i]; } if((target + arraysum) % 2 == 1){ return 0; } int sum = (target + arraysum) / 2; sum = Math.abs(sum); int dp[][] = new int[N + 1][sum + 1]; for(int i = 0; i <= N; i++){ dp[i][0] = 1; } for(int i = 1; i <= N; i++){ for(int j = 1; j <= sum; j++){ if(arr[i - 1] <= j){ dp[i][j] = dp[i - 1][j - arr[i - 1]] + dp[i - 1][j]; }else{ dp[i][j] = dp[i - 1][j]; } } } return dp[N][sum]; }"
},
{
"code": null,
"e": 7652,
"s": 7648,
"text": "+20"
},
{
"code": null,
"e": 7679,
"s": 7652,
"text": "mukulbansal4213 months ago"
},
{
"code": null,
"e": 7695,
"s": 7679,
"text": "Aditya verma OP"
},
{
"code": null,
"e": 7697,
"s": 7695,
"text": "0"
},
{
"code": null,
"e": 7721,
"s": 7697,
"text": "sandeep55213 months ago"
},
{
"code": null,
"e": 7747,
"s": 7721,
"text": "C++ 10 lines DP Solution."
},
{
"code": null,
"e": 8174,
"s": 7747,
"text": "class Solution {\n public:\n map<pair<int,int>,int> mp;\n int func(vector<int> v,int n,int tar)\n {\n if(!n and !tar) return 1;\n if(!n) return 0;\n if(mp.find({n,tar})!=mp.end())\n return mp[{n,tar}];\n mp[{n,tar}]=func(v,n-1,tar+v[n-1])+func(v,n-1,tar-v[n-1]);\n return mp[{n,tar}];\n }\n int findTargetSumWays(vector<int>&A ,int target) {\n return func(A,A.size(),target);\n }\n};"
},
{
"code": null,
"e": 8320,
"s": 8174,
"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": 8356,
"s": 8320,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8366,
"s": 8356,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8376,
"s": 8366,
"text": "\nContest\n"
},
{
"code": null,
"e": 8439,
"s": 8376,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8587,
"s": 8439,
"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": 8795,
"s": 8587,
"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": 8901,
"s": 8795,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
AIML - First Application | Let us start creating first bot which will simply greet a user with Hello User! when a user types Hello Alice.
As in AIML Environment Setup, we've extracted content of program-ab in C > ab with the following directory structure.
c:/ab/bots
Stores AIML bots
c:/ab/lib
Stores Java libraries
c:/ab/out
Java class file directory
c:/ab/run.bat
batch file for running Program AB
Now, create a directory test inside C > ab > bots and create the following directories in it.
c:/ab/bots/test/aiml
Stores AIML files
c:/ab/bots/test/aimlif
Stores AIMLIF files
c:/ab/bots/test/config
Stores configuration files
c:/ab/bots/test/sets
Stores AIML Sets
c:/ab/bots/test/maps
Stores AIML Maps
Create test.aiml inside C > ab > bots > test > aiml and test.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version="1.0.1" encoding = "UTF-8"?>
<category>
<pattern> HELLO ALICE </pattern>
<template>
Hello User
</template>
</category>
</aiml>
0,HELLO ALICE,*,*,Hello User,test.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You'll see the following output −
Working Directory = C:\ab
Program AB 0.0.4.2 beta -- AI Foundation Reference AIML 2.0 implementation
bot = test
action = chat
trace = false
trace mode = false
Name = test Path = C:\ab/bots/test
C:\ab
C:\ab/bots
C:\ab/bots/test
C:\ab/bots/test/aiml
C:\ab/bots/test/aimlif
C:\ab/bots/test/config
C:\ab/bots/test/logs
C:\ab/bots/test/sets
C:\ab/bots/test/maps
Preprocessor: 0 norms 0 persons 0 person2
Get Properties: C:\ab/bots/test/config/properties.txt
addAIMLSets: C:\ab/bots/test/sets does not exist.
addCategories: C:\ab/bots/test/aiml does not exist.
AIML modified Tue Apr 07 22:24:29 IST 2015 AIMLIF modified Tue Apr 07 22:26:53 I
ST 2015
No deleted.aiml.csv file found
No deleted.aiml.csv file found
Loading AIML files from C:\ab/bots/test/aimlif
Reading Learnf file
Loaded 1 categories in 0.009 sec
--> Bot test 1 completed 0 deleted 0 unfinished
(1[6])--HELLO-->(1[5])--ALICE-->(1[4])--<THAT>-->(1[3])--*-->(1[2])--<TOPIC>-->(
1[1])--*-->(0[null,null]) Hello User...
7 nodes 6 singletons 1 leaves 0 shortcuts 0 n-ary 6 branches 0.85714287 average
branching
Human:
Type Hello Alice and see the result and then type anything else to see the changed result.
Human: hello alice
Robot: Hello User
Human: bye
Robot: I have no answer for that.
Human:
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1922,
"s": 1811,
"text": "Let us start creating first bot which will simply greet a user with Hello User! when a user types Hello Alice."
},
{
"code": null,
"e": 2040,
"s": 1922,
"text": "As in AIML Environment Setup, we've extracted content of program-ab in C > ab with the following directory structure."
},
{
"code": null,
"e": 2051,
"s": 2040,
"text": "c:/ab/bots"
},
{
"code": null,
"e": 2068,
"s": 2051,
"text": "Stores AIML bots"
},
{
"code": null,
"e": 2078,
"s": 2068,
"text": "c:/ab/lib"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Stores Java libraries"
},
{
"code": null,
"e": 2110,
"s": 2100,
"text": "c:/ab/out"
},
{
"code": null,
"e": 2136,
"s": 2110,
"text": "Java class file directory"
},
{
"code": null,
"e": 2150,
"s": 2136,
"text": "c:/ab/run.bat"
},
{
"code": null,
"e": 2184,
"s": 2150,
"text": "batch file for running Program AB"
},
{
"code": null,
"e": 2278,
"s": 2184,
"text": "Now, create a directory test inside C > ab > bots and create the following directories in it."
},
{
"code": null,
"e": 2299,
"s": 2278,
"text": "c:/ab/bots/test/aiml"
},
{
"code": null,
"e": 2317,
"s": 2299,
"text": "Stores AIML files"
},
{
"code": null,
"e": 2340,
"s": 2317,
"text": "c:/ab/bots/test/aimlif"
},
{
"code": null,
"e": 2360,
"s": 2340,
"text": "Stores AIMLIF files"
},
{
"code": null,
"e": 2383,
"s": 2360,
"text": "c:/ab/bots/test/config"
},
{
"code": null,
"e": 2410,
"s": 2383,
"text": "Stores configuration files"
},
{
"code": null,
"e": 2431,
"s": 2410,
"text": "c:/ab/bots/test/sets"
},
{
"code": null,
"e": 2448,
"s": 2431,
"text": "Stores AIML Sets"
},
{
"code": null,
"e": 2469,
"s": 2448,
"text": "c:/ab/bots/test/maps"
},
{
"code": null,
"e": 2486,
"s": 2469,
"text": "Stores AIML Maps"
},
{
"code": null,
"e": 2606,
"s": 2486,
"text": "Create test.aiml inside C > ab > bots > test > aiml and test.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 2837,
"s": 2606,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version=\"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> HELLO ALICE </pattern>\n \n <template>\n Hello User\n </template>\n \n </category>\n</aiml>"
},
{
"code": null,
"e": 2877,
"s": 2837,
"text": "0,HELLO ALICE,*,*,Hello User,test.aiml\n"
},
{
"code": null,
"e": 2950,
"s": 2877,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 3015,
"s": 2950,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 3049,
"s": 3015,
"text": "You'll see the following output −"
},
{
"code": null,
"e": 4126,
"s": 3049,
"text": "Working Directory = C:\\ab\n\nProgram AB 0.0.4.2 beta -- AI Foundation Reference AIML 2.0 implementation\nbot = test\naction = chat\ntrace = false\ntrace mode = false\nName = test Path = C:\\ab/bots/test\n\nC:\\ab\nC:\\ab/bots\nC:\\ab/bots/test\nC:\\ab/bots/test/aiml\nC:\\ab/bots/test/aimlif\nC:\\ab/bots/test/config\nC:\\ab/bots/test/logs\nC:\\ab/bots/test/sets\nC:\\ab/bots/test/maps\n\nPreprocessor: 0 norms 0 persons 0 person2\nGet Properties: C:\\ab/bots/test/config/properties.txt\naddAIMLSets: C:\\ab/bots/test/sets does not exist.\naddCategories: C:\\ab/bots/test/aiml does not exist.\nAIML modified Tue Apr 07 22:24:29 IST 2015 AIMLIF modified Tue Apr 07 22:26:53 I\nST 2015\nNo deleted.aiml.csv file found\nNo deleted.aiml.csv file found\nLoading AIML files from C:\\ab/bots/test/aimlif\n\nReading Learnf file\nLoaded 1 categories in 0.009 sec\n--> Bot test 1 completed 0 deleted 0 unfinished\n(1[6])--HELLO-->(1[5])--ALICE-->(1[4])--<THAT>-->(1[3])--*-->(1[2])--<TOPIC>-->(\n1[1])--*-->(0[null,null]) Hello User...\n7 nodes 6 singletons 1 leaves 0 shortcuts 0 n-ary 6 branches 0.85714287 average\nbranching\nHuman:\n"
},
{
"code": null,
"e": 4217,
"s": 4126,
"text": "Type Hello Alice and see the result and then type anything else to see the changed result."
},
{
"code": null,
"e": 4307,
"s": 4217,
"text": "Human: hello alice\nRobot: Hello User\nHuman: bye\nRobot: I have no answer for that.\nHuman:\n"
},
{
"code": null,
"e": 4314,
"s": 4307,
"text": " Print"
},
{
"code": null,
"e": 4325,
"s": 4314,
"text": " Add Notes"
}
] |
Python | Replace elements in second list with index of same element in first list | 18 Aug, 2021
Given two lists of strings, where first list contains all elements of second list, the task is to replace every element in second list with index of elements in first list.Method #1: Using Iteration
Python3
# Python code to replace every element# in second list with index of first element. # List InitializationInput1 = ['cut', 'god', 'pass']Input2 = ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass'] # List InitializationOutput = [] # Using iterationfor x in Input2: for y in Input1: if x == y: Output.append(Input1.index(y)) # Printing outputprint("initial 2 list are")print(Input1, "\n", Input2)print("Second list after replacement is:", Output)
initial 2 list are
['cut', 'god', 'pass']
['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']
Second list after replacement is: [1, 0, 0, 0, 1, 2, 0, 2]
Method #2: Using List comprehension
Python3
# Python code to replace every element# in second list with index of first element. # List initializationInput1 = ['cut', 'god', 'pass'] # using enumeratetemp = {y:x for x, y in enumerate(Input1)} # List initializationInput2 = ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass'] # Using list comprehensionOutput = [temp.get(elem) for elem in Input2] # Printing outputprint("initial 2 list are")print(Input1, "\n", Input2)print("Second list after replacement is:", Output)
initial 2 list are
['cut', 'god', 'pass']
['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']
Second list after replacement is: [1, 0, 0, 0, 1, 2, 0, 2]
Method #3 : Using map
Python3
# Python code to replace every element# in second list with index of first element. # List initializationInput1 = ['cut', 'god', 'pass'] # List initializationInput2 = ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass'] elem = {k: i for i, k in enumerate(Input1)}Output = list(map(elem.get, Input2)) # Printing outputprint("initial 2 list are")print(Input1, "\n", Input2)print("Second list after replacement is:", Output)
initial 2 list are
['cut', 'god', 'pass']
['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']
Second list after replacement is: [1, 0, 0, 0, 1, 2, 0, 2]
varshagumber28
Python list-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
How to Install PIP on Windows ?
*args and **kwargs in Python
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": "\n18 Aug, 2021"
},
{
"code": null,
"e": 229,
"s": 28,
"text": "Given two lists of strings, where first list contains all elements of second list, the task is to replace every element in second list with index of elements in first list.Method #1: Using Iteration "
},
{
"code": null,
"e": 237,
"s": 229,
"text": "Python3"
},
{
"code": "# Python code to replace every element# in second list with index of first element. # List InitializationInput1 = ['cut', 'god', 'pass']Input2 = ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass'] # List InitializationOutput = [] # Using iterationfor x in Input2: for y in Input1: if x == y: Output.append(Input1.index(y)) # Printing outputprint(\"initial 2 list are\")print(Input1, \"\\n\", Input2)print(\"Second list after replacement is:\", Output)",
"e": 719,
"s": 237,
"text": null
},
{
"code": null,
"e": 881,
"s": 719,
"text": "initial 2 list are\n['cut', 'god', 'pass'] \n ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']\nSecond list after replacement is: [1, 0, 0, 0, 1, 2, 0, 2]"
},
{
"code": null,
"e": 923,
"s": 883,
"text": " Method #2: Using List comprehension "
},
{
"code": null,
"e": 931,
"s": 923,
"text": "Python3"
},
{
"code": "# Python code to replace every element# in second list with index of first element. # List initializationInput1 = ['cut', 'god', 'pass'] # using enumeratetemp = {y:x for x, y in enumerate(Input1)} # List initializationInput2 = ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass'] # Using list comprehensionOutput = [temp.get(elem) for elem in Input2] # Printing outputprint(\"initial 2 list are\")print(Input1, \"\\n\", Input2)print(\"Second list after replacement is:\", Output)",
"e": 1419,
"s": 931,
"text": null
},
{
"code": null,
"e": 1581,
"s": 1419,
"text": "initial 2 list are\n['cut', 'god', 'pass'] \n ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']\nSecond list after replacement is: [1, 0, 0, 0, 1, 2, 0, 2]"
},
{
"code": null,
"e": 1609,
"s": 1583,
"text": " Method #3 : Using map "
},
{
"code": null,
"e": 1617,
"s": 1609,
"text": "Python3"
},
{
"code": "# Python code to replace every element# in second list with index of first element. # List initializationInput1 = ['cut', 'god', 'pass'] # List initializationInput2 = ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass'] elem = {k: i for i, k in enumerate(Input1)}Output = list(map(elem.get, Input2)) # Printing outputprint(\"initial 2 list are\")print(Input1, \"\\n\", Input2)print(\"Second list after replacement is:\", Output)",
"e": 2054,
"s": 1617,
"text": null
},
{
"code": null,
"e": 2216,
"s": 2054,
"text": "initial 2 list are\n['cut', 'god', 'pass'] \n ['god', 'cut', 'cut', 'cut', 'god', 'pass', 'cut', 'pass']\nSecond list after replacement is: [1, 0, 0, 0, 1, 2, 0, 2]"
},
{
"code": null,
"e": 2233,
"s": 2218,
"text": "varshagumber28"
},
{
"code": null,
"e": 2254,
"s": 2233,
"text": "Python list-programs"
},
{
"code": null,
"e": 2261,
"s": 2254,
"text": "Python"
},
{
"code": null,
"e": 2277,
"s": 2261,
"text": "Python Programs"
},
{
"code": null,
"e": 2375,
"s": 2277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2393,
"s": 2375,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2435,
"s": 2393,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2457,
"s": 2435,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2489,
"s": 2457,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2518,
"s": 2489,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2540,
"s": 2518,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2579,
"s": 2540,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2617,
"s": 2579,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2666,
"s": 2617,
"text": "Python | Convert string dictionary to dictionary"
}
] |
How does Selenium Webdriver handle SSL certificate in Chrome? | We can handle SSL certificate with Selenium webdriver in Chrome browser. A SSL is the standardized protocol used to create a connection between the browser and server.
The information exchanged via a SSL certificate is encrypted and it verifies if the information is sent to the correct server. It authenticates a website and provides protection from hacking.
An untrusted SSL certificate error is thrown if there are problems in the SSL certificate. We shall receive such an error while we launch a website. In Chrome, we use the ChromeOptions class to work with SSL certificates.
We shall create an instance of this class and set the capability - setAcceptInsecureCerts to true. Finally, this property of the Chrome browser shall be passed to the webdriver object.
ChromeOptions c = new ChromeOptions();
c.setAcceptInsecureCerts(true);
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.WebDriver;
public class SSLErrorChrome {
public static void main(String[] args) throws IOException {
//object of ChromeOptions
ChromeOptions c = new ChromeOptions();
//set browser properties
c.setAcceptInsecureCerts(true);
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
// pass browser option to webdriver
WebDriver driver = new ChromeDriver(c);
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("application url to be entered");
driver.quit();
}
} | [
{
"code": null,
"e": 1355,
"s": 1187,
"text": "We can handle SSL certificate with Selenium webdriver in Chrome browser. A SSL is the standardized protocol used to create a connection between the browser and server."
},
{
"code": null,
"e": 1547,
"s": 1355,
"text": "The information exchanged via a SSL certificate is encrypted and it verifies if the information is sent to the correct server. It authenticates a website and provides protection from hacking."
},
{
"code": null,
"e": 1769,
"s": 1547,
"text": "An untrusted SSL certificate error is thrown if there are problems in the SSL certificate. We shall receive such an error while we launch a website. In Chrome, we use the ChromeOptions class to work with SSL certificates."
},
{
"code": null,
"e": 1954,
"s": 1769,
"text": "We shall create an instance of this class and set the capability - setAcceptInsecureCerts to true. Finally, this property of the Chrome browser shall be passed to the webdriver object."
},
{
"code": null,
"e": 2025,
"s": 1954,
"text": "ChromeOptions c = new ChromeOptions();\nc.setAcceptInsecureCerts(true);"
},
{
"code": null,
"e": 2826,
"s": 2025,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.chrome.ChromeOptions;\nimport org.openqa.selenium.WebDriver;\npublic class SSLErrorChrome {\n public static void main(String[] args) throws IOException {\n //object of ChromeOptions\n ChromeOptions c = new ChromeOptions();\n\n //set browser properties\n c.setAcceptInsecureCerts(true);\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n // pass browser option to webdriver\n WebDriver driver = new ChromeDriver(c);\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"application url to be entered\");\n driver.quit();\n }\n}"
}
] |
ReactJS | Lists | 12 Jan, 2021
Lists are very useful when it comes to developing the UI of any website. Lists are mainly used for displaying menus in a website, for example, the navbar menu. In regular JavaScript, we can use arrays for creating lists. We can create lists in React in a similar manner as we do in regular JavaScript. We will see how to do this in detail further in this article.Let’s first see how we can traverse and update any list in regular JavaScript. We can use the map() function in JavaScript for traversing the lists.
Below JavaScript code illustrate using map() function to traverse lists:
Javascript
<script type="text/javascript"> var numbers = [1,2,3,4,5]; const updatedNums = numbers.map((number)=>{ return (number + 2); }); console.log(updatedNums);</script>
The above code will log the below output to the console:
[3, 4, 5, 6, 7]
Let us now create a list of elements in React. We will render the list numbers in the above code as an unordered list element in the browser rather than simply logging in to the console. To do this, we will traverse the list using the JavaScript map() function and updates elements to be enclosed between <li> </li> elements. Finally we will wrap this new list within <ul> </ul> elements and render it to the DOM.
The below code illustrates this:
Javascript
import React from 'react';import ReactDOM from 'react-dom'; const numbers = [1,2,3,4,5]; const updatedNums = numbers.map((number)=>{ return <li>{number}</li>;}); ReactDOM.render( <ul> {updatedNums} </ul>, document.getElementById('root'));
The above code will render an unordered list as shown in below output:
Rendering lists inside Components
In the above code in React, we had directly rendered the list to the DOM. But usually this not a good practice to render lists in React. We already have talked about the uses of Components and had seen that everything in React is built as individual components. Consider the example of a Navigation Menu. It is obvious that in any website the items in a navigation menu are not hard coded. This item is fetched from the database and then displayed as lists in the browser. So from the component’s point of view, we can say that we will pass a list to a component using props and then use this component to render the list to the DOM. We can update the above code in which we have directly rendered the list to now a component that will accept an array as props and returns an unordered list.
Javascript
import React from 'react';import ReactDOM from 'react-dom'; // Component that will return an// unordered listfunction Navmenu(props){ const list = props.menuitems; const updatedList = list.map((listItems)=>{ return <li>{listItems}</li>; }); return( <ul>{updatedList}</ul> );} const menuItems = [1,2,3,4,5]; ReactDOM.render( <Navmenu menuitems = {menuItems} />, document.getElementById('root'));
Output:
You can see in the above output that the unordered list is successfully rendered to the browser but a warning message is logged to the console.
Warning: Each child in an array or iterator
should have a unique "key" prop
The above warning message says that each of the list items in our unordered list should have a unique key. A “key” is a special string attribute you need to include when creating lists of elements in React. We will discuss about keys in detail in further articles. For now, let’s just assign a string key to each of our list items in the above code.
Below is the updated code with keys:
Javascript
import React from 'react';import ReactDOM from 'react-dom'; // Component that will return an// unordered listfunction Navmenu(props){ const list = props.menuitems; const updatedList = list.map((listItems)=>{ return( <li key={listItems.toString()}> {listItems} </li> ); }); return( <ul>{updatedList}</ul> );} const menuItems = [1,2,3,4,5]; ReactDOM.render( <Navmenu menuitems = {menuItems} />, document.getElementById('root'));
This code will give the same output as that of the previous code but this time without any warning. Keys are used in React to identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists. We will learn about keys in more detail in our next article.
shubhamyadav4
JavaScript-Misc
react-js
JavaScript
ReactJS
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
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS setState()
How to pass data from one component to other component in ReactJS ? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jan, 2021"
},
{
"code": null,
"e": 564,
"s": 52,
"text": "Lists are very useful when it comes to developing the UI of any website. Lists are mainly used for displaying menus in a website, for example, the navbar menu. In regular JavaScript, we can use arrays for creating lists. We can create lists in React in a similar manner as we do in regular JavaScript. We will see how to do this in detail further in this article.Let’s first see how we can traverse and update any list in regular JavaScript. We can use the map() function in JavaScript for traversing the lists."
},
{
"code": null,
"e": 639,
"s": 564,
"text": "Below JavaScript code illustrate using map() function to traverse lists: "
},
{
"code": null,
"e": 650,
"s": 639,
"text": "Javascript"
},
{
"code": "<script type=\"text/javascript\"> var numbers = [1,2,3,4,5]; const updatedNums = numbers.map((number)=>{ return (number + 2); }); console.log(updatedNums);</script>",
"e": 836,
"s": 650,
"text": null
},
{
"code": null,
"e": 895,
"s": 836,
"text": "The above code will log the below output to the console: "
},
{
"code": null,
"e": 911,
"s": 895,
"text": "[3, 4, 5, 6, 7]"
},
{
"code": null,
"e": 1325,
"s": 911,
"text": "Let us now create a list of elements in React. We will render the list numbers in the above code as an unordered list element in the browser rather than simply logging in to the console. To do this, we will traverse the list using the JavaScript map() function and updates elements to be enclosed between <li> </li> elements. Finally we will wrap this new list within <ul> </ul> elements and render it to the DOM."
},
{
"code": null,
"e": 1360,
"s": 1325,
"text": "The below code illustrates this: "
},
{
"code": null,
"e": 1371,
"s": 1360,
"text": "Javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom'; const numbers = [1,2,3,4,5]; const updatedNums = numbers.map((number)=>{ return <li>{number}</li>;}); ReactDOM.render( <ul> {updatedNums} </ul>, document.getElementById('root'));",
"e": 1633,
"s": 1371,
"text": null
},
{
"code": null,
"e": 1705,
"s": 1633,
"text": "The above code will render an unordered list as shown in below output: "
},
{
"code": null,
"e": 1741,
"s": 1707,
"text": "Rendering lists inside Components"
},
{
"code": null,
"e": 2534,
"s": 1741,
"text": "In the above code in React, we had directly rendered the list to the DOM. But usually this not a good practice to render lists in React. We already have talked about the uses of Components and had seen that everything in React is built as individual components. Consider the example of a Navigation Menu. It is obvious that in any website the items in a navigation menu are not hard coded. This item is fetched from the database and then displayed as lists in the browser. So from the component’s point of view, we can say that we will pass a list to a component using props and then use this component to render the list to the DOM. We can update the above code in which we have directly rendered the list to now a component that will accept an array as props and returns an unordered list. "
},
{
"code": null,
"e": 2545,
"s": 2534,
"text": "Javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom'; // Component that will return an// unordered listfunction Navmenu(props){ const list = props.menuitems; const updatedList = list.map((listItems)=>{ return <li>{listItems}</li>; }); return( <ul>{updatedList}</ul> );} const menuItems = [1,2,3,4,5]; ReactDOM.render( <Navmenu menuitems = {menuItems} />, document.getElementById('root'));",
"e": 2983,
"s": 2545,
"text": null
},
{
"code": null,
"e": 2992,
"s": 2983,
"text": "Output: "
},
{
"code": null,
"e": 3137,
"s": 2992,
"text": "You can see in the above output that the unordered list is successfully rendered to the browser but a warning message is logged to the console. "
},
{
"code": null,
"e": 3222,
"s": 3137,
"text": "Warning: Each child in an array or iterator\n should have a unique \"key\" prop"
},
{
"code": null,
"e": 3572,
"s": 3222,
"text": "The above warning message says that each of the list items in our unordered list should have a unique key. A “key” is a special string attribute you need to include when creating lists of elements in React. We will discuss about keys in detail in further articles. For now, let’s just assign a string key to each of our list items in the above code."
},
{
"code": null,
"e": 3611,
"s": 3572,
"text": "Below is the updated code with keys: "
},
{
"code": null,
"e": 3622,
"s": 3611,
"text": "Javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom'; // Component that will return an// unordered listfunction Navmenu(props){ const list = props.menuitems; const updatedList = list.map((listItems)=>{ return( <li key={listItems.toString()}> {listItems} </li> ); }); return( <ul>{updatedList}</ul> );} const menuItems = [1,2,3,4,5]; ReactDOM.render( <Navmenu menuitems = {menuItems} />, document.getElementById('root'));",
"e": 4153,
"s": 3622,
"text": null
},
{
"code": null,
"e": 4504,
"s": 4153,
"text": "This code will give the same output as that of the previous code but this time without any warning. Keys are used in React to identify which items in the list are changed, updated, or deleted. In other words, we can say that keys are used to give an identity to the elements in the lists. We will learn about keys in more detail in our next article. "
},
{
"code": null,
"e": 4518,
"s": 4504,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 4534,
"s": 4518,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 4543,
"s": 4534,
"text": "react-js"
},
{
"code": null,
"e": 4554,
"s": 4543,
"text": "JavaScript"
},
{
"code": null,
"e": 4562,
"s": 4554,
"text": "ReactJS"
},
{
"code": null,
"e": 4579,
"s": 4562,
"text": "Web Technologies"
},
{
"code": null,
"e": 4677,
"s": 4579,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4738,
"s": 4677,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4778,
"s": 4738,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4831,
"s": 4778,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4872,
"s": 4831,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4924,
"s": 4872,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 4967,
"s": 4924,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 5012,
"s": 4967,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 5050,
"s": 5012,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 5069,
"s": 5050,
"text": "ReactJS setState()"
}
] |
How to make a div stick to the top of the screen ? | 12 May, 2022
In this article, we will know how to make a sticky element that will stick to the top of the screen. Here, we have used the div to stick to the top of the screen. We will understand its implementation by using the below 2 methods.
Method 1: Using the sticky value of the position property
The ‘sticky’ value of the position property sets an element to use a ‘relative’ position unless it crosses a specific portion of the page, after which the ‘fixed’ position is used. The vertical position of the element to be stuck can also be modified with the help of the ‘top’ property. It can be given a value of ‘0px’ to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.
Example: This example illustrates the use of the position property to stick to the top of the element.
HTML
<!DOCTYPE html><html><head> <style> .sticky-div { background-color: green; position: sticky; top: 0px; padding: 10px 0px; } .start { height: 100px; } .end { height: 500px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <h3>Sticky Element</h3> <b> How to make a div stick to the top of the screen once it’s been scrolled to? </b> <p class="start"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions. </p> <div class="sticky-div"> This is div will stick to the top when it has been scrolled past </div> <p class="end"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions. </p> </body></html>
Output:
Method 2: Setting the div to be stuck after it had scrolled past
This method attempts to emulate the “position: sticky” method. The element is set to ‘fixed’ or ‘relative’ depending upon whether the user has scrolled past the element.The element to be stuck is first identified and its current position on the page is calculated. This is done by adding the position of the element relative to the viewport with the current scroll position.
The getBoundingClientRect() method returns a DOMReact object of which the ‘top’ value could be used to get the position relative to the viewport. The current vertical scroll position can be found out by using the window.pageYOffset property. Adding both these values would give us the position of the element on the page regardless of the current scroll position.
The onscroll method is then overridden with a new function to calculate the current scroll position and compare it to the element’s position on the page. If the vertical scroll is more than the element’s position, the position property is set to ‘fixed’, and the ‘top’ property is given a value of ‘0px’. Otherwise, the position is set to ‘relative’, and the ‘top’ property is reset using the ‘initial’ value.
This will compare and make the element stick whenever the user scrolls past the element.
Example: This example illustrates the setup for the div to stuck after it had scrolled past.
HTML
<!DOCTYPE html><html><head> <style> .sticky-div { background-color: green; position: relative; width: 100%; padding: 10px 0px; } .start { height: 100px; } .end { height: 500px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to make a div stick to the top of the screen once it’s been scrolled to? </b> <p class="start"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions. </p> <div class="sticky-div"> This is div will stick to the top when it has been scrolled past </div> <p class="end"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions. </p> <script> stickyElem = document.querySelector(".sticky-div"); /* Gets the amount of height of the element from the viewport and adds the pageYOffset to get the height relative to the page */ currStickyPos = stickyElem.getBoundingClientRect().top + window.pageYOffset; window.onscroll = function() { /* Check if the current Y offset is greater than the position of the element */ if(window.pageYOffset > currStickyPos) { stickyElem.style.position = "fixed"; stickyElem.style.top = "0px"; } else { stickyElem.style.position = "relative"; stickyElem.style.top = "initial"; } } </script></body></html>
Output:
bhaskargeeksforgeeks
sagartomar9927
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
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 fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 259,
"s": 28,
"text": "In this article, we will know how to make a sticky element that will stick to the top of the screen. Here, we have used the div to stick to the top of the screen. We will understand its implementation by using the below 2 methods."
},
{
"code": null,
"e": 317,
"s": 259,
"text": "Method 1: Using the sticky value of the position property"
},
{
"code": null,
"e": 769,
"s": 317,
"text": "The ‘sticky’ value of the position property sets an element to use a ‘relative’ position unless it crosses a specific portion of the page, after which the ‘fixed’ position is used. The vertical position of the element to be stuck can also be modified with the help of the ‘top’ property. It can be given a value of ‘0px’ to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport."
},
{
"code": null,
"e": 872,
"s": 769,
"text": "Example: This example illustrates the use of the position property to stick to the top of the element."
},
{
"code": null,
"e": 877,
"s": 872,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <style> .sticky-div { background-color: green; position: sticky; top: 0px; padding: 10px 0px; } .start { height: 100px; } .end { height: 500px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <h3>Sticky Element</h3> <b> How to make a div stick to the top of the screen once it’s been scrolled to? </b> <p class=\"start\"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions. </p> <div class=\"sticky-div\"> This is div will stick to the top when it has been scrolled past </div> <p class=\"end\"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions. </p> </body></html>",
"e": 2112,
"s": 877,
"text": null
},
{
"code": null,
"e": 2120,
"s": 2112,
"text": "Output:"
},
{
"code": null,
"e": 2187,
"s": 2120,
"text": "Method 2: Setting the div to be stuck after it had scrolled past "
},
{
"code": null,
"e": 2562,
"s": 2187,
"text": "This method attempts to emulate the “position: sticky” method. The element is set to ‘fixed’ or ‘relative’ depending upon whether the user has scrolled past the element.The element to be stuck is first identified and its current position on the page is calculated. This is done by adding the position of the element relative to the viewport with the current scroll position."
},
{
"code": null,
"e": 2926,
"s": 2562,
"text": "The getBoundingClientRect() method returns a DOMReact object of which the ‘top’ value could be used to get the position relative to the viewport. The current vertical scroll position can be found out by using the window.pageYOffset property. Adding both these values would give us the position of the element on the page regardless of the current scroll position."
},
{
"code": null,
"e": 3336,
"s": 2926,
"text": "The onscroll method is then overridden with a new function to calculate the current scroll position and compare it to the element’s position on the page. If the vertical scroll is more than the element’s position, the position property is set to ‘fixed’, and the ‘top’ property is given a value of ‘0px’. Otherwise, the position is set to ‘relative’, and the ‘top’ property is reset using the ‘initial’ value."
},
{
"code": null,
"e": 3426,
"s": 3336,
"text": "This will compare and make the element stick whenever the user scrolls past the element. "
},
{
"code": null,
"e": 3519,
"s": 3426,
"text": "Example: This example illustrates the setup for the div to stuck after it had scrolled past."
},
{
"code": null,
"e": 3524,
"s": 3519,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <style> .sticky-div { background-color: green; position: relative; width: 100%; padding: 10px 0px; } .start { height: 100px; } .end { height: 500px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to make a div stick to the top of the screen once it’s been scrolled to? </b> <p class=\"start\"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions. </p> <div class=\"sticky-div\"> This is div will stick to the top when it has been scrolled past </div> <p class=\"end\"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions. </p> <script> stickyElem = document.querySelector(\".sticky-div\"); /* Gets the amount of height of the element from the viewport and adds the pageYOffset to get the height relative to the page */ currStickyPos = stickyElem.getBoundingClientRect().top + window.pageYOffset; window.onscroll = function() { /* Check if the current Y offset is greater than the position of the element */ if(window.pageYOffset > currStickyPos) { stickyElem.style.position = \"fixed\"; stickyElem.style.top = \"0px\"; } else { stickyElem.style.position = \"relative\"; stickyElem.style.top = \"initial\"; } } </script></body></html>",
"e": 5443,
"s": 3524,
"text": null
},
{
"code": null,
"e": 5452,
"s": 5443,
"text": "Output: "
},
{
"code": null,
"e": 5473,
"s": 5452,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 5488,
"s": 5473,
"text": "sagartomar9927"
},
{
"code": null,
"e": 5504,
"s": 5488,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 5511,
"s": 5504,
"text": "Picked"
},
{
"code": null,
"e": 5522,
"s": 5511,
"text": "JavaScript"
},
{
"code": null,
"e": 5539,
"s": 5522,
"text": "Web Technologies"
},
{
"code": null,
"e": 5637,
"s": 5539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5698,
"s": 5637,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5770,
"s": 5698,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5810,
"s": 5770,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5851,
"s": 5810,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5893,
"s": 5851,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 5926,
"s": 5893,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5988,
"s": 5926,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 6049,
"s": 5988,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6092,
"s": 6049,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Java Program to Find Duplicate Words in a Regular Expression | 20 Nov, 2020
Given an Expression which is represented by String. The task is to find duplicate elements in a Regular Expression in Java. Use a map or set data structures for identifying the uniqueness of words in a sentence.
Examples:
Input : str = " Hi, I am Hritik and I am a programmer. "
Output: I am
Explanation: We are printing duplicate words in the given Expression.
Input : str = " Ironman is alive. "
Output: There is no Duplicate Word.
Explanation: There are no duplicate words present in the given Expression.
Approach 1:
Get the Expression.Store all Words in an Array.Splitting word using regex ‘\\W’. (use of regex)Iterating in the array and storing words and all the number of occurrences in the Map.Now, In the Map, If the number of occurrences is more than 1 then we are printing the word.
Get the Expression.
Store all Words in an Array.
Splitting word using regex ‘\\W’. (use of regex)
Iterating in the array and storing words and all the number of occurrences in the Map.
Now, In the Map, If the number of occurrences is more than 1 then we are printing the word.
Below is the implementation of the above approach:
Java
// Find Duplicate Words in a Regular Expression in Javaimport java.util.*; public class GFG { public static void main(String[] args) { // we have a expression String expression = "Hi, I am Hritik and I am a programmer"; // splitting words using regex String[] words = expression.split("\\W"); // we are creating a Map for storing // strings and it's occurrence" Map<String, Integer> word_map = new HashMap<>(); // Here we are iterating in words array and // increasing it's occurrence by 1. for (String word : words) { if (word_map.get(word) != null) { word_map.put(word, word_map.get(word) + 1); } // if the word came once then occurrence is 1. else { word_map.put(word, 1); } } // creating a keyset of word_map Set<String> word_set = word_map.keySet(); // We are iterating in word set for (String word : word_set) { // if word matched then checking occurrence if (word_map.get(word) > 1) // here we are printing the duplicate words System.out.println(word); } }}
I
am
Approach 2:
Get the Expression.Store all Words in an Array.Splitting word using regex ‘\\W’. (use of regex)Matching every word of the array with other words through iteration.If words matched then adding words in a Set because set removes the repeated words added by the flow of iteration.Finally, we are printing the set.
Get the Expression.
Store all Words in an Array.
Splitting word using regex ‘\\W’. (use of regex)
Matching every word of the array with other words through iteration.
If words matched then adding words in a Set because set removes the repeated words added by the flow of iteration.
Finally, we are printing the set.
Below is the implementation of the above approach:
Java
// Find Duplicate Words in a Regular Expression in Javaimport java.util.*; public class Main { public static void main(String[] args) { String expression = "Hi, I am Hritik and I am a programmer"; // splitting words using regex String[] words = expression.split("\\W"); // creating object of HashSet class implemented by Set<String> set = new HashSet<>(); // here we are iterating in Array for (int i = 0; i < words.length - 1; i++) { for (int j = 1; j < words.length; j++) { // if strings matched then adding strings in // Set because if we ad same string set will // remove one and we have only repeated // words. if (words[i].equals(words[j]) && i != j) { set.add(words[i]); } } } // here we are printing the set System.out.println(set); }}
[I, am]
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Nov, 2020"
},
{
"code": null,
"e": 240,
"s": 28,
"text": "Given an Expression which is represented by String. The task is to find duplicate elements in a Regular Expression in Java. Use a map or set data structures for identifying the uniqueness of words in a sentence."
},
{
"code": null,
"e": 250,
"s": 240,
"text": "Examples:"
},
{
"code": null,
"e": 539,
"s": 250,
"text": "Input : str = \" Hi, I am Hritik and I am a programmer. \"\nOutput: I am\nExplanation: We are printing duplicate words in the given Expression.\n\nInput : str = \" Ironman is alive. \"\nOutput: There is no Duplicate Word.\nExplanation: There are no duplicate words present in the given Expression.\n"
},
{
"code": null,
"e": 551,
"s": 539,
"text": "Approach 1:"
},
{
"code": null,
"e": 824,
"s": 551,
"text": "Get the Expression.Store all Words in an Array.Splitting word using regex ‘\\\\W’. (use of regex)Iterating in the array and storing words and all the number of occurrences in the Map.Now, In the Map, If the number of occurrences is more than 1 then we are printing the word."
},
{
"code": null,
"e": 844,
"s": 824,
"text": "Get the Expression."
},
{
"code": null,
"e": 873,
"s": 844,
"text": "Store all Words in an Array."
},
{
"code": null,
"e": 922,
"s": 873,
"text": "Splitting word using regex ‘\\\\W’. (use of regex)"
},
{
"code": null,
"e": 1009,
"s": 922,
"text": "Iterating in the array and storing words and all the number of occurrences in the Map."
},
{
"code": null,
"e": 1101,
"s": 1009,
"text": "Now, In the Map, If the number of occurrences is more than 1 then we are printing the word."
},
{
"code": null,
"e": 1152,
"s": 1101,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1157,
"s": 1152,
"text": "Java"
},
{
"code": "// Find Duplicate Words in a Regular Expression in Javaimport java.util.*; public class GFG { public static void main(String[] args) { // we have a expression String expression = \"Hi, I am Hritik and I am a programmer\"; // splitting words using regex String[] words = expression.split(\"\\\\W\"); // we are creating a Map for storing // strings and it's occurrence\" Map<String, Integer> word_map = new HashMap<>(); // Here we are iterating in words array and // increasing it's occurrence by 1. for (String word : words) { if (word_map.get(word) != null) { word_map.put(word, word_map.get(word) + 1); } // if the word came once then occurrence is 1. else { word_map.put(word, 1); } } // creating a keyset of word_map Set<String> word_set = word_map.keySet(); // We are iterating in word set for (String word : word_set) { // if word matched then checking occurrence if (word_map.get(word) > 1) // here we are printing the duplicate words System.out.println(word); } }}",
"e": 2414,
"s": 1157,
"text": null
},
{
"code": null,
"e": 2419,
"s": 2414,
"text": "I\nam"
},
{
"code": null,
"e": 2431,
"s": 2419,
"text": "Approach 2:"
},
{
"code": null,
"e": 2742,
"s": 2431,
"text": "Get the Expression.Store all Words in an Array.Splitting word using regex ‘\\\\W’. (use of regex)Matching every word of the array with other words through iteration.If words matched then adding words in a Set because set removes the repeated words added by the flow of iteration.Finally, we are printing the set."
},
{
"code": null,
"e": 2762,
"s": 2742,
"text": "Get the Expression."
},
{
"code": null,
"e": 2791,
"s": 2762,
"text": "Store all Words in an Array."
},
{
"code": null,
"e": 2840,
"s": 2791,
"text": "Splitting word using regex ‘\\\\W’. (use of regex)"
},
{
"code": null,
"e": 2909,
"s": 2840,
"text": "Matching every word of the array with other words through iteration."
},
{
"code": null,
"e": 3024,
"s": 2909,
"text": "If words matched then adding words in a Set because set removes the repeated words added by the flow of iteration."
},
{
"code": null,
"e": 3058,
"s": 3024,
"text": "Finally, we are printing the set."
},
{
"code": null,
"e": 3109,
"s": 3058,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 3114,
"s": 3109,
"text": "Java"
},
{
"code": "// Find Duplicate Words in a Regular Expression in Javaimport java.util.*; public class Main { public static void main(String[] args) { String expression = \"Hi, I am Hritik and I am a programmer\"; // splitting words using regex String[] words = expression.split(\"\\\\W\"); // creating object of HashSet class implemented by Set<String> set = new HashSet<>(); // here we are iterating in Array for (int i = 0; i < words.length - 1; i++) { for (int j = 1; j < words.length; j++) { // if strings matched then adding strings in // Set because if we ad same string set will // remove one and we have only repeated // words. if (words[i].equals(words[j]) && i != j) { set.add(words[i]); } } } // here we are printing the set System.out.println(set); }}",
"e": 4094,
"s": 3114,
"text": null
},
{
"code": null,
"e": 4102,
"s": 4094,
"text": "[I, am]"
},
{
"code": null,
"e": 4109,
"s": 4102,
"text": "Picked"
},
{
"code": null,
"e": 4133,
"s": 4109,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4138,
"s": 4133,
"text": "Java"
},
{
"code": null,
"e": 4152,
"s": 4138,
"text": "Java Programs"
},
{
"code": null,
"e": 4171,
"s": 4152,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4176,
"s": 4171,
"text": "Java"
}
] |
Python SQLite – Create Table | 13 Jan, 2022
In this article, we will discuss how can we create tables in the SQLite database from the Python program using the sqlite3 module.
In SQLite database we use the following syntax to create a table:
CREATE TABLE database_name.table_name(
column1 datatype PRIMARY KEY(one or more columns),
column2 datatype,
column3 datatype,
.....
columnN datatype
);
Now we will create a table using Python:
Approach:
Import the required module
Establish the connection or create a connection object with the database using the connect() function of the sqlite3 module.
Create a Cursor object by calling the cursor() method of the Connection object.
Form table using the CREATE TABLE statement with the execute() method of the Cursor class.
Implementation:
Python3
import sqlite3 # Connecting to sqlite# connection objectconnection_obj = sqlite3.connect('geek.db') # cursor objectcursor_obj = connection_obj.cursor() # Drop the GEEK table if already exists.cursor_obj.execute("DROP TABLE IF EXISTS GEEK") # Creating tabletable = """ CREATE TABLE GEEK ( Email VARCHAR(255) NOT NULL, First_Name CHAR(25) NOT NULL, Last_Name CHAR(25), Score INT ); """ cursor_obj.execute(table) print("Table is Ready") # Close the connectionconnection_obj.close()
Output:
rkbhola5
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 160,
"s": 28,
"text": "In this article, we will discuss how can we create tables in the SQLite database from the Python program using the sqlite3 module. "
},
{
"code": null,
"e": 226,
"s": 160,
"text": "In SQLite database we use the following syntax to create a table:"
},
{
"code": null,
"e": 265,
"s": 226,
"text": "CREATE TABLE database_name.table_name("
},
{
"code": null,
"e": 355,
"s": 265,
"text": " column1 datatype PRIMARY KEY(one or more columns),"
},
{
"code": null,
"e": 412,
"s": 355,
"text": " column2 datatype,"
},
{
"code": null,
"e": 469,
"s": 412,
"text": " column3 datatype,"
},
{
"code": null,
"e": 514,
"s": 469,
"text": " ....."
},
{
"code": null,
"e": 570,
"s": 514,
"text": " columnN datatype"
},
{
"code": null,
"e": 573,
"s": 570,
"text": ");"
},
{
"code": null,
"e": 614,
"s": 573,
"text": "Now we will create a table using Python:"
},
{
"code": null,
"e": 624,
"s": 614,
"text": "Approach:"
},
{
"code": null,
"e": 651,
"s": 624,
"text": "Import the required module"
},
{
"code": null,
"e": 776,
"s": 651,
"text": "Establish the connection or create a connection object with the database using the connect() function of the sqlite3 module."
},
{
"code": null,
"e": 856,
"s": 776,
"text": "Create a Cursor object by calling the cursor() method of the Connection object."
},
{
"code": null,
"e": 947,
"s": 856,
"text": "Form table using the CREATE TABLE statement with the execute() method of the Cursor class."
},
{
"code": null,
"e": 963,
"s": 947,
"text": "Implementation:"
},
{
"code": null,
"e": 971,
"s": 963,
"text": "Python3"
},
{
"code": "import sqlite3 # Connecting to sqlite# connection objectconnection_obj = sqlite3.connect('geek.db') # cursor objectcursor_obj = connection_obj.cursor() # Drop the GEEK table if already exists.cursor_obj.execute(\"DROP TABLE IF EXISTS GEEK\") # Creating tabletable = \"\"\" CREATE TABLE GEEK ( Email VARCHAR(255) NOT NULL, First_Name CHAR(25) NOT NULL, Last_Name CHAR(25), Score INT ); \"\"\" cursor_obj.execute(table) print(\"Table is Ready\") # Close the connectionconnection_obj.close()",
"e": 1501,
"s": 971,
"text": null
},
{
"code": null,
"e": 1509,
"s": 1501,
"text": "Output:"
},
{
"code": null,
"e": 1518,
"s": 1509,
"text": "rkbhola5"
},
{
"code": null,
"e": 1525,
"s": 1518,
"text": "Picked"
},
{
"code": null,
"e": 1539,
"s": 1525,
"text": "Python-SQLite"
},
{
"code": null,
"e": 1546,
"s": 1539,
"text": "Python"
}
] |
Python – Odd elements indices | 19 Feb, 2020
Sometimes, while working with Python lists, we can have a problem in which we wish to find Odd elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss certain way to find indices of Odd elements.
Method #1 : Using loopThis is brute force method in which this task can be performed. In this, we check for odd element in list and append its index accordingly.
# Python3 code to demonstrate working of # Odd elements indices# using loop # initialize list test_list = [5, 6, 10, 4, 7, 1, 19] # printing original list print("The original list is : " + str(test_list)) # Odd elements indices# using loop res = [] for idx, ele in enumerate(test_list): if ele % 2 != 0: res.append(idx) # printing result print("Indices list Odd elements is : " + str(res))
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Odd elements is : [0, 4, 5, 6]
Method #2 : Using list comprehensionThis is the shorthand by which this task can be performed. This method works in similar way as the above method. The difference is that it’s a one liner.
# Python3 code to demonstrate working of # Odd elements indices# using list comprehension # initialize list test_list = [5, 6, 10, 4, 7, 1, 19] # printing original list print("The original list is : " + str(test_list)) # Odd elements indices# using list comprehension res = [idx for idx, ele in enumerate(test_list) if ele % 2 != 0] # printing result print("Indices list Odd elements is : " + str(res))
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Odd elements is : [0, 4, 5, 6]
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 348,
"s": 28,
"text": "Sometimes, while working with Python lists, we can have a problem in which we wish to find Odd elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss certain way to find indices of Odd elements."
},
{
"code": null,
"e": 510,
"s": 348,
"text": "Method #1 : Using loopThis is brute force method in which this task can be performed. In this, we check for odd element in list and append its index accordingly."
},
{
"code": "# Python3 code to demonstrate working of # Odd elements indices# using loop # initialize list test_list = [5, 6, 10, 4, 7, 1, 19] # printing original list print(\"The original list is : \" + str(test_list)) # Odd elements indices# using loop res = [] for idx, ele in enumerate(test_list): if ele % 2 != 0: res.append(idx) # printing result print(\"Indices list Odd elements is : \" + str(res)) ",
"e": 929,
"s": 510,
"text": null
},
{
"code": null,
"e": 1021,
"s": 929,
"text": "The original list is : [5, 6, 10, 4, 7, 1, 19]\nIndices list Odd elements is : [0, 4, 5, 6]\n"
},
{
"code": null,
"e": 1213,
"s": 1023,
"text": "Method #2 : Using list comprehensionThis is the shorthand by which this task can be performed. This method works in similar way as the above method. The difference is that it’s a one liner."
},
{
"code": "# Python3 code to demonstrate working of # Odd elements indices# using list comprehension # initialize list test_list = [5, 6, 10, 4, 7, 1, 19] # printing original list print(\"The original list is : \" + str(test_list)) # Odd elements indices# using list comprehension res = [idx for idx, ele in enumerate(test_list) if ele % 2 != 0] # printing result print(\"Indices list Odd elements is : \" + str(res)) ",
"e": 1633,
"s": 1213,
"text": null
},
{
"code": null,
"e": 1725,
"s": 1633,
"text": "The original list is : [5, 6, 10, 4, 7, 1, 19]\nIndices list Odd elements is : [0, 4, 5, 6]\n"
},
{
"code": null,
"e": 1746,
"s": 1725,
"text": "Python list-programs"
},
{
"code": null,
"e": 1753,
"s": 1746,
"text": "Python"
},
{
"code": null,
"e": 1769,
"s": 1753,
"text": "Python Programs"
},
{
"code": null,
"e": 1867,
"s": 1769,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1899,
"s": 1867,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1926,
"s": 1899,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1957,
"s": 1926,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1980,
"s": 1957,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2001,
"s": 1980,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2023,
"s": 2001,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2062,
"s": 2023,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2100,
"s": 2062,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2149,
"s": 2100,
"text": "Python | Convert string dictionary to dictionary"
}
] |
How to redirect to generated URL with ExpressJS? | 08 Apr, 2021
In this article I’m showing you how to redirect users using ExpressJS. First of all, when you want to redirect the user? Here are some real scenario.
Example, when user successfully login you can redirect him to the dashboard. Another instance, when user request for reset password, generally we generate an URL with user’s old password’s hash and send to user’s email. Here, I’m showing you How redirect user to dashboard after successfully login.
Overview:
Client: Make a GET request on URL ‘/’ for login page.Server: Render login pageClient: Next, user fill the form data and make a POST request on URL ‘/login’.Server: If user data matched then redirect to ‘/dashboaard/[ USER EMAIL ]’.Client: User make GET request on ‘/dashboaard/[ USER EMAIL ]’.Server: Render dashboard page.
Project Structure: Final project directory structure will look like this.
Project
|
|-> node_modules
|-> views
|-> login.ejs
|-> dashboard.ejs
|-> package.json
|-> package-lock.json
|-> server.js
Step 1: Create empty npm project folder and name it Project.
mkdir Project
cd Project
npm init -y
Step 2: Install require dependency.
Require dependency:
ExpressJSEJSbody-parser
ExpressJS
EJS
body-parser
npm i express ejs body-parser
Step 3: Client files, the default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make two files named “login.ejs” and “dashboard.ejs” .
login.js is responsible for user login request and if login success user will redirect to dashboard.ejs.
login.ejs
<!DOCTYPE html><html><head> <title></title> <style type="text/css"> body{ margin: 0% auto; } h1{ color: green; } input{ margin: 10px; display: block; padding: 5px 10px; } button{ margin: 10px; display: block; padding: 5px 10px; cursor: pointer; background-color: green; border: none; color: white; font-weight: bold; } form{ margin: 10% auto; padding: 20px; width: 20%; border: 1px solid green; } </style></head><body> <form> <center><h1>GeeksForGeeks</h1></center> <label>Email</label> <input type="email" id="userEmail"> <label>Password</label> <input type="password" id="userPassword"> <button onClick = "login(event)"> Login </button> </form> <script> const login = e =>{ e.preventDefault(); const email = document.getElementById('userEmail').value; const password = document.getElementById('userPassword').value; const option = { headers:{ "Content-Type": "application/json" }, method: "POST", body: JSON.stringify({ email: email, password: password }), redirect: "follow" } // fetching data fetch(`<%= url %>`, option) .then(res => res.redirected && ( location.href = res.url )) .catch(err => alert('Something happen wrong!')); } </script></body></html>
dashboard.ejs
<!DOCTYPE html><html><head> <title>Dashboard</title></head><body> <h1>Welcome <%= email %></h1></body></html>
Step 4: Create a file name server.js on your root folder. This file is has some middleware and it response on user request. Generally user login information is fetched from database but for our case it is fair to fetch it from a damy database.
Here, login handler route is redirect to ‘/dashboaard/[ USER EMAIL ]’ if user data matched else response with HTTP Client Error Code 401.
server.js
const express = require('express');const path = require('path'); const bodyParser = require('body-parser'); const ejs = require('ejs'); const app = express();const PORT = 3000; app.set('view engine', 'ejs');app.use(bodyParser.json()); //login page routeapp.get('/', (req,res)=>{ res.render(path.join(__dirname, 'views/login.ejs'), {url: '/login'});}) // login handler routeapp.post('/login', (req,res)=>{ const {email, password} = req.body; findUser(email, password) ? // if user is registered // generate a dynamic url // redirect to user res.redirect(301, `/dashboard/${email}`) : res.status(401).end(); }); // dashboard routeapp.get('/dashboard/:email', (req, res)=>{ const {email} = req.params; res.render(path.join(__dirname, 'views/dashboard.ejs'), {email: email})}); // damy user dbconst users = [ { name: "Raktim Banerjee", email: "[email protected]", password: "Raktim" }, { name: "Arpita Banerjee", email: "[email protected]", password :"Arpita" }]; // find user const findUser = (email, password)=> users.some(user => user.email === email && user.password === password ) // Start the serverapp.listen(PORT, err =>{ err ? console.log("Error in server setup") : console.log("Server listening on Port", PORT)});
Step 5: Start server.
node server.js
Output:
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Windows
JWT Authentication with Node.js
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 178,
"s": 28,
"text": "In this article I’m showing you how to redirect users using ExpressJS. First of all, when you want to redirect the user? Here are some real scenario."
},
{
"code": null,
"e": 477,
"s": 178,
"text": "Example, when user successfully login you can redirect him to the dashboard. Another instance, when user request for reset password, generally we generate an URL with user’s old password’s hash and send to user’s email. Here, I’m showing you How redirect user to dashboard after successfully login."
},
{
"code": null,
"e": 487,
"s": 477,
"text": "Overview:"
},
{
"code": null,
"e": 812,
"s": 487,
"text": "Client: Make a GET request on URL ‘/’ for login page.Server: Render login pageClient: Next, user fill the form data and make a POST request on URL ‘/login’.Server: If user data matched then redirect to ‘/dashboaard/[ USER EMAIL ]’.Client: User make GET request on ‘/dashboaard/[ USER EMAIL ]’.Server: Render dashboard page."
},
{
"code": null,
"e": 886,
"s": 812,
"text": "Project Structure: Final project directory structure will look like this."
},
{
"code": null,
"e": 1012,
"s": 886,
"text": "Project\n|\n|-> node_modules\n|-> views\n |-> login.ejs\n |-> dashboard.ejs\n|-> package.json\n|-> package-lock.json\n|-> server.js"
},
{
"code": null,
"e": 1073,
"s": 1012,
"text": "Step 1: Create empty npm project folder and name it Project."
},
{
"code": null,
"e": 1111,
"s": 1073,
"text": "mkdir Project\ncd Project \nnpm init -y"
},
{
"code": null,
"e": 1147,
"s": 1111,
"text": "Step 2: Install require dependency."
},
{
"code": null,
"e": 1167,
"s": 1147,
"text": "Require dependency:"
},
{
"code": null,
"e": 1191,
"s": 1167,
"text": "ExpressJSEJSbody-parser"
},
{
"code": null,
"e": 1201,
"s": 1191,
"text": "ExpressJS"
},
{
"code": null,
"e": 1205,
"s": 1201,
"text": "EJS"
},
{
"code": null,
"e": 1217,
"s": 1205,
"text": "body-parser"
},
{
"code": null,
"e": 1247,
"s": 1217,
"text": "npm i express ejs body-parser"
},
{
"code": null,
"e": 1491,
"s": 1247,
"text": "Step 3: Client files, the default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make two files named “login.ejs” and “dashboard.ejs” ."
},
{
"code": null,
"e": 1596,
"s": 1491,
"text": "login.js is responsible for user login request and if login success user will redirect to dashboard.ejs."
},
{
"code": null,
"e": 1606,
"s": 1596,
"text": "login.ejs"
},
{
"code": "<!DOCTYPE html><html><head> <title></title> <style type=\"text/css\"> body{ margin: 0% auto; } h1{ color: green; } input{ margin: 10px; display: block; padding: 5px 10px; } button{ margin: 10px; display: block; padding: 5px 10px; cursor: pointer; background-color: green; border: none; color: white; font-weight: bold; } form{ margin: 10% auto; padding: 20px; width: 20%; border: 1px solid green; } </style></head><body> <form> <center><h1>GeeksForGeeks</h1></center> <label>Email</label> <input type=\"email\" id=\"userEmail\"> <label>Password</label> <input type=\"password\" id=\"userPassword\"> <button onClick = \"login(event)\"> Login </button> </form> <script> const login = e =>{ e.preventDefault(); const email = document.getElementById('userEmail').value; const password = document.getElementById('userPassword').value; const option = { headers:{ \"Content-Type\": \"application/json\" }, method: \"POST\", body: JSON.stringify({ email: email, password: password }), redirect: \"follow\" } // fetching data fetch(`<%= url %>`, option) .then(res => res.redirected && ( location.href = res.url )) .catch(err => alert('Something happen wrong!')); } </script></body></html>",
"e": 3396,
"s": 1606,
"text": null
},
{
"code": null,
"e": 3410,
"s": 3396,
"text": "dashboard.ejs"
},
{
"code": "<!DOCTYPE html><html><head> <title>Dashboard</title></head><body> <h1>Welcome <%= email %></h1></body></html>",
"e": 3526,
"s": 3410,
"text": null
},
{
"code": null,
"e": 3771,
"s": 3526,
"text": "Step 4: Create a file name server.js on your root folder. This file is has some middleware and it response on user request. Generally user login information is fetched from database but for our case it is fair to fetch it from a damy database. "
},
{
"code": null,
"e": 3912,
"s": 3771,
"text": "Here, login handler route is redirect to ‘/dashboaard/[ USER EMAIL ]’ if user data matched else response with HTTP Client Error Code 401. "
},
{
"code": null,
"e": 3922,
"s": 3912,
"text": "server.js"
},
{
"code": "const express = require('express');const path = require('path'); const bodyParser = require('body-parser'); const ejs = require('ejs'); const app = express();const PORT = 3000; app.set('view engine', 'ejs');app.use(bodyParser.json()); //login page routeapp.get('/', (req,res)=>{ res.render(path.join(__dirname, 'views/login.ejs'), {url: '/login'});}) // login handler routeapp.post('/login', (req,res)=>{ const {email, password} = req.body; findUser(email, password) ? // if user is registered // generate a dynamic url // redirect to user res.redirect(301, `/dashboard/${email}`) : res.status(401).end(); }); // dashboard routeapp.get('/dashboard/:email', (req, res)=>{ const {email} = req.params; res.render(path.join(__dirname, 'views/dashboard.ejs'), {email: email})}); // damy user dbconst users = [ { name: \"Raktim Banerjee\", email: \"[email protected]\", password: \"Raktim\" }, { name: \"Arpita Banerjee\", email: \"[email protected]\", password :\"Arpita\" }]; // find user const findUser = (email, password)=> users.some(user => user.email === email && user.password === password ) // Start the serverapp.listen(PORT, err =>{ err ? console.log(\"Error in server setup\") : console.log(\"Server listening on Port\", PORT)});",
"e": 5278,
"s": 3922,
"text": null
},
{
"code": null,
"e": 5300,
"s": 5278,
"text": "Step 5: Start server."
},
{
"code": null,
"e": 5315,
"s": 5300,
"text": "node server.js"
},
{
"code": null,
"e": 5323,
"s": 5315,
"text": "Output:"
},
{
"code": null,
"e": 5334,
"s": 5323,
"text": "Express.js"
},
{
"code": null,
"e": 5351,
"s": 5334,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 5358,
"s": 5351,
"text": "Picked"
},
{
"code": null,
"e": 5366,
"s": 5358,
"text": "Node.js"
},
{
"code": null,
"e": 5383,
"s": 5366,
"text": "Web Technologies"
},
{
"code": null,
"e": 5481,
"s": 5383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5516,
"s": 5481,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 5548,
"s": 5516,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 5618,
"s": 5548,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 5645,
"s": 5618,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 5670,
"s": 5645,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 5732,
"s": 5670,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5793,
"s": 5732,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5843,
"s": 5793,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5886,
"s": 5843,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Islands in a graph using BFS | 06 Jul, 2021
Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 5 islands
Example:
Input : mat[][] = {{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}
Output : 5
What is an island? A group of connected 1s forms an island. For example, the below matrix contains 5 islands
{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}
This is a variation of the standard problem: connected component. A connected component of an undirected graph is a subgraph in which every two vertices are connected to each other by a path(s), and which is connected to no other vertices outside the subgraph.
For example, the graph shown below has three connected components.
A graph where all vertices are connected with each other has exactly one connected component, consisting of the whole graph. Such graph with only one connected component is called as Strongly Connected Graph.We have discussed a DFS solution for islands is already discussed. This problem can also solved by applying BFS() on each component. In each BFS() call, a component or a sub-graph is visited. We will call BFS on the next un-visited component. The number of calls to BFS() gives the number of connected components. BFS can also be used.
A cell in 2D matrix can be connected to 8 neighbours. So, unlike standard BFS(), where we process all adjacent vertices, we process 8 neighbours only. We keep track of the visited 1s so that they are not visited again.
C++
Java
Python3
C#
Javascript
// A BFS based solution to count number of// islands in a graph.#include <bits/stdc++.h>using namespace std; // R x C matrix#define R 5#define C 5 // A function to check if a given cell// (u, v) can be included in DFSbool isSafe(int mat[R][C], int i, int j, bool vis[R][C]){ return (i >= 0) && (i < R) && (j >= 0) && (j < C) && (mat[i][j] && !vis[i][j]);} void BFS(int mat[R][C], bool vis[R][C], int si, int sj){ // These arrays are used to get row and // column numbers of 8 neighbours of // a given cell int row[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; int col[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Simple BFS first step, we enqueue // source and mark it as visited queue<pair<int, int> > q; q.push(make_pair(si, sj)); vis[si][sj] = true; // Next step of BFS. We take out // items one by one from queue and // enqueue their univisited adjacent while (!q.empty()) { int i = q.front().first; int j = q.front().second; q.pop(); // Go through all 8 adjacent for (int k = 0; k < 8; k++) { if (isSafe(mat, i + row[k], j + col[k], vis)) { vis[i + row[k]][j + col[k]] = true; q.push(make_pair(i + row[k], j + col[k])); } } }} // This function returns number islands (connected// components) in a graph. It simply works as// BFS for disconnected graph and returns count// of BFS calls.int countIslands(int mat[R][C]){ // Mark all cells as not visited bool vis[R][C]; memset(vis, 0, sizeof(vis)); // Call BFS for every unvisited vertex // Whenever we see an univisted vertex, // we increment res (number of islands) // also. int res = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (mat[i][j] && !vis[i][j]) { BFS(mat, vis, i, j); res++; } } } return res;} // main functionint main(){ int mat[][C] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << countIslands(mat); return 0;}
// A BFS based solution to count number of// islands in a graph.import java.util.*; class GFG{ // R x C matrixstatic final int R = 5;static final int C = 5 ;static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // A function to check if a given cell// (u, v) can be included in DFSstatic boolean isSafe(int mat[][], int i, int j, boolean vis[][]){ return (i >= 0) && (i < R) && (j >= 0) && (j < C) && (mat[i][j]==1 && !vis[i][j]);} static void BFS(int mat[][], boolean vis[][], int si, int sj){ // These arrays are used to get row and // column numbers of 8 neighbours of // a given cell int row[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; int col[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Simple BFS first step, we enqueue // source and mark it as visited Queue<pair> q = new LinkedList<pair>(); q.add(new pair(si, sj)); vis[si][sj] = true; // Next step of BFS. We take out // items one by one from queue and // enqueue their univisited adjacent while (!q.isEmpty()) { int i = q.peek().first; int j = q.peek().second; q.remove(); // Go through all 8 adjacent for (int k = 0; k < 8; k++) { if (isSafe(mat, i + row[k], j + col[k], vis)) { vis[i + row[k]][j + col[k]] = true; q.add(new pair(i + row[k], j + col[k])); } } }} // This function returns number islands (connected// components) in a graph. It simply works as// BFS for disconnected graph and returns count// of BFS calls.static int countIslands(int mat[][]){ // Mark all cells as not visited boolean [][]vis = new boolean[R][C]; // Call BFS for every unvisited vertex // Whenever we see an univisted vertex, // we increment res (number of islands) // also. int res = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (mat[i][j]==1 && !vis[i][j]) { BFS(mat, vis, i, j); res++; } } } return res;} // Driver codepublic static void main(String[] args){ int mat[][] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; System.out.print(countIslands(mat));}} // This code is contributed by PrinciRaj1992
# A BFS based solution to count number of# islands in a graph.from collections import deque # A function to check if a given cell# (u, v) can be included in DFSdef isSafe(mat, i, j, vis): return ((i >= 0) and (i < 5) and (j >= 0) and (j < 5) and (mat[i][j] and (not vis[i][j]))) def BFS(mat, vis, si, sj): # These arrays are used to get row and # column numbers of 8 neighbours of # a given cell row = [-1, -1, -1, 0, 0, 1, 1, 1] col = [-1, 0, 1, -1, 1, -1, 0, 1] # Simple BFS first step, we enqueue # source and mark it as visited q = deque() q.append([si, sj]) vis[si][sj] = True # Next step of BFS. We take out # items one by one from queue and # enqueue their univisited adjacent while (len(q) > 0): temp = q.popleft() i = temp[0] j = temp[1] # Go through all 8 adjacent for k in range(8): if (isSafe(mat, i + row[k], j + col[k], vis)): vis[i + row[k]][j + col[k]] = True q.append([i + row[k], j + col[k]]) # This function returns number islands (connected# components) in a graph. It simply works as# BFS for disconnected graph and returns count# of BFS calls.def countIslands(mat): # Mark all cells as not visited vis = [[False for i in range(5)] for i in range(5)] # memset(vis, 0, sizeof(vis)); # 5all BFS for every unvisited vertex # Whenever we see an univisted vertex, # we increment res (number of islands) # also. res = 0 for i in range(5): for j in range(5): if (mat[i][j] and not vis[i][j]): BFS(mat, vis, i, j) res += 1 return res # Driver codeif __name__ == '__main__': mat = [ [ 1, 1, 0, 0, 0 ], [ 0, 1, 0, 0, 1 ], [ 1, 0, 0, 1, 1 ], [ 0, 0, 0, 0, 0 ], [ 1, 0, 1, 0, 1 ]] print (countIslands(mat)) # This code is contributed by mohit kumar 29
// A BFS based solution to count number of// islands in a graph.using System;using System.Collections.Generic; class GFG{ // R x C matrixstatic readonly int R = 5;static readonly int C = 5 ;class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // A function to check if a given cell// (u, v) can be included in DFSstatic bool isSafe(int [,]mat, int i, int j, bool [,]vis){ return (i >= 0) && (i < R) && (j >= 0) && (j < C) && (mat[i, j]==1 && !vis[i, j]);} static void BFS(int [,]mat, bool [,]vis, int si, int sj){ // These arrays are used to get row and // column numbers of 8 neighbours of // a given cell int []row = { -1, -1, -1, 0, 0, 1, 1, 1 }; int []col = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Simple BFS first step, we enqueue // source and mark it as visited List<pair> q = new List<pair>(); q.Add(new pair(si, sj)); vis[si, sj] = true; // Next step of BFS. We take out // items one by one from queue and // enqueue their univisited adjacent while (q.Count != 0) { int i = q[0].first; int j = q[0].second; q.RemoveAt(0); // Go through all 8 adjacent for (int k = 0; k < 8; k++) { if (isSafe(mat, i + row[k], j + col[k], vis)) { vis[i + row[k], j + col[k]] = true; q.Add(new pair(i + row[k], j + col[k])); } } }} // This function returns number islands (connected// components) in a graph. It simply works as// BFS for disconnected graph and returns count// of BFS calls.static int countIslands(int [,]mat){ // Mark all cells as not visited bool [,]vis = new bool[R, C]; // Call BFS for every unvisited vertex // Whenever we see an univisted vertex, // we increment res (number of islands) // also. int res = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (mat[i, j]==1 && !vis[i, j]) { BFS(mat, vis, i, j); res++; } } } return res;} // Driver codepublic static void Main(String[] args){ int [,]mat = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; Console.Write(countIslands(mat));}} // This code is contributed by 29AjayKumar
<script>// A BFS based solution to count number of// islands in a graph. // R x C matrixlet R = 5;let C = 5 ; // A function to check if a given cell// (u, v) can be included in DFSfunction isSafe(mat,i,j,vis){ return (i >= 0) && (i < R) && (j >= 0) && (j < C) && (mat[i][j] == 1 && !vis[i][j]);} function BFS(mat, vis, si, sj){ // These arrays are used to get row and // column numbers of 8 neighbours of // a given cell let row = [ -1, -1, -1, 0, 0, 1, 1, 1 ]; let col = [ -1, 0, 1, -1, 1, -1, 0, 1 ]; // Simple BFS first step, we enqueue // source and mark it as visited let q = []; q.push([si, sj]); vis[si][sj] = true; // Next step of BFS. We take out // items one by one from queue and // enqueue their univisited adjacent while (q.length != 0) { let i = q[0][0]; let j = q[0][1]; q.shift(); // Go through all 8 adjacent for (let k = 0; k < 8; k++) { if (isSafe(mat, i + row[k], j + col[k], vis)) { vis[i + row[k]][j + col[k]] = true; q.push([i + row[k], j + col[k]]); } } }} // This function returns number islands (connected// components) in a graph. It simply works as// BFS for disconnected graph and returns count// of BFS calls.function countIslands(mat){ // Mark all cells as not visited let vis = new Array(R); for(let i = 0; i < R; i++) { vis[i] = new Array(C); for(let j = 0; j < C; j++) { vis[i][j] = false; } } // Call BFS for every unvisited vertex // Whenever we see an univisted vertex, // we increment res (number of islands) // also. let res = 0; for (let i = 0; i < R; i++) { for (let j = 0; j < C; j++) { if (mat[i][j] == 1 && !vis[i][j]) { BFS(mat, vis, i, j); res++; } } } return res;} // Driver codelet mat = [[ 1, 1, 0, 0, 0 ], [ 0, 1, 0, 0, 1 ], [ 1, 0, 0, 1, 1 ], [ 0, 0, 0, 0, 0 ], [ 1, 0, 1, 0, 1 ] ]; document.write(countIslands(mat)); // This code is contributed by patel2127.</script>
5
Time Complexity : O(ROW * COL) where ROW is number of ROWS and COL is number of COLUMNS in the matrix.
princiraj1992
29AjayKumar
mohit kumar 29
patel2127
pk1409
BFS
Graph
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in a directed graph
Topological Sorting
Detect Cycle in a Directed Graph
Find if there is a path between two vertices in an undirected graph
Introduction to Data Structures
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
What is Data Structure: Types, Classifications and Applications
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Detect cycle in an undirected graph
Minimum number of swaps required to sort an array | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 199,
"s": 54,
"text": "Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 5 islands"
},
{
"code": null,
"e": 210,
"s": 199,
"text": "Example: "
},
{
"code": null,
"e": 401,
"s": 210,
"text": "Input : mat[][] = {{1, 1, 0, 0, 0},\n {0, 1, 0, 0, 1},\n {1, 0, 0, 1, 1},\n {0, 0, 0, 0, 0},\n {1, 0, 1, 0, 1} \nOutput : 5"
},
{
"code": null,
"e": 511,
"s": 401,
"text": "What is an island? A group of connected 1s forms an island. For example, the below matrix contains 5 islands "
},
{
"code": null,
"e": 716,
"s": 511,
"text": " {1, 1, 0, 0, 0},\n {0, 1, 0, 0, 1},\n {1, 0, 0, 1, 1},\n {0, 0, 0, 0, 0},\n {1, 0, 1, 0, 1}"
},
{
"code": null,
"e": 978,
"s": 716,
"text": "This is a variation of the standard problem: connected component. A connected component of an undirected graph is a subgraph in which every two vertices are connected to each other by a path(s), and which is connected to no other vertices outside the subgraph. "
},
{
"code": null,
"e": 1047,
"s": 978,
"text": "For example, the graph shown below has three connected components. "
},
{
"code": null,
"e": 1593,
"s": 1049,
"text": "A graph where all vertices are connected with each other has exactly one connected component, consisting of the whole graph. Such graph with only one connected component is called as Strongly Connected Graph.We have discussed a DFS solution for islands is already discussed. This problem can also solved by applying BFS() on each component. In each BFS() call, a component or a sub-graph is visited. We will call BFS on the next un-visited component. The number of calls to BFS() gives the number of connected components. BFS can also be used."
},
{
"code": null,
"e": 1813,
"s": 1593,
"text": "A cell in 2D matrix can be connected to 8 neighbours. So, unlike standard BFS(), where we process all adjacent vertices, we process 8 neighbours only. We keep track of the visited 1s so that they are not visited again. "
},
{
"code": null,
"e": 1817,
"s": 1813,
"text": "C++"
},
{
"code": null,
"e": 1822,
"s": 1817,
"text": "Java"
},
{
"code": null,
"e": 1830,
"s": 1822,
"text": "Python3"
},
{
"code": null,
"e": 1833,
"s": 1830,
"text": "C#"
},
{
"code": null,
"e": 1844,
"s": 1833,
"text": "Javascript"
},
{
"code": "// A BFS based solution to count number of// islands in a graph.#include <bits/stdc++.h>using namespace std; // R x C matrix#define R 5#define C 5 // A function to check if a given cell// (u, v) can be included in DFSbool isSafe(int mat[R][C], int i, int j, bool vis[R][C]){ return (i >= 0) && (i < R) && (j >= 0) && (j < C) && (mat[i][j] && !vis[i][j]);} void BFS(int mat[R][C], bool vis[R][C], int si, int sj){ // These arrays are used to get row and // column numbers of 8 neighbours of // a given cell int row[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; int col[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Simple BFS first step, we enqueue // source and mark it as visited queue<pair<int, int> > q; q.push(make_pair(si, sj)); vis[si][sj] = true; // Next step of BFS. We take out // items one by one from queue and // enqueue their univisited adjacent while (!q.empty()) { int i = q.front().first; int j = q.front().second; q.pop(); // Go through all 8 adjacent for (int k = 0; k < 8; k++) { if (isSafe(mat, i + row[k], j + col[k], vis)) { vis[i + row[k]][j + col[k]] = true; q.push(make_pair(i + row[k], j + col[k])); } } }} // This function returns number islands (connected// components) in a graph. It simply works as// BFS for disconnected graph and returns count// of BFS calls.int countIslands(int mat[R][C]){ // Mark all cells as not visited bool vis[R][C]; memset(vis, 0, sizeof(vis)); // Call BFS for every unvisited vertex // Whenever we see an univisted vertex, // we increment res (number of islands) // also. int res = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (mat[i][j] && !vis[i][j]) { BFS(mat, vis, i, j); res++; } } } return res;} // main functionint main(){ int mat[][C] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << countIslands(mat); return 0;}",
"e": 4080,
"s": 1844,
"text": null
},
{
"code": "// A BFS based solution to count number of// islands in a graph.import java.util.*; class GFG{ // R x C matrixstatic final int R = 5;static final int C = 5 ;static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // A function to check if a given cell// (u, v) can be included in DFSstatic boolean isSafe(int mat[][], int i, int j, boolean vis[][]){ return (i >= 0) && (i < R) && (j >= 0) && (j < C) && (mat[i][j]==1 && !vis[i][j]);} static void BFS(int mat[][], boolean vis[][], int si, int sj){ // These arrays are used to get row and // column numbers of 8 neighbours of // a given cell int row[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; int col[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Simple BFS first step, we enqueue // source and mark it as visited Queue<pair> q = new LinkedList<pair>(); q.add(new pair(si, sj)); vis[si][sj] = true; // Next step of BFS. We take out // items one by one from queue and // enqueue their univisited adjacent while (!q.isEmpty()) { int i = q.peek().first; int j = q.peek().second; q.remove(); // Go through all 8 adjacent for (int k = 0; k < 8; k++) { if (isSafe(mat, i + row[k], j + col[k], vis)) { vis[i + row[k]][j + col[k]] = true; q.add(new pair(i + row[k], j + col[k])); } } }} // This function returns number islands (connected// components) in a graph. It simply works as// BFS for disconnected graph and returns count// of BFS calls.static int countIslands(int mat[][]){ // Mark all cells as not visited boolean [][]vis = new boolean[R][C]; // Call BFS for every unvisited vertex // Whenever we see an univisted vertex, // we increment res (number of islands) // also. int res = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (mat[i][j]==1 && !vis[i][j]) { BFS(mat, vis, i, j); res++; } } } return res;} // Driver codepublic static void main(String[] args){ int mat[][] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; System.out.print(countIslands(mat));}} // This code is contributed by PrinciRaj1992",
"e": 6619,
"s": 4080,
"text": null
},
{
"code": "# A BFS based solution to count number of# islands in a graph.from collections import deque # A function to check if a given cell# (u, v) can be included in DFSdef isSafe(mat, i, j, vis): return ((i >= 0) and (i < 5) and (j >= 0) and (j < 5) and (mat[i][j] and (not vis[i][j]))) def BFS(mat, vis, si, sj): # These arrays are used to get row and # column numbers of 8 neighbours of # a given cell row = [-1, -1, -1, 0, 0, 1, 1, 1] col = [-1, 0, 1, -1, 1, -1, 0, 1] # Simple BFS first step, we enqueue # source and mark it as visited q = deque() q.append([si, sj]) vis[si][sj] = True # Next step of BFS. We take out # items one by one from queue and # enqueue their univisited adjacent while (len(q) > 0): temp = q.popleft() i = temp[0] j = temp[1] # Go through all 8 adjacent for k in range(8): if (isSafe(mat, i + row[k], j + col[k], vis)): vis[i + row[k]][j + col[k]] = True q.append([i + row[k], j + col[k]]) # This function returns number islands (connected# components) in a graph. It simply works as# BFS for disconnected graph and returns count# of BFS calls.def countIslands(mat): # Mark all cells as not visited vis = [[False for i in range(5)] for i in range(5)] # memset(vis, 0, sizeof(vis)); # 5all BFS for every unvisited vertex # Whenever we see an univisted vertex, # we increment res (number of islands) # also. res = 0 for i in range(5): for j in range(5): if (mat[i][j] and not vis[i][j]): BFS(mat, vis, i, j) res += 1 return res # Driver codeif __name__ == '__main__': mat = [ [ 1, 1, 0, 0, 0 ], [ 0, 1, 0, 0, 1 ], [ 1, 0, 0, 1, 1 ], [ 0, 0, 0, 0, 0 ], [ 1, 0, 1, 0, 1 ]] print (countIslands(mat)) # This code is contributed by mohit kumar 29",
"e": 8596,
"s": 6619,
"text": null
},
{
"code": "// A BFS based solution to count number of// islands in a graph.using System;using System.Collections.Generic; class GFG{ // R x C matrixstatic readonly int R = 5;static readonly int C = 5 ;class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // A function to check if a given cell// (u, v) can be included in DFSstatic bool isSafe(int [,]mat, int i, int j, bool [,]vis){ return (i >= 0) && (i < R) && (j >= 0) && (j < C) && (mat[i, j]==1 && !vis[i, j]);} static void BFS(int [,]mat, bool [,]vis, int si, int sj){ // These arrays are used to get row and // column numbers of 8 neighbours of // a given cell int []row = { -1, -1, -1, 0, 0, 1, 1, 1 }; int []col = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Simple BFS first step, we enqueue // source and mark it as visited List<pair> q = new List<pair>(); q.Add(new pair(si, sj)); vis[si, sj] = true; // Next step of BFS. We take out // items one by one from queue and // enqueue their univisited adjacent while (q.Count != 0) { int i = q[0].first; int j = q[0].second; q.RemoveAt(0); // Go through all 8 adjacent for (int k = 0; k < 8; k++) { if (isSafe(mat, i + row[k], j + col[k], vis)) { vis[i + row[k], j + col[k]] = true; q.Add(new pair(i + row[k], j + col[k])); } } }} // This function returns number islands (connected// components) in a graph. It simply works as// BFS for disconnected graph and returns count// of BFS calls.static int countIslands(int [,]mat){ // Mark all cells as not visited bool [,]vis = new bool[R, C]; // Call BFS for every unvisited vertex // Whenever we see an univisted vertex, // we increment res (number of islands) // also. int res = 0; for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (mat[i, j]==1 && !vis[i, j]) { BFS(mat, vis, i, j); res++; } } } return res;} // Driver codepublic static void Main(String[] args){ int [,]mat = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; Console.Write(countIslands(mat));}} // This code is contributed by 29AjayKumar",
"e": 11125,
"s": 8596,
"text": null
},
{
"code": "<script>// A BFS based solution to count number of// islands in a graph. // R x C matrixlet R = 5;let C = 5 ; // A function to check if a given cell// (u, v) can be included in DFSfunction isSafe(mat,i,j,vis){ return (i >= 0) && (i < R) && (j >= 0) && (j < C) && (mat[i][j] == 1 && !vis[i][j]);} function BFS(mat, vis, si, sj){ // These arrays are used to get row and // column numbers of 8 neighbours of // a given cell let row = [ -1, -1, -1, 0, 0, 1, 1, 1 ]; let col = [ -1, 0, 1, -1, 1, -1, 0, 1 ]; // Simple BFS first step, we enqueue // source and mark it as visited let q = []; q.push([si, sj]); vis[si][sj] = true; // Next step of BFS. We take out // items one by one from queue and // enqueue their univisited adjacent while (q.length != 0) { let i = q[0][0]; let j = q[0][1]; q.shift(); // Go through all 8 adjacent for (let k = 0; k < 8; k++) { if (isSafe(mat, i + row[k], j + col[k], vis)) { vis[i + row[k]][j + col[k]] = true; q.push([i + row[k], j + col[k]]); } } }} // This function returns number islands (connected// components) in a graph. It simply works as// BFS for disconnected graph and returns count// of BFS calls.function countIslands(mat){ // Mark all cells as not visited let vis = new Array(R); for(let i = 0; i < R; i++) { vis[i] = new Array(C); for(let j = 0; j < C; j++) { vis[i][j] = false; } } // Call BFS for every unvisited vertex // Whenever we see an univisted vertex, // we increment res (number of islands) // also. let res = 0; for (let i = 0; i < R; i++) { for (let j = 0; j < C; j++) { if (mat[i][j] == 1 && !vis[i][j]) { BFS(mat, vis, i, j); res++; } } } return res;} // Driver codelet mat = [[ 1, 1, 0, 0, 0 ], [ 0, 1, 0, 0, 1 ], [ 1, 0, 0, 1, 1 ], [ 0, 0, 0, 0, 0 ], [ 1, 0, 1, 0, 1 ] ]; document.write(countIslands(mat)); // This code is contributed by patel2127.</script>",
"e": 13417,
"s": 11125,
"text": null
},
{
"code": null,
"e": 13419,
"s": 13417,
"text": "5"
},
{
"code": null,
"e": 13525,
"s": 13421,
"text": "Time Complexity : O(ROW * COL) where ROW is number of ROWS and COL is number of COLUMNS in the matrix. "
},
{
"code": null,
"e": 13539,
"s": 13525,
"text": "princiraj1992"
},
{
"code": null,
"e": 13551,
"s": 13539,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13566,
"s": 13551,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 13576,
"s": 13566,
"text": "patel2127"
},
{
"code": null,
"e": 13583,
"s": 13576,
"text": "pk1409"
},
{
"code": null,
"e": 13587,
"s": 13583,
"text": "BFS"
},
{
"code": null,
"e": 13593,
"s": 13587,
"text": "Graph"
},
{
"code": null,
"e": 13599,
"s": 13593,
"text": "Graph"
},
{
"code": null,
"e": 13603,
"s": 13599,
"text": "BFS"
},
{
"code": null,
"e": 13701,
"s": 13603,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13766,
"s": 13701,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 13786,
"s": 13766,
"text": "Topological Sorting"
},
{
"code": null,
"e": 13819,
"s": 13786,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 13887,
"s": 13819,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 13919,
"s": 13887,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 13994,
"s": 13919,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 14058,
"s": 13994,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 14126,
"s": 14058,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 14162,
"s": 14126,
"text": "Detect cycle in an undirected graph"
}
] |
Can we define a method name same as class name in Java? | Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur. But this is not recommended as per coding standards in Java. Normally the constructor name and class name always the same in Java.
Live Demo
public class MethodNameTest {
private String str = "Welcome to TutorialsPoint";
public void MethodNameTest() { // Declared method name same as the class name
System.out.println("Both method name and class name are the same");
}
public static void main(String args[]) {
MethodNameTest test = new MethodNameTest();
System.out.println(test.str);
System.out.println(test.MethodNameTest());
}
}
In the above example, we can declare a method name (MethodNameTest) same as the class name (MethodNameTest), it will be compiled successfully without any errors.
Welcome to TutorialsPoint
Both method name and class name are the same | [
{
"code": null,
"e": 1324,
"s": 1062,
"text": "Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur. But this is not recommended as per coding standards in Java. Normally the constructor name and class name always the same in Java."
},
{
"code": null,
"e": 1334,
"s": 1324,
"text": "Live Demo"
},
{
"code": null,
"e": 1763,
"s": 1334,
"text": "public class MethodNameTest {\n private String str = \"Welcome to TutorialsPoint\";\n public void MethodNameTest() { // Declared method name same as the class name\n System.out.println(\"Both method name and class name are the same\");\n }\n public static void main(String args[]) {\n MethodNameTest test = new MethodNameTest();\n System.out.println(test.str);\n System.out.println(test.MethodNameTest());\n }\n}"
},
{
"code": null,
"e": 1925,
"s": 1763,
"text": "In the above example, we can declare a method name (MethodNameTest) same as the class name (MethodNameTest), it will be compiled successfully without any errors."
},
{
"code": null,
"e": 1996,
"s": 1925,
"text": "Welcome to TutorialsPoint\nBoth method name and class name are the same"
}
] |
Position of rightmost different bit - GeeksforGeeks | 01 Jul, 2021
Given two numbers m and n. Find the position of the rightmost different bit in the binary representation of numbers. It is guaranteed that such a bit exists.
Examples:
Input: m = 11, n = 9
Output: 2
(11)10 = (1011)2
(9)10 = (1001)2
It can be seen that 2nd bit from
the right is different
Input: m = 52, n = 4
Output: 5
(52)10 = (110100)2
(4)10 = (100)2, can also be written as
= (000100)2
It can be seen that 5th bit from
the right is different
Approach: Get the bitwise xor of m and n. Let it be xor_value = m ^ n. Now, find the position of rightmost set bit in xor_value.
Explanation: The bitwise xor operation produces a number that has set bits only at the positions where the bits of m and n differ. Thus, the position of the rightmost set bit in xor_value gives the position of the rightmost different bit.
Efficient way to find the rightmost set bit:
log2(n & -n) + 1 gives us the position of the rightmost set bit.
(-n) reverses all the bits from left to right till the last set bit
for example:
n = 16810
binary signed 2's complement of n = 00000000101010002
binary signed 2's complement of -n = 11111111010110002
∴ (n & -n) = 00000000000010002 = 8
now, log2(n & -n) = log2(8) = 3
log2(n & -n) + 1 = 4 (position of rightmost set bit)
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find the position// of rightmost different bit#include <bits/stdc++.h>using namespace std; // Function to find the position of// rightmost set bit in 'n'// returns 0 if there is no set bit.int getRightMostSetBit(int n){ // to handle edge case when n = 0. if (n == 0) return 0; return log2(n & -n) + 1;} // Function to find the position of// rightmost different bit in the// binary representations of 'm' and 'n'// returns 0 if there is no// rightmost different bit.int posOfRightMostDiffBit(int m, int n){ // position of rightmost different // bit return getRightMostSetBit(m ^ n);} // Driver programint main(){ int m = 52, n = 24; cout << "Position of rightmost different bit:" << posOfRightMostDiffBit(m, n)<<endl; return 0;}
// Java implementation to find the position// of rightmost different bit class GFG { // Function to find the position of // rightmost set bit in 'n' // return 0 if there is no set bit. static int getRightMostSetBit(int n) { if(n == 0) return 0; return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1; } // Function to find the position of // rightmost different bit in the // binary representations of 'm' and 'n' static int posOfRightMostDiffBit(int m, int n) { // position of rightmost different bit return getRightMostSetBit(m ^ n); } // Driver code public static void main(String arg[]) { int m = 52, n = 4; System.out.print("Position = " + posOfRightMostDiffBit(m, n)); }} // This code is contributed by Anant Agarwal.
# Python implementation# to find the position# of rightmost different bit import math # Function to find the position of# rightmost set bit in 'n'def getRightMostSetBit(n): if (n == 0): return 0 return math.log2(n & -n) + 1 # Function to find the position of# rightmost different bit in the# binary representations of 'm' and 'n'def posOfRightMostDiffBit(m, n): # position of rightmost different # bit return getRightMostSetBit(m ^ n) # Driver code m = 52n = 4print("position = ", int(posOfRightMostDiffBit(m, n))) # This code is contributed# by Anant Agarwal.
// C# implementation to find the position// of rightmost different bitusing System; class GFG { // Function to find the position of // rightmost set bit in 'n' static int getRightMostSetBit(int n) { if (n == 0) return 0; return (int)((Math.Log10(n & -n)) / Math.Log10(2)) + 1; } // Function to find the position of // rightmost different bit in the // binary representations of 'm' and 'n' static int posOfRightMostDiffBit(int m, int n) { // position of rightmost different bit return getRightMostSetBit(m ^ n); } // Driver code public static void Main() { int m = 52, n = 4; Console.Write("Position = " + posOfRightMostDiffBit(m, n)); }} // This code is contributed by Smitha.
<?php// PHP implementation to// find the position of// rightmost different bit // Function to find the position// of rightmost set bit in 'n'function getRightMostSetBit($n){ if ($n == 0) return 0; return log($n & -$n, (2)) + 1;} // Function to find the position of// rightmost different bit in the// binary representations of 'm'// and 'n'function posOfRightMostDiffBit($m, $n){ // position of rightmost // different bit return getRightMostSetBit($m ^ $n);} // Driver Code $m = 52; $n = 4; echo posOfRightMostDiffBit($m, $n); // This code is contributed by Ajit?>
<script>// JavaScript implementation to find the position// of rightmost different bit // Function to find the position of// rightmost set bit in 'n'// returns 0 if there is no set bit.function getRightMostSetBit(n){ // to handle edge case when n = 0. if (n == 0) return 0; return Math.log2(n & -n) + 1;} // Function to find the position of// rightmost different bit in the// binary representations of 'm' and 'n'// returns 0 if there is no// rightmost different bit.function posOfRightMostDiffBit(m, n){ // position of rightmost different // bit return getRightMostSetBit(m ^ n);} // Driver program let m = 52, n = 24; document.write("Position of rightmost different bit:" + posOfRightMostDiffBit(m, n) + "<br>"); // This code is contributed by Surbhi Tyagi.</script>
Position of rightmost different bit:3
Using ffs() function
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find the// position of rightmost different// bit in two number.#include <bits/stdc++.h>using namespace std; // function to find rightmost different// bit in two numbers.int posOfRightMostDiffBit(int m, int n){ return ffs(m ^ n);} // Driver codeint main(){ int m = 52, n = 4; cout <<"Position = " << posOfRightMostDiffBit(m, n); return 0;}
// Java implementation to find the// position of rightmost different// bit in two number.import java.util.*;class GFG{ // function to find rightmost// different bit in two numbers.static int posOfRightMostDiffBit(int m, int n){ return (int)Math.floor( Math.log10( Math.pow(m ^ n, 2)))+2;} // Driver codepublic static void main(String[] args){ int m = 52, n = 4; System.out.println("Position = " + posOfRightMostDiffBit(m, n));}} // This code is contributed by gauravrajput1
# Python3 implementation to find the# position of rightmost different# bit in two number.from math import floor, log10 # Function to find rightmost different# bit in two numbers.def posOfRightMostDiffBit(m, n): return floor(log10(pow(m ^ n, 2))) + 2 # Driver codeif __name__ == '__main__': m, n = 52, 4 print("Position = ", posOfRightMostDiffBit(m, n)) # This code is contributed by mohit kumar 29
// C# implementation to find the// position of rightmost different// bit in two number.using System;class GFG{ // function to find rightmost // different bit in two numbers. static int posOfRightMostDiffBit(int m, int n) { return (int)Math.Floor(Math.Log10( Math.Pow(m ^ n, 2))) + 2; } // Driver code public static void Main(String[] args) { int m = 52, n = 4; Console.Write("Position = " + posOfRightMostDiffBit(m, n)); }} // This code is contributed by shivanisinghss2110
<?php// PHP implementation to find the// position of rightmost different// bit in two number. // function to find rightmost// different bit in two numbers.function posOfRightMostDiffBit($m, $n){ $t = floor(log($m ^ $n, 2)); return $t;} // Driver code$m = 52;$n = 4;echo "Position = " , posOfRightMostDiffBit($m, $n); // This code is contributed by ajit?>
<script> // Javascript implementation to find the // position of rightmost different // bit in two number. // function to find rightmost // different bit in two numbers. function posOfRightMostDiffBit(m, n) { return parseInt(Math.floor (Math.log10(Math.pow(m ^ n, 2))), 10) + 2; } let m = 52, n = 4; document.write( "Position = " + posOfRightMostDiffBit(m, n) ); </script>
Position = 5
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mannuyou
jit_t
Smitha Dinesh Semwal
shreyashagrawal
abbccc123
GauravRajput1
mohit kumar 29
shivanisinghss2110
mank1083
divyeshrabadiya07
clintra
scisaif
sumitgumber28
surinderdawra388
binary-representation
BIT
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Binary representation of a given number
Program to find whether a given number is power of 2
Add two numbers without using arithmetic operators
Josephus problem | Set 1 (A O(n) Solution)
Find the element that appears once
Bits manipulation (Important tactics)
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C | [
{
"code": null,
"e": 24263,
"s": 24235,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 24422,
"s": 24263,
"text": "Given two numbers m and n. Find the position of the rightmost different bit in the binary representation of numbers. It is guaranteed that such a bit exists. "
},
{
"code": null,
"e": 24433,
"s": 24422,
"text": "Examples: "
},
{
"code": null,
"e": 24717,
"s": 24433,
"text": "Input: m = 11, n = 9\nOutput: 2\n(11)10 = (1011)2\n(9)10 = (1001)2\nIt can be seen that 2nd bit from\nthe right is different \n\nInput: m = 52, n = 4\nOutput: 5\n(52)10 = (110100)2\n(4)10 = (100)2, can also be written as\n = (000100)2\nIt can be seen that 5th bit from\nthe right is different"
},
{
"code": null,
"e": 24846,
"s": 24717,
"text": "Approach: Get the bitwise xor of m and n. Let it be xor_value = m ^ n. Now, find the position of rightmost set bit in xor_value."
},
{
"code": null,
"e": 25086,
"s": 24846,
"text": "Explanation: The bitwise xor operation produces a number that has set bits only at the positions where the bits of m and n differ. Thus, the position of the rightmost set bit in xor_value gives the position of the rightmost different bit. "
},
{
"code": null,
"e": 25518,
"s": 25086,
"text": "Efficient way to find the rightmost set bit: \nlog2(n & -n) + 1 gives us the position of the rightmost set bit.\n(-n) reverses all the bits from left to right till the last set bit\nfor example:\nn = 16810\nbinary signed 2's complement of n = 00000000101010002\nbinary signed 2's complement of -n = 11111111010110002\n∴ (n & -n) = 00000000000010002 = 8\nnow, log2(n & -n) = log2(8) = 3\nlog2(n & -n) + 1 = 4 (position of rightmost set bit)"
},
{
"code": null,
"e": 25569,
"s": 25518,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25573,
"s": 25569,
"text": "C++"
},
{
"code": null,
"e": 25578,
"s": 25573,
"text": "Java"
},
{
"code": null,
"e": 25586,
"s": 25578,
"text": "Python3"
},
{
"code": null,
"e": 25589,
"s": 25586,
"text": "C#"
},
{
"code": null,
"e": 25593,
"s": 25589,
"text": "PHP"
},
{
"code": null,
"e": 25604,
"s": 25593,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the position// of rightmost different bit#include <bits/stdc++.h>using namespace std; // Function to find the position of// rightmost set bit in 'n'// returns 0 if there is no set bit.int getRightMostSetBit(int n){ // to handle edge case when n = 0. if (n == 0) return 0; return log2(n & -n) + 1;} // Function to find the position of// rightmost different bit in the// binary representations of 'm' and 'n'// returns 0 if there is no// rightmost different bit.int posOfRightMostDiffBit(int m, int n){ // position of rightmost different // bit return getRightMostSetBit(m ^ n);} // Driver programint main(){ int m = 52, n = 24; cout << \"Position of rightmost different bit:\" << posOfRightMostDiffBit(m, n)<<endl; return 0;}",
"e": 26415,
"s": 25604,
"text": null
},
{
"code": "// Java implementation to find the position// of rightmost different bit class GFG { // Function to find the position of // rightmost set bit in 'n' // return 0 if there is no set bit. static int getRightMostSetBit(int n) { if(n == 0) return 0; return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1; } // Function to find the position of // rightmost different bit in the // binary representations of 'm' and 'n' static int posOfRightMostDiffBit(int m, int n) { // position of rightmost different bit return getRightMostSetBit(m ^ n); } // Driver code public static void main(String arg[]) { int m = 52, n = 4; System.out.print(\"Position = \" + posOfRightMostDiffBit(m, n)); }} // This code is contributed by Anant Agarwal.",
"e": 27291,
"s": 26415,
"text": null
},
{
"code": "# Python implementation# to find the position# of rightmost different bit import math # Function to find the position of# rightmost set bit in 'n'def getRightMostSetBit(n): if (n == 0): return 0 return math.log2(n & -n) + 1 # Function to find the position of# rightmost different bit in the# binary representations of 'm' and 'n'def posOfRightMostDiffBit(m, n): # position of rightmost different # bit return getRightMostSetBit(m ^ n) # Driver code m = 52n = 4print(\"position = \", int(posOfRightMostDiffBit(m, n))) # This code is contributed# by Anant Agarwal.",
"e": 27877,
"s": 27291,
"text": null
},
{
"code": "// C# implementation to find the position// of rightmost different bitusing System; class GFG { // Function to find the position of // rightmost set bit in 'n' static int getRightMostSetBit(int n) { if (n == 0) return 0; return (int)((Math.Log10(n & -n)) / Math.Log10(2)) + 1; } // Function to find the position of // rightmost different bit in the // binary representations of 'm' and 'n' static int posOfRightMostDiffBit(int m, int n) { // position of rightmost different bit return getRightMostSetBit(m ^ n); } // Driver code public static void Main() { int m = 52, n = 4; Console.Write(\"Position = \" + posOfRightMostDiffBit(m, n)); }} // This code is contributed by Smitha.",
"e": 28701,
"s": 27877,
"text": null
},
{
"code": "<?php// PHP implementation to// find the position of// rightmost different bit // Function to find the position// of rightmost set bit in 'n'function getRightMostSetBit($n){ if ($n == 0) return 0; return log($n & -$n, (2)) + 1;} // Function to find the position of// rightmost different bit in the// binary representations of 'm'// and 'n'function posOfRightMostDiffBit($m, $n){ // position of rightmost // different bit return getRightMostSetBit($m ^ $n);} // Driver Code $m = 52; $n = 4; echo posOfRightMostDiffBit($m, $n); // This code is contributed by Ajit?>",
"e": 29311,
"s": 28701,
"text": null
},
{
"code": "<script>// JavaScript implementation to find the position// of rightmost different bit // Function to find the position of// rightmost set bit in 'n'// returns 0 if there is no set bit.function getRightMostSetBit(n){ // to handle edge case when n = 0. if (n == 0) return 0; return Math.log2(n & -n) + 1;} // Function to find the position of// rightmost different bit in the// binary representations of 'm' and 'n'// returns 0 if there is no// rightmost different bit.function posOfRightMostDiffBit(m, n){ // position of rightmost different // bit return getRightMostSetBit(m ^ n);} // Driver program let m = 52, n = 24; document.write(\"Position of rightmost different bit:\" + posOfRightMostDiffBit(m, n) + \"<br>\"); // This code is contributed by Surbhi Tyagi.</script>",
"e": 30133,
"s": 29311,
"text": null
},
{
"code": null,
"e": 30171,
"s": 30133,
"text": "Position of rightmost different bit:3"
},
{
"code": null,
"e": 30192,
"s": 30171,
"text": "Using ffs() function"
},
{
"code": null,
"e": 30196,
"s": 30192,
"text": "C++"
},
{
"code": null,
"e": 30201,
"s": 30196,
"text": "Java"
},
{
"code": null,
"e": 30209,
"s": 30201,
"text": "Python3"
},
{
"code": null,
"e": 30212,
"s": 30209,
"text": "C#"
},
{
"code": null,
"e": 30216,
"s": 30212,
"text": "PHP"
},
{
"code": null,
"e": 30227,
"s": 30216,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// position of rightmost different// bit in two number.#include <bits/stdc++.h>using namespace std; // function to find rightmost different// bit in two numbers.int posOfRightMostDiffBit(int m, int n){ return ffs(m ^ n);} // Driver codeint main(){ int m = 52, n = 4; cout <<\"Position = \" << posOfRightMostDiffBit(m, n); return 0;}",
"e": 30614,
"s": 30227,
"text": null
},
{
"code": "// Java implementation to find the// position of rightmost different// bit in two number.import java.util.*;class GFG{ // function to find rightmost// different bit in two numbers.static int posOfRightMostDiffBit(int m, int n){ return (int)Math.floor( Math.log10( Math.pow(m ^ n, 2)))+2;} // Driver codepublic static void main(String[] args){ int m = 52, n = 4; System.out.println(\"Position = \" + posOfRightMostDiffBit(m, n));}} // This code is contributed by gauravrajput1",
"e": 31194,
"s": 30614,
"text": null
},
{
"code": "# Python3 implementation to find the# position of rightmost different# bit in two number.from math import floor, log10 # Function to find rightmost different# bit in two numbers.def posOfRightMostDiffBit(m, n): return floor(log10(pow(m ^ n, 2))) + 2 # Driver codeif __name__ == '__main__': m, n = 52, 4 print(\"Position = \", posOfRightMostDiffBit(m, n)) # This code is contributed by mohit kumar 29",
"e": 31619,
"s": 31194,
"text": null
},
{
"code": "// C# implementation to find the// position of rightmost different// bit in two number.using System;class GFG{ // function to find rightmost // different bit in two numbers. static int posOfRightMostDiffBit(int m, int n) { return (int)Math.Floor(Math.Log10( Math.Pow(m ^ n, 2))) + 2; } // Driver code public static void Main(String[] args) { int m = 52, n = 4; Console.Write(\"Position = \" + posOfRightMostDiffBit(m, n)); }} // This code is contributed by shivanisinghss2110",
"e": 32169,
"s": 31619,
"text": null
},
{
"code": "<?php// PHP implementation to find the// position of rightmost different// bit in two number. // function to find rightmost// different bit in two numbers.function posOfRightMostDiffBit($m, $n){ $t = floor(log($m ^ $n, 2)); return $t;} // Driver code$m = 52;$n = 4;echo \"Position = \" , posOfRightMostDiffBit($m, $n); // This code is contributed by ajit?>",
"e": 32533,
"s": 32169,
"text": null
},
{
"code": "<script> // Javascript implementation to find the // position of rightmost different // bit in two number. // function to find rightmost // different bit in two numbers. function posOfRightMostDiffBit(m, n) { return parseInt(Math.floor (Math.log10(Math.pow(m ^ n, 2))), 10) + 2; } let m = 52, n = 4; document.write( \"Position = \" + posOfRightMostDiffBit(m, n) ); </script>",
"e": 32967,
"s": 32533,
"text": null
},
{
"code": null,
"e": 32980,
"s": 32967,
"text": "Position = 5"
},
{
"code": null,
"e": 33402,
"s": 32980,
"text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33411,
"s": 33402,
"text": "Mannuyou"
},
{
"code": null,
"e": 33417,
"s": 33411,
"text": "jit_t"
},
{
"code": null,
"e": 33438,
"s": 33417,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 33454,
"s": 33438,
"text": "shreyashagrawal"
},
{
"code": null,
"e": 33464,
"s": 33454,
"text": "abbccc123"
},
{
"code": null,
"e": 33478,
"s": 33464,
"text": "GauravRajput1"
},
{
"code": null,
"e": 33493,
"s": 33478,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33512,
"s": 33493,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 33521,
"s": 33512,
"text": "mank1083"
},
{
"code": null,
"e": 33539,
"s": 33521,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 33547,
"s": 33539,
"text": "clintra"
},
{
"code": null,
"e": 33555,
"s": 33547,
"text": "scisaif"
},
{
"code": null,
"e": 33569,
"s": 33555,
"text": "sumitgumber28"
},
{
"code": null,
"e": 33586,
"s": 33569,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33608,
"s": 33586,
"text": "binary-representation"
},
{
"code": null,
"e": 33612,
"s": 33608,
"text": "BIT"
},
{
"code": null,
"e": 33622,
"s": 33612,
"text": "Bit Magic"
},
{
"code": null,
"e": 33632,
"s": 33622,
"text": "Bit Magic"
},
{
"code": null,
"e": 33730,
"s": 33632,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33739,
"s": 33730,
"text": "Comments"
},
{
"code": null,
"e": 33752,
"s": 33739,
"text": "Old Comments"
},
{
"code": null,
"e": 33798,
"s": 33752,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 33828,
"s": 33798,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 33868,
"s": 33828,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 33921,
"s": 33868,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 33972,
"s": 33921,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 34015,
"s": 33972,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 34050,
"s": 34015,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 34088,
"s": 34050,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 34139,
"s": 34088,
"text": "Set, Clear and Toggle a given bit of a number in C"
}
] |
Get last N elements from given list in Python | Given a Python list we want to find out only e e the last few elements.
The number of positions to be extracted is given. Based on that we design is slicing technique to slice elements from the end of the list by using a negative sign.
Live Demo
listA = ['Mon','Tue','Wed','Thu','Fri','Sat']
# Given list
print("Given list : \n",listA)
# initializing N
n = 4
# using list slicing
res = listA[-n:]
# print result
print("The last 4 elements of the list are : \n",res)
Running the above code gives us the following result −
Given list :
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
The last 4 elements of the list are :
['Wed', 'Thu', 'Fri', 'Sat']
The islice function takes the number of positions as a parameter along with the reversed order of the list.
Live Demo
from itertools import islice
listA = ['Mon','Tue','Wed','Thu','Fri','Sat']
# Given list
print("Given list : \n",listA)
# initializing N
n = 4
# using reversed
res = list(islice(reversed(listA), 0, n))
res.reverse()
# print result
print("The last 4 elements of the list are : \n",res)
Running the above code gives us the following result −
Given list :
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
The last 4 elements of the list are :
['Wed', 'Thu', 'Fri', 'Sat'] | [
{
"code": null,
"e": 1134,
"s": 1062,
"text": "Given a Python list we want to find out only e e the last few elements."
},
{
"code": null,
"e": 1298,
"s": 1134,
"text": "The number of positions to be extracted is given. Based on that we design is slicing technique to slice elements from the end of the list by using a negative sign."
},
{
"code": null,
"e": 1309,
"s": 1298,
"text": " Live Demo"
},
{
"code": null,
"e": 1529,
"s": 1309,
"text": "listA = ['Mon','Tue','Wed','Thu','Fri','Sat']\n# Given list\nprint(\"Given list : \\n\",listA)\n# initializing N\nn = 4\n# using list slicing\nres = listA[-n:]\n# print result\nprint(\"The last 4 elements of the list are : \\n\",res)"
},
{
"code": null,
"e": 1584,
"s": 1529,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1707,
"s": 1584,
"text": "Given list :\n['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']\nThe last 4 elements of the list are :\n['Wed', 'Thu', 'Fri', 'Sat']"
},
{
"code": null,
"e": 1815,
"s": 1707,
"text": "The islice function takes the number of positions as a parameter along with the reversed order of the list."
},
{
"code": null,
"e": 1826,
"s": 1815,
"text": " Live Demo"
},
{
"code": null,
"e": 2110,
"s": 1826,
"text": "from itertools import islice\nlistA = ['Mon','Tue','Wed','Thu','Fri','Sat']\n# Given list\nprint(\"Given list : \\n\",listA)\n# initializing N\nn = 4\n# using reversed\nres = list(islice(reversed(listA), 0, n))\nres.reverse()\n# print result\nprint(\"The last 4 elements of the list are : \\n\",res)"
},
{
"code": null,
"e": 2165,
"s": 2110,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2288,
"s": 2165,
"text": "Given list :\n['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']\nThe last 4 elements of the list are :\n['Wed', 'Thu', 'Fri', 'Sat']"
}
] |
Check if given array can be rearranged such that mean is equal to median - GeeksforGeeks | 24 Sep, 2021
Given sorted float array arr[]. Check if arr[] can be rearranged such that its mean is equal to its median.
Examples:
Input: arr[] = {1.0, 3.0, 6.0, 9.0, 12.0, 32.0}Output: YesExplanation: The mean of given array is (1.0 + 3.0 + 6.0 + 9.0 + 12.0 + 32.0) / 6 = 10.5. Rearranging given array as {1.0, 3.0, 9.0, 12.0, 6.0, 32.0}, here median is (9.0 + 12.0) / 2 = 10.5
Input: arr[] = {8.0, 13.0, 15.0}Output: No
Approach: The given problem can be solved by using Binary Search and Two Pointers approach. If size of arr[] is odd that means the median is a single element that can be searched by using Binary search. If array size is even then Two pointers approach can be used because then median will be composed of two elements. Follow the steps below to solve the given problem.
Initialize a variable say, mean to store mean of arr[].
Check if the size of arr[] is even or odd.if size of arr[] is evenUse Two Pointers approach to search two elements whose average = mean.Initialize two pointers as i=0, j=n-1.Perform two pointers approach to search for the median in arr[].if size of arr[] is oddApply Binary Search to find if mean is present in arr[] or not.
if size of arr[] is evenUse Two Pointers approach to search two elements whose average = mean.Initialize two pointers as i=0, j=n-1.Perform two pointers approach to search for the median in arr[].
Use Two Pointers approach to search two elements whose average = mean.
Initialize two pointers as i=0, j=n-1.
Perform two pointers approach to search for the median in arr[].
if size of arr[] is oddApply Binary Search to find if mean is present in arr[] or not.
Apply Binary Search to find if mean is present in arr[] or not.
If it is mean is found return Yes, otherwise No.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; // Function to return true or false if// size of array is oddbool binarySearch(float arr[], int size, float key){ int low = 0, high = size - 1, mid; while (low <= high) { // To prevent overflow mid = low + (high - low) / 2; // If element is greater than mid, then // it can only be present in right subarray if (key > arr[mid]) low = mid + 1; // If element is smaller than mid, then // it can only be present in left subarray else if (key < arr[mid]) high = mid - 1; // Else the element is present at the middle // then return 1 else return 1; } // when element is not present // in array then return 0 return 0;} // Function to return true or false// if size of array is evenbool twoPointers(float arr[], int N, float mean){ int i = 0, j = N - 1; while (i < j) { // Calculating Candidate Median float temp = (arr[i] + arr[j]) / 2; // If Candidate Median if greater // than Mean then decrement j if (temp > mean) j--; // If Candidate Median if less // than Mean then increment i else if (temp < mean) i++; // If Candidate Median if equal // to Mean then return 1 else return 1; } // when No candidate found for mean return 0;} // Function to return true if Mean// can be equal to any candidate// median otherwise return falsebool checkArray(float arr[], int N){ // Calculating Mean float sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; float mean = sum / N; // If N is Odd if (N & 1) return binarySearch(arr, N, mean); // If N is even else return twoPointers(arr, N, mean);} // Driver Codeint main(){ float arr[] = { 1.0, 3.0, 6.0, 9.0, 12.0, 32.0 }; int N = sizeof(arr) / sizeof(arr[0]); if (checkArray(arr, N)) cout << "Yes"; else cout << "No"; return 0;}
// Java program for the above approachimport java.io.*; public class GFG{ // Function to return true or false if// size of array is oddstatic boolean binarySearch(float []arr, int size, float key){ int low = 0, high = size - 1, mid; while (low <= high) { // To prevent overflow mid = low + (high - low) / 2; // If element is greater than mid, then // it can only be present in right subarray if (key > arr[mid]) low = mid + 1; // If element is smaller than mid, then // it can only be present in left subarray else if (key < arr[mid]) high = mid - 1; // Else the element is present at the middle // then return 1 else return true; } // when element is not present // in array then return 0 return false;} // Function to return true or false// if size of array is evenstatic boolean twoPointers(float []arr, int N, float mean){ int i = 0, j = N - 1; while (i < j) { // Calculating Candidate Median float temp = (arr[i] + arr[j]) / 2; // If Candidate Median if greater // than Mean then decrement j if (temp > mean) j--; // If Candidate Median if less // than Mean then increment i else if (temp < mean) i++; // If Candidate Median if equal // to Mean then return 1 else return true; } // when No candidate found for mean return false;} // Function to return true if Mean// can be equal to any candidate// median otherwise return falsestatic boolean checkArray(float []arr, int N){ // Calculating Mean float sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; float mean = sum / N; // If N is Odd if ((N & 1)!=0) return binarySearch(arr, N, mean); // If N is even else return twoPointers(arr, N, mean);} // Driver Codepublic static void main(String []args){ float []arr = { 1.0f, 3.0f, 6.0f, 9.0f, 12.0f, 32.0f }; int N = arr.length; if (checkArray(arr, N)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by AnkThon.
# python program for the above approach # Function to return true or false if# size of array is odddef binarySearch(arr, size, key): low = 0 high = size - 1 while (low <= high): # To prevent overflow mid = low + (high - low) // 2 # If element is greater than mid, then # it can only be present in right subarray if (key > arr[mid]): low = mid + 1 # If element is smaller than mid, then # it can only be present in left subarray elif (key < arr[mid]): high = mid - 1 # Else the element is present at the middle # then return 1 else: return 1 # when element is not present # in array then return 0 return 0 # Function to return true or false# if size of array is evendef twoPointers(arr, N, mean): i = 0 j = N - 1 while (i < j): # Calculating Candidate Median temp = (arr[i] + arr[j]) / 2 # If Candidate Median if greater # than Mean then decrement j if (temp > mean): j = j - 1 # If Candidate Median if less # than Mean then increment i elif (temp < mean): i = i + 1 # If Candidate Median if equal # to Mean then return 1 else: return 1 # when No candidate found for mean return 0 # Function to return true if Mean# can be equal to any candidate# median otherwise return falsedef checkArray(arr, N): # Calculating Mean sum = 0 for i in range(0, N): sum += arr[i] mean = sum / N # If N is Odd if (N & 1): return binarySearch(arr, N, mean) # If N is even else: return twoPointers(arr, N, mean) # Driver Codeif __name__ == "__main__": arr = [1.0, 3.0, 6.0, 9.0, 12.0, 32.0] N = len(arr) if (checkArray(arr, N)): print("Yes") else: print("No") # This code is contributed by rakeshsahni
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return true or false if// size of array is oddstatic bool binarySearch(float []arr, int size, float key){ int low = 0, high = size - 1, mid; while (low <= high) { // To prevent overflow mid = low + (high - low) / 2; // If element is greater than mid, then // it can only be present in right subarray if (key > arr[mid]) low = mid + 1; // If element is smaller than mid, then // it can only be present in left subarray else if (key < arr[mid]) high = mid - 1; // Else the element is present at the middle // then return 1 else return true; } // when element is not present // in array then return 0 return false;} // Function to return true or false// if size of array is evenstatic bool twoPointers(float []arr, int N, float mean){ int i = 0, j = N - 1; while (i < j) { // Calculating Candidate Median float temp = (arr[i] + arr[j]) / 2; // If Candidate Median if greater // than Mean then decrement j if (temp > mean) j--; // If Candidate Median if less // than Mean then increment i else if (temp < mean) i++; // If Candidate Median if equal // to Mean then return 1 else return true; } // when No candidate found for mean return false;} // Function to return true if Mean// can be equal to any candidate// median otherwise return falsestatic bool checkArray(float []arr, int N){ // Calculating Mean float sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; float mean = sum / N; // If N is Odd if ((N & 1)!=0) return binarySearch(arr, N, mean); // If N is even else return twoPointers(arr, N, mean);} // Driver Codepublic static void Main(){ float []arr = { 1.0f, 3.0f, 6.0f, 9.0f, 12.0f, 32.0f }; int N = arr.Length; if (checkArray(arr, N)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by SURENDRA_GANGWAR.
<script> // JavaScript program for the above approach // Function to return true or false if // size of array is odd const binarySearch = (arr, size, key) => { let low = 0, high = size - 1, mid; while (low <= high) { // To prevent overflow mid = low + parseInt((high - low) / 2); // If element is greater than mid, then // it can only be present in right subarray if (key > arr[mid]) low = mid + 1; // If element is smaller than mid, then // it can only be present in left subarray else if (key < arr[mid]) high = mid - 1; // Else the element is present at the middle // then return 1 else return 1; } // when element is not present // in array then return 0 return 0; } // Function to return true or false // if size of array is even const twoPointers = (arr, N, mean) => { let i = 0, j = N - 1; while (i < j) { // Calculating Candidate Median let temp = (arr[i] + arr[j]) / 2; // If Candidate Median if greater // than Mean then decrement j if (temp > mean) j--; // If Candidate Median if less // than Mean then increment i else if (temp < mean) i++; // If Candidate Median if equal // to Mean then return 1 else return 1; } // when No candidate found for mean return 0; } // Function to return true if Mean // can be equal to any candidate // median otherwise return false const checkArray = (arr, N) => { // Calculating Mean let sum = 0; for (let i = 0; i < N; i++) sum += arr[i]; let mean = sum / N; // If N is Odd if (N & 1) return binarySearch(arr, N, mean); // If N is even else return twoPointers(arr, N, mean); } // Driver Code let arr = [1.0, 3.0, 6.0, 9.0, 12.0, 32.0]; let N = arr.length; if (checkArray(arr, N)) document.write("Yes"); else document.write("No"); // This code is contributed by rakeshsahni</script>
Yes
Time Complexity: O(N), when N is even.O(logN), when N is odd.Auxiliary Space: O(1).
rakeshsahni
SURENDRA_GANGWAR
ankthon
array-rearrange
Blogathon-2021
maths-mean
Arrays
Blogathon
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Trapping Rain Water
Find duplicates in O(n) time and O(1) extra space | Set 1
How to Call or Consume External API in Spring Boot?
SQL Query to Insert Multiple Rows
How to Install Selenium on MacOS?
Re-rendering Components in ReactJS
Difference Between Local Storage, Session Storage And Cookies | [
{
"code": null,
"e": 24742,
"s": 24714,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 24850,
"s": 24742,
"text": "Given sorted float array arr[]. Check if arr[] can be rearranged such that its mean is equal to its median."
},
{
"code": null,
"e": 24860,
"s": 24850,
"text": "Examples:"
},
{
"code": null,
"e": 25108,
"s": 24860,
"text": "Input: arr[] = {1.0, 3.0, 6.0, 9.0, 12.0, 32.0}Output: YesExplanation: The mean of given array is (1.0 + 3.0 + 6.0 + 9.0 + 12.0 + 32.0) / 6 = 10.5. Rearranging given array as {1.0, 3.0, 9.0, 12.0, 6.0, 32.0}, here median is (9.0 + 12.0) / 2 = 10.5"
},
{
"code": null,
"e": 25151,
"s": 25108,
"text": "Input: arr[] = {8.0, 13.0, 15.0}Output: No"
},
{
"code": null,
"e": 25520,
"s": 25151,
"text": "Approach: The given problem can be solved by using Binary Search and Two Pointers approach. If size of arr[] is odd that means the median is a single element that can be searched by using Binary search. If array size is even then Two pointers approach can be used because then median will be composed of two elements. Follow the steps below to solve the given problem."
},
{
"code": null,
"e": 25576,
"s": 25520,
"text": "Initialize a variable say, mean to store mean of arr[]."
},
{
"code": null,
"e": 25901,
"s": 25576,
"text": "Check if the size of arr[] is even or odd.if size of arr[] is evenUse Two Pointers approach to search two elements whose average = mean.Initialize two pointers as i=0, j=n-1.Perform two pointers approach to search for the median in arr[].if size of arr[] is oddApply Binary Search to find if mean is present in arr[] or not."
},
{
"code": null,
"e": 26098,
"s": 25901,
"text": "if size of arr[] is evenUse Two Pointers approach to search two elements whose average = mean.Initialize two pointers as i=0, j=n-1.Perform two pointers approach to search for the median in arr[]."
},
{
"code": null,
"e": 26169,
"s": 26098,
"text": "Use Two Pointers approach to search two elements whose average = mean."
},
{
"code": null,
"e": 26208,
"s": 26169,
"text": "Initialize two pointers as i=0, j=n-1."
},
{
"code": null,
"e": 26273,
"s": 26208,
"text": "Perform two pointers approach to search for the median in arr[]."
},
{
"code": null,
"e": 26360,
"s": 26273,
"text": "if size of arr[] is oddApply Binary Search to find if mean is present in arr[] or not."
},
{
"code": null,
"e": 26424,
"s": 26360,
"text": "Apply Binary Search to find if mean is present in arr[] or not."
},
{
"code": null,
"e": 26473,
"s": 26424,
"text": "If it is mean is found return Yes, otherwise No."
},
{
"code": null,
"e": 26524,
"s": 26473,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26528,
"s": 26524,
"text": "C++"
},
{
"code": null,
"e": 26533,
"s": 26528,
"text": "Java"
},
{
"code": null,
"e": 26541,
"s": 26533,
"text": "Python3"
},
{
"code": null,
"e": 26544,
"s": 26541,
"text": "C#"
},
{
"code": null,
"e": 26555,
"s": 26544,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; // Function to return true or false if// size of array is oddbool binarySearch(float arr[], int size, float key){ int low = 0, high = size - 1, mid; while (low <= high) { // To prevent overflow mid = low + (high - low) / 2; // If element is greater than mid, then // it can only be present in right subarray if (key > arr[mid]) low = mid + 1; // If element is smaller than mid, then // it can only be present in left subarray else if (key < arr[mid]) high = mid - 1; // Else the element is present at the middle // then return 1 else return 1; } // when element is not present // in array then return 0 return 0;} // Function to return true or false// if size of array is evenbool twoPointers(float arr[], int N, float mean){ int i = 0, j = N - 1; while (i < j) { // Calculating Candidate Median float temp = (arr[i] + arr[j]) / 2; // If Candidate Median if greater // than Mean then decrement j if (temp > mean) j--; // If Candidate Median if less // than Mean then increment i else if (temp < mean) i++; // If Candidate Median if equal // to Mean then return 1 else return 1; } // when No candidate found for mean return 0;} // Function to return true if Mean// can be equal to any candidate// median otherwise return falsebool checkArray(float arr[], int N){ // Calculating Mean float sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; float mean = sum / N; // If N is Odd if (N & 1) return binarySearch(arr, N, mean); // If N is even else return twoPointers(arr, N, mean);} // Driver Codeint main(){ float arr[] = { 1.0, 3.0, 6.0, 9.0, 12.0, 32.0 }; int N = sizeof(arr) / sizeof(arr[0]); if (checkArray(arr, N)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 28640,
"s": 26555,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; public class GFG{ // Function to return true or false if// size of array is oddstatic boolean binarySearch(float []arr, int size, float key){ int low = 0, high = size - 1, mid; while (low <= high) { // To prevent overflow mid = low + (high - low) / 2; // If element is greater than mid, then // it can only be present in right subarray if (key > arr[mid]) low = mid + 1; // If element is smaller than mid, then // it can only be present in left subarray else if (key < arr[mid]) high = mid - 1; // Else the element is present at the middle // then return 1 else return true; } // when element is not present // in array then return 0 return false;} // Function to return true or false// if size of array is evenstatic boolean twoPointers(float []arr, int N, float mean){ int i = 0, j = N - 1; while (i < j) { // Calculating Candidate Median float temp = (arr[i] + arr[j]) / 2; // If Candidate Median if greater // than Mean then decrement j if (temp > mean) j--; // If Candidate Median if less // than Mean then increment i else if (temp < mean) i++; // If Candidate Median if equal // to Mean then return 1 else return true; } // when No candidate found for mean return false;} // Function to return true if Mean// can be equal to any candidate// median otherwise return falsestatic boolean checkArray(float []arr, int N){ // Calculating Mean float sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; float mean = sum / N; // If N is Odd if ((N & 1)!=0) return binarySearch(arr, N, mean); // If N is even else return twoPointers(arr, N, mean);} // Driver Codepublic static void main(String []args){ float []arr = { 1.0f, 3.0f, 6.0f, 9.0f, 12.0f, 32.0f }; int N = arr.length; if (checkArray(arr, N)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by AnkThon.",
"e": 30838,
"s": 28640,
"text": null
},
{
"code": "# python program for the above approach # Function to return true or false if# size of array is odddef binarySearch(arr, size, key): low = 0 high = size - 1 while (low <= high): # To prevent overflow mid = low + (high - low) // 2 # If element is greater than mid, then # it can only be present in right subarray if (key > arr[mid]): low = mid + 1 # If element is smaller than mid, then # it can only be present in left subarray elif (key < arr[mid]): high = mid - 1 # Else the element is present at the middle # then return 1 else: return 1 # when element is not present # in array then return 0 return 0 # Function to return true or false# if size of array is evendef twoPointers(arr, N, mean): i = 0 j = N - 1 while (i < j): # Calculating Candidate Median temp = (arr[i] + arr[j]) / 2 # If Candidate Median if greater # than Mean then decrement j if (temp > mean): j = j - 1 # If Candidate Median if less # than Mean then increment i elif (temp < mean): i = i + 1 # If Candidate Median if equal # to Mean then return 1 else: return 1 # when No candidate found for mean return 0 # Function to return true if Mean# can be equal to any candidate# median otherwise return falsedef checkArray(arr, N): # Calculating Mean sum = 0 for i in range(0, N): sum += arr[i] mean = sum / N # If N is Odd if (N & 1): return binarySearch(arr, N, mean) # If N is even else: return twoPointers(arr, N, mean) # Driver Codeif __name__ == \"__main__\": arr = [1.0, 3.0, 6.0, 9.0, 12.0, 32.0] N = len(arr) if (checkArray(arr, N)): print(\"Yes\") else: print(\"No\") # This code is contributed by rakeshsahni",
"e": 32814,
"s": 30838,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return true or false if// size of array is oddstatic bool binarySearch(float []arr, int size, float key){ int low = 0, high = size - 1, mid; while (low <= high) { // To prevent overflow mid = low + (high - low) / 2; // If element is greater than mid, then // it can only be present in right subarray if (key > arr[mid]) low = mid + 1; // If element is smaller than mid, then // it can only be present in left subarray else if (key < arr[mid]) high = mid - 1; // Else the element is present at the middle // then return 1 else return true; } // when element is not present // in array then return 0 return false;} // Function to return true or false// if size of array is evenstatic bool twoPointers(float []arr, int N, float mean){ int i = 0, j = N - 1; while (i < j) { // Calculating Candidate Median float temp = (arr[i] + arr[j]) / 2; // If Candidate Median if greater // than Mean then decrement j if (temp > mean) j--; // If Candidate Median if less // than Mean then increment i else if (temp < mean) i++; // If Candidate Median if equal // to Mean then return 1 else return true; } // when No candidate found for mean return false;} // Function to return true if Mean// can be equal to any candidate// median otherwise return falsestatic bool checkArray(float []arr, int N){ // Calculating Mean float sum = 0; for (int i = 0; i < N; i++) sum += arr[i]; float mean = sum / N; // If N is Odd if ((N & 1)!=0) return binarySearch(arr, N, mean); // If N is even else return twoPointers(arr, N, mean);} // Driver Codepublic static void Main(){ float []arr = { 1.0f, 3.0f, 6.0f, 9.0f, 12.0f, 32.0f }; int N = arr.Length; if (checkArray(arr, N)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by SURENDRA_GANGWAR.",
"e": 35009,
"s": 32814,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to return true or false if // size of array is odd const binarySearch = (arr, size, key) => { let low = 0, high = size - 1, mid; while (low <= high) { // To prevent overflow mid = low + parseInt((high - low) / 2); // If element is greater than mid, then // it can only be present in right subarray if (key > arr[mid]) low = mid + 1; // If element is smaller than mid, then // it can only be present in left subarray else if (key < arr[mid]) high = mid - 1; // Else the element is present at the middle // then return 1 else return 1; } // when element is not present // in array then return 0 return 0; } // Function to return true or false // if size of array is even const twoPointers = (arr, N, mean) => { let i = 0, j = N - 1; while (i < j) { // Calculating Candidate Median let temp = (arr[i] + arr[j]) / 2; // If Candidate Median if greater // than Mean then decrement j if (temp > mean) j--; // If Candidate Median if less // than Mean then increment i else if (temp < mean) i++; // If Candidate Median if equal // to Mean then return 1 else return 1; } // when No candidate found for mean return 0; } // Function to return true if Mean // can be equal to any candidate // median otherwise return false const checkArray = (arr, N) => { // Calculating Mean let sum = 0; for (let i = 0; i < N; i++) sum += arr[i]; let mean = sum / N; // If N is Odd if (N & 1) return binarySearch(arr, N, mean); // If N is even else return twoPointers(arr, N, mean); } // Driver Code let arr = [1.0, 3.0, 6.0, 9.0, 12.0, 32.0]; let N = arr.length; if (checkArray(arr, N)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by rakeshsahni</script>",
"e": 37332,
"s": 35009,
"text": null
},
{
"code": null,
"e": 37336,
"s": 37332,
"text": "Yes"
},
{
"code": null,
"e": 37420,
"s": 37336,
"text": "Time Complexity: O(N), when N is even.O(logN), when N is odd.Auxiliary Space: O(1)."
},
{
"code": null,
"e": 37432,
"s": 37420,
"text": "rakeshsahni"
},
{
"code": null,
"e": 37449,
"s": 37432,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 37457,
"s": 37449,
"text": "ankthon"
},
{
"code": null,
"e": 37473,
"s": 37457,
"text": "array-rearrange"
},
{
"code": null,
"e": 37488,
"s": 37473,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 37499,
"s": 37488,
"text": "maths-mean"
},
{
"code": null,
"e": 37506,
"s": 37499,
"text": "Arrays"
},
{
"code": null,
"e": 37516,
"s": 37506,
"text": "Blogathon"
},
{
"code": null,
"e": 37529,
"s": 37516,
"text": "Mathematical"
},
{
"code": null,
"e": 37536,
"s": 37529,
"text": "Arrays"
},
{
"code": null,
"e": 37549,
"s": 37536,
"text": "Mathematical"
},
{
"code": null,
"e": 37647,
"s": 37549,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37656,
"s": 37647,
"text": "Comments"
},
{
"code": null,
"e": 37669,
"s": 37656,
"text": "Old Comments"
},
{
"code": null,
"e": 37694,
"s": 37669,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 37743,
"s": 37694,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 37781,
"s": 37743,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 37801,
"s": 37781,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 37859,
"s": 37801,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 37911,
"s": 37859,
"text": "How to Call or Consume External API in Spring Boot?"
},
{
"code": null,
"e": 37945,
"s": 37911,
"text": "SQL Query to Insert Multiple Rows"
},
{
"code": null,
"e": 37979,
"s": 37945,
"text": "How to Install Selenium on MacOS?"
},
{
"code": null,
"e": 38014,
"s": 37979,
"text": "Re-rendering Components in ReactJS"
}
] |
Python | Pandas DataFrame.columns | 20 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.columns attribute return the column labels of the given Dataframe.
Syntax: DataFrame.columns
Parameter : None
Returns : column names
Example #1: Use DataFrame.columns attribute to return the column labels of the given Dataframe.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.columns attribute to return the column labels of the given dataframe.
# return the column labelsresult = df.columns # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.columns attribute has successfully returned all of the column labels of the given dataframe. Example #2: Use DataFrame.columns attribute to return the column labels of the given Dataframe.
# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.columns attribute to return the column labels of the given dataframe.
# return the column labelsresult = df.columns # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.columns attribute has successfully returned all of the column labels of the given dataframe.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Feb, 2019"
},
{
"code": null,
"e": 342,
"s": 28,
"text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas."
},
{
"code": null,
"e": 426,
"s": 342,
"text": "Pandas DataFrame.columns attribute return the column labels of the given Dataframe."
},
{
"code": null,
"e": 452,
"s": 426,
"text": "Syntax: DataFrame.columns"
},
{
"code": null,
"e": 469,
"s": 452,
"text": "Parameter : None"
},
{
"code": null,
"e": 492,
"s": 469,
"text": "Returns : column names"
},
{
"code": null,
"e": 588,
"s": 492,
"text": "Example #1: Use DataFrame.columns attribute to return the column labels of the given Dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 'Age':[14, 25, 55, 8, 21]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)",
"e": 961,
"s": 588,
"text": null
},
{
"code": null,
"e": 970,
"s": 961,
"text": "Output :"
},
{
"code": null,
"e": 1066,
"s": 970,
"text": "Now we will use DataFrame.columns attribute to return the column labels of the given dataframe."
},
{
"code": "# return the column labelsresult = df.columns # Print the resultprint(result)",
"e": 1145,
"s": 1066,
"text": null
},
{
"code": null,
"e": 1385,
"s": 1145,
"text": "Output :As we can see in the output, the DataFrame.columns attribute has successfully returned all of the column labels of the given dataframe. Example #2: Use DataFrame.columns attribute to return the column labels of the given Dataframe."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the DataFramedf = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] # Set the indexdf.index = index_ # Print the DataFrameprint(df)",
"e": 1771,
"s": 1385,
"text": null
},
{
"code": null,
"e": 1780,
"s": 1771,
"text": "Output :"
},
{
"code": null,
"e": 1876,
"s": 1780,
"text": "Now we will use DataFrame.columns attribute to return the column labels of the given dataframe."
},
{
"code": "# return the column labelsresult = df.columns # Print the resultprint(result)",
"e": 1955,
"s": 1876,
"text": null
},
{
"code": null,
"e": 2099,
"s": 1955,
"text": "Output :As we can see in the output, the DataFrame.columns attribute has successfully returned all of the column labels of the given dataframe."
},
{
"code": null,
"e": 2123,
"s": 2099,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2155,
"s": 2123,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2169,
"s": 2155,
"text": "Python-pandas"
},
{
"code": null,
"e": 2176,
"s": 2169,
"text": "Python"
},
{
"code": null,
"e": 2274,
"s": 2176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2292,
"s": 2274,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2334,
"s": 2292,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2356,
"s": 2334,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2391,
"s": 2356,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2417,
"s": 2391,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2449,
"s": 2417,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2478,
"s": 2449,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2505,
"s": 2478,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2535,
"s": 2505,
"text": "Iterate over a list in Python"
}
] |
Queue in C++ Standard Template Library (STL) | 06 Jul, 2022
Queues are a type of container adaptors that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. Queues use an encapsulated object of deque or list (sequential container class) as its underlying container, providing a specific set of member functions to access its elements.
Following is an example to demonstrate the queue and its various methods.
CPP
// CPP code to illustrate Queue in // Standard Template Library (STL)#include <iostream>#include <queue> using namespace std; // Print the queuevoid showq(queue<int> gq){ queue<int> g = gq; while (!g.empty()) { cout << '\t' << g.front(); g.pop(); } cout << '\n';} // Driver Codeint main(){ queue<int> gquiz; gquiz.push(10); gquiz.push(20); gquiz.push(30); cout << "The queue gquiz is : "; showq(gquiz); cout << "\ngquiz.size() : " << gquiz.size(); cout << "\ngquiz.front() : " << gquiz.front(); cout << "\ngquiz.back() : " << gquiz.back(); cout << "\ngquiz.pop() : "; gquiz.pop(); showq(gquiz); return 0;}
The queue gquiz is : 10 20 30
gquiz.size() : 3
gquiz.front() : 10
gquiz.back() : 30
gquiz.pop() : 20 30
Methods of Queue are:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
The time complexity and definition of the following functions are as follows:
C++
// CPP code to illustrate Queue operations in STL// Divyansh Mishra --> divyanshmishra101010#include <iostream>#include <queue> using namespace std; // Print the queuevoid print_queue(queue<int> q){ queue<int> temp = q; while (!temp.empty()) { cout << temp.front()<<" "; temp.pop(); } cout << '\n';} // Driver Codeint main(){ queue<int> q1; q1.push(1); q1.push(2); q1.push(3); cout << "The first queue is : "; print_queue(q1); queue<int> q2; q2.push(4); q2.push(5); q2.push(6); cout << "The second queue is : "; print_queue(q2); q1.swap(q2); cout << "After swapping, the first queue is : "; print_queue(q1); cout << "After swapping the second queue is : "; print_queue(q2); cout<<q1.empty(); //returns false since q1 is not empty return 0;}
The first queue is : 1 2 3
The second queue is : 4 5 6
After swapping, the first queue is : 4 5 6
After swapping the second queue is : 1 2 3
0
C++ Programming Language Tutorial | Stacks and Queues using STL | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersC++ Programming Language Tutorial | Stacks and Queues using STL | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:39•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fV_DchJem0U" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Recent Articles on C++ Queue Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rohit kumar 37
rkmvcommon92569153
siddhartha_agarwal
lekhrajsharmaas
naveenkumar173
vijayt
anshikajain26
karunasharma12dec
divyanshmishra101010
cpp-containers-library
cpp-queue
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Arrays in C/C++
Set in C++ Standard Template Library (STL)
Inheritance in C++
unordered_map in C++ STL
vector erase() and clear() in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 407,
"s": 52,
"text": "Queues are a type of container adaptors that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. Queues use an encapsulated object of deque or list (sequential container class) as its underlying container, providing a specific set of member functions to access its elements."
},
{
"code": null,
"e": 481,
"s": 407,
"text": "Following is an example to demonstrate the queue and its various methods."
},
{
"code": null,
"e": 485,
"s": 481,
"text": "CPP"
},
{
"code": "// CPP code to illustrate Queue in // Standard Template Library (STL)#include <iostream>#include <queue> using namespace std; // Print the queuevoid showq(queue<int> gq){ queue<int> g = gq; while (!g.empty()) { cout << '\\t' << g.front(); g.pop(); } cout << '\\n';} // Driver Codeint main(){ queue<int> gquiz; gquiz.push(10); gquiz.push(20); gquiz.push(30); cout << \"The queue gquiz is : \"; showq(gquiz); cout << \"\\ngquiz.size() : \" << gquiz.size(); cout << \"\\ngquiz.front() : \" << gquiz.front(); cout << \"\\ngquiz.back() : \" << gquiz.back(); cout << \"\\ngquiz.pop() : \"; gquiz.pop(); showq(gquiz); return 0;}",
"e": 1167,
"s": 485,
"text": null
},
{
"code": null,
"e": 1289,
"s": 1167,
"text": "The queue gquiz is : 10 20 30\n\ngquiz.size() : 3\ngquiz.front() : 10\ngquiz.back() : 30\ngquiz.pop() : 20 30"
},
{
"code": null,
"e": 1312,
"s": 1289,
"text": "Methods of Queue are: "
},
{
"code": null,
"e": 1321,
"s": 1312,
"text": "Chapters"
},
{
"code": null,
"e": 1348,
"s": 1321,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1398,
"s": 1348,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1421,
"s": 1398,
"text": "captions off, selected"
},
{
"code": null,
"e": 1429,
"s": 1421,
"text": "English"
},
{
"code": null,
"e": 1453,
"s": 1429,
"text": "This is a modal window."
},
{
"code": null,
"e": 1522,
"s": 1453,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1544,
"s": 1522,
"text": "End of dialog window."
},
{
"code": null,
"e": 1622,
"s": 1544,
"text": "The time complexity and definition of the following functions are as follows:"
},
{
"code": null,
"e": 1626,
"s": 1622,
"text": "C++"
},
{
"code": "// CPP code to illustrate Queue operations in STL// Divyansh Mishra --> divyanshmishra101010#include <iostream>#include <queue> using namespace std; // Print the queuevoid print_queue(queue<int> q){ queue<int> temp = q; while (!temp.empty()) { cout << temp.front()<<\" \"; temp.pop(); } cout << '\\n';} // Driver Codeint main(){ queue<int> q1; q1.push(1); q1.push(2); q1.push(3); cout << \"The first queue is : \"; print_queue(q1); queue<int> q2; q2.push(4); q2.push(5); q2.push(6); cout << \"The second queue is : \"; print_queue(q2); q1.swap(q2); cout << \"After swapping, the first queue is : \"; print_queue(q1); cout << \"After swapping the second queue is : \"; print_queue(q2); cout<<q1.empty(); //returns false since q1 is not empty return 0;}",
"e": 2495,
"s": 1626,
"text": null
},
{
"code": null,
"e": 2642,
"s": 2495,
"text": "The first queue is : 1 2 3 \nThe second queue is : 4 5 6 \nAfter swapping, the first queue is : 4 5 6 \nAfter swapping the second queue is : 1 2 3 \n0"
},
{
"code": null,
"e": 3586,
"s": 2642,
"text": "C++ Programming Language Tutorial | Stacks and Queues using STL | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersC++ Programming Language Tutorial | Stacks and Queues using STL | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:39•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fV_DchJem0U\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 3742,
"s": 3586,
"text": "Recent Articles on C++ Queue Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3757,
"s": 3742,
"text": "Rohit kumar 37"
},
{
"code": null,
"e": 3776,
"s": 3757,
"text": "rkmvcommon92569153"
},
{
"code": null,
"e": 3795,
"s": 3776,
"text": "siddhartha_agarwal"
},
{
"code": null,
"e": 3811,
"s": 3795,
"text": "lekhrajsharmaas"
},
{
"code": null,
"e": 3826,
"s": 3811,
"text": "naveenkumar173"
},
{
"code": null,
"e": 3833,
"s": 3826,
"text": "vijayt"
},
{
"code": null,
"e": 3847,
"s": 3833,
"text": "anshikajain26"
},
{
"code": null,
"e": 3865,
"s": 3847,
"text": "karunasharma12dec"
},
{
"code": null,
"e": 3886,
"s": 3865,
"text": "divyanshmishra101010"
},
{
"code": null,
"e": 3909,
"s": 3886,
"text": "cpp-containers-library"
},
{
"code": null,
"e": 3919,
"s": 3909,
"text": "cpp-queue"
},
{
"code": null,
"e": 3923,
"s": 3919,
"text": "STL"
},
{
"code": null,
"e": 3927,
"s": 3923,
"text": "C++"
},
{
"code": null,
"e": 3931,
"s": 3927,
"text": "STL"
},
{
"code": null,
"e": 3935,
"s": 3931,
"text": "CPP"
},
{
"code": null,
"e": 4033,
"s": 3935,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4051,
"s": 4033,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 4094,
"s": 4051,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4140,
"s": 4094,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 4163,
"s": 4140,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 4190,
"s": 4163,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 4206,
"s": 4190,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 4249,
"s": 4206,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4268,
"s": 4249,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 4293,
"s": 4268,
"text": "unordered_map in C++ STL"
}
] |
Scala Map count() method with example | 13 Aug, 2019
The count() method is utilized to count pair of keys in the Map.
Method Definition: def count(p: ((A, B)) => Boolean): Int
Return Type: It returns the number of keys present in the map that satisfies the given predicate.
Example #1:
// Scala program of count()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map("geeks" -> 5, "for" -> 3, "cs" -> 5) // Applying count method val result = m1.count(z=>true) // Displays output println(result) }}
3
Example #2:
// Scala program of count()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map("geeks" -> 5, "for" -> 3, "geeks" -> 5) // Applying count method val result = m1.count(z=>true) // Displays output println(result) }}
2
So, the identical keys are counted only once.
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 93,
"s": 28,
"text": "The count() method is utilized to count pair of keys in the Map."
},
{
"code": null,
"e": 151,
"s": 93,
"text": "Method Definition: def count(p: ((A, B)) => Boolean): Int"
},
{
"code": null,
"e": 249,
"s": 151,
"text": "Return Type: It returns the number of keys present in the map that satisfies the given predicate."
},
{
"code": null,
"e": 261,
"s": 249,
"text": "Example #1:"
},
{
"code": "// Scala program of count()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3, \"cs\" -> 5) // Applying count method val result = m1.count(z=>true) // Displays output println(result) }}",
"e": 626,
"s": 261,
"text": null
},
{
"code": null,
"e": 629,
"s": 626,
"text": "3\n"
},
{
"code": null,
"e": 641,
"s": 629,
"text": "Example #2:"
},
{
"code": "// Scala program of count()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3, \"geeks\" -> 5) // Applying count method val result = m1.count(z=>true) // Displays output println(result) }}",
"e": 1009,
"s": 641,
"text": null
},
{
"code": null,
"e": 1012,
"s": 1009,
"text": "2\n"
},
{
"code": null,
"e": 1058,
"s": 1012,
"text": "So, the identical keys are counted only once."
},
{
"code": null,
"e": 1064,
"s": 1058,
"text": "Scala"
},
{
"code": null,
"e": 1074,
"s": 1064,
"text": "Scala-Map"
},
{
"code": null,
"e": 1087,
"s": 1074,
"text": "Scala-Method"
},
{
"code": null,
"e": 1093,
"s": 1087,
"text": "Scala"
}
] |
Producer Consumer Problem and its Implementation with C++ | 31 May, 2021
Overview :In this article, we will discuss the Producer-Consumer Problem and its Implementation with C++. The Producer-Consumer problem is a classical two-process synchronization problem. Let’s discuss it one by one.
Problem Statement :There is one Producer and one Consumer in the producer-consumer problem.
Producer – The producer process executes a set of statements int produce to create a data element and stores it in the buffer.Consumer – If the buffer has items, a consumer process executes a statement consume with the data element as a parameter.
Producer – The producer process executes a set of statements int produce to create a data element and stores it in the buffer.
Consumer – If the buffer has items, a consumer process executes a statement consume with the data element as a parameter.
Solution : The problem arises because the process is not synchronized because of which the items produced and consumed may not be consistent. In order to solve this problem, we use semaphore for solving this problem i.e. problem of the critical section.
Implementation in C++ :This problem can be further subdivided into two parts as follows.
Part-1: Where the buffer size is infinite –In this case, the buffer from where the producer stores the item and the consumer consumes the item size is not fixed.
C++14
#include<bits/stdc++.h>#include<pthread.h>#include<semaphore.h>#include <unistd.h> using namespace std; // Declarationint r1,total_produced=0,total_consume=0; // Semaphore declarationsem_t notEmpty; // Producer Sectionvoid* produce(void *arg){ while(1){ cout<<"Producer produces item."<<endl; cout<<"Total produced = "<<++total_produced<< " Total consume = "<<total_consume*-1<<endl; sem_post(¬Empty); sleep(rand()%100*0.01); }} // Consumer Sectionvoid* consume(void *arg){ while(1){ sem_wait(¬Empty); cout<<"Consumer consumes item."<<endl; cout<<"Total produced = "<<total_produced<< " Total consume = "<<(--total_consume)*-1<<endl; sleep(rand()%100*0.01); } } int main(int argv,char *argc[]){ // thread declaration pthread_t producer,consumer; // Declaration of attribute...... pthread_attr_t attr; // semaphore initialization sem_init(¬Empty,0,0); // pthread_attr_t initialization pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); // Creation of process r1=pthread_create(&producer,&attr,produce,NULL); if(r1){ cout<<"Error in creating thread"<<endl; exit(-1); } r1=pthread_create(&consumer,&attr,consume,NULL); if(r1){ cout<<"Error in creating thread"<<endl; exit(-1); } // destroying the pthread_attr pthread_attr_destroy(&attr); // Joining the thread r1=pthread_join(producer,NULL); if(r1){ cout<<"Error in joining thread"<<endl; exit(-1); } r1=pthread_join(consumer,NULL); if(r1){ cout<<"Error in joining thread"<<endl; exit(-1); } // Exiting thread pthread_exit(NULL); return 0;}
Part-2: Where the buffer size is fixed or finite –In this case, the buffer from where the producer stores the item and the consumer consumes the item size is fixed.
C++14
#include <bits/stdc++.h>#include <pthread.h>#include <semaphore.h>#include <unistd.h>using namespace std; // Declarationint r1, items = 0; // Semaphore declarationsem_t notEmpty, notFull; // Producer Sectionvoid* produce(void* arg){ while (1) { sem_wait(¬Full); sleep(rand() % 100 * 0.01); cout << "Producer produces item.Items Present = " << ++items << endl; sem_post(¬Empty); sleep(rand() % 100 * 0.01); }} // Consumer Sectionvoid* consume(void* arg){ while (1) { sem_wait(¬Empty); sleep(rand() % 100 * 0.01); cout << "Consumer consumes item.Items Present = " << --items << endl; sem_post(¬Full); sleep(rand() % 100 * 0.01); }} int main(int argv, char* argc[]){ int N; cout << "Enter the capacity of the buffer" << endl; cin >> N; // thread declaration pthread_t producer, consumer; // Declaration of attribute...... pthread_attr_t attr; // semaphore initialization sem_init(¬Empty, 0, 0); sem_init(¬Full, 0, N); // pthread_attr_t initialization pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); // Creation of process r1 = pthread_create(&producer, &attr, produce, NULL); if (r1) { cout << "Error in creating thread" << endl; exit(-1); } r1 = pthread_create(&consumer, &attr, consume, NULL); if (r1) { cout << "Error in creating thread" << endl; exit(-1); } // destroying the pthread_attr pthread_attr_destroy(&attr); // Joining the thread r1 = pthread_join(producer, NULL); if (r1) { cout << "Error in joining thread" << endl; exit(-1); } r1 = pthread_join(consumer, NULL); if (r1) { cout << "Error in joining thread" << endl; exit(-1); } // Exiting thread pthread_exit(NULL); return 0;}
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Introduction of Process Synchronization
Three address code in Compiler
Differences between IPv4 and IPv6
Phases of a Compiler
Banker's Algorithm in Operating System
Disk Scheduling Algorithms
Introduction of Deadlock in Operating System
Paging in Operating System
File Allocation Methods | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 269,
"s": 52,
"text": "Overview :In this article, we will discuss the Producer-Consumer Problem and its Implementation with C++. The Producer-Consumer problem is a classical two-process synchronization problem. Let’s discuss it one by one."
},
{
"code": null,
"e": 361,
"s": 269,
"text": "Problem Statement :There is one Producer and one Consumer in the producer-consumer problem."
},
{
"code": null,
"e": 609,
"s": 361,
"text": "Producer – The producer process executes a set of statements int produce to create a data element and stores it in the buffer.Consumer – If the buffer has items, a consumer process executes a statement consume with the data element as a parameter."
},
{
"code": null,
"e": 736,
"s": 609,
"text": "Producer – The producer process executes a set of statements int produce to create a data element and stores it in the buffer."
},
{
"code": null,
"e": 858,
"s": 736,
"text": "Consumer – If the buffer has items, a consumer process executes a statement consume with the data element as a parameter."
},
{
"code": null,
"e": 1113,
"s": 858,
"text": "Solution : The problem arises because the process is not synchronized because of which the items produced and consumed may not be consistent. In order to solve this problem, we use semaphore for solving this problem i.e. problem of the critical section."
},
{
"code": null,
"e": 1202,
"s": 1113,
"text": "Implementation in C++ :This problem can be further subdivided into two parts as follows."
},
{
"code": null,
"e": 1364,
"s": 1202,
"text": "Part-1: Where the buffer size is infinite –In this case, the buffer from where the producer stores the item and the consumer consumes the item size is not fixed."
},
{
"code": null,
"e": 1370,
"s": 1364,
"text": "C++14"
},
{
"code": "#include<bits/stdc++.h>#include<pthread.h>#include<semaphore.h>#include <unistd.h> using namespace std; // Declarationint r1,total_produced=0,total_consume=0; // Semaphore declarationsem_t notEmpty; // Producer Sectionvoid* produce(void *arg){ while(1){ cout<<\"Producer produces item.\"<<endl; cout<<\"Total produced = \"<<++total_produced<< \" Total consume = \"<<total_consume*-1<<endl; sem_post(¬Empty); sleep(rand()%100*0.01); }} // Consumer Sectionvoid* consume(void *arg){ while(1){ sem_wait(¬Empty); cout<<\"Consumer consumes item.\"<<endl; cout<<\"Total produced = \"<<total_produced<< \" Total consume = \"<<(--total_consume)*-1<<endl; sleep(rand()%100*0.01); } } int main(int argv,char *argc[]){ // thread declaration pthread_t producer,consumer; // Declaration of attribute...... pthread_attr_t attr; // semaphore initialization sem_init(¬Empty,0,0); // pthread_attr_t initialization pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); // Creation of process r1=pthread_create(&producer,&attr,produce,NULL); if(r1){ cout<<\"Error in creating thread\"<<endl; exit(-1); } r1=pthread_create(&consumer,&attr,consume,NULL); if(r1){ cout<<\"Error in creating thread\"<<endl; exit(-1); } // destroying the pthread_attr pthread_attr_destroy(&attr); // Joining the thread r1=pthread_join(producer,NULL); if(r1){ cout<<\"Error in joining thread\"<<endl; exit(-1); } r1=pthread_join(consumer,NULL); if(r1){ cout<<\"Error in joining thread\"<<endl; exit(-1); } // Exiting thread pthread_exit(NULL); return 0;}",
"e": 3122,
"s": 1370,
"text": null
},
{
"code": null,
"e": 3287,
"s": 3122,
"text": "Part-2: Where the buffer size is fixed or finite –In this case, the buffer from where the producer stores the item and the consumer consumes the item size is fixed."
},
{
"code": null,
"e": 3293,
"s": 3287,
"text": "C++14"
},
{
"code": "#include <bits/stdc++.h>#include <pthread.h>#include <semaphore.h>#include <unistd.h>using namespace std; // Declarationint r1, items = 0; // Semaphore declarationsem_t notEmpty, notFull; // Producer Sectionvoid* produce(void* arg){ while (1) { sem_wait(¬Full); sleep(rand() % 100 * 0.01); cout << \"Producer produces item.Items Present = \" << ++items << endl; sem_post(¬Empty); sleep(rand() % 100 * 0.01); }} // Consumer Sectionvoid* consume(void* arg){ while (1) { sem_wait(¬Empty); sleep(rand() % 100 * 0.01); cout << \"Consumer consumes item.Items Present = \" << --items << endl; sem_post(¬Full); sleep(rand() % 100 * 0.01); }} int main(int argv, char* argc[]){ int N; cout << \"Enter the capacity of the buffer\" << endl; cin >> N; // thread declaration pthread_t producer, consumer; // Declaration of attribute...... pthread_attr_t attr; // semaphore initialization sem_init(¬Empty, 0, 0); sem_init(¬Full, 0, N); // pthread_attr_t initialization pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); // Creation of process r1 = pthread_create(&producer, &attr, produce, NULL); if (r1) { cout << \"Error in creating thread\" << endl; exit(-1); } r1 = pthread_create(&consumer, &attr, consume, NULL); if (r1) { cout << \"Error in creating thread\" << endl; exit(-1); } // destroying the pthread_attr pthread_attr_destroy(&attr); // Joining the thread r1 = pthread_join(producer, NULL); if (r1) { cout << \"Error in joining thread\" << endl; exit(-1); } r1 = pthread_join(consumer, NULL); if (r1) { cout << \"Error in joining thread\" << endl; exit(-1); } // Exiting thread pthread_exit(NULL); return 0;}",
"e": 5306,
"s": 3293,
"text": null
},
{
"code": null,
"e": 5314,
"s": 5306,
"text": "GATE CS"
},
{
"code": null,
"e": 5332,
"s": 5314,
"text": "Operating Systems"
},
{
"code": null,
"e": 5350,
"s": 5332,
"text": "Operating Systems"
},
{
"code": null,
"e": 5448,
"s": 5350,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5501,
"s": 5448,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 5541,
"s": 5501,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 5572,
"s": 5541,
"text": "Three address code in Compiler"
},
{
"code": null,
"e": 5606,
"s": 5572,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 5627,
"s": 5606,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 5666,
"s": 5627,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 5693,
"s": 5666,
"text": "Disk Scheduling Algorithms"
},
{
"code": null,
"e": 5738,
"s": 5693,
"text": "Introduction of Deadlock in Operating System"
},
{
"code": null,
"e": 5765,
"s": 5738,
"text": "Paging in Operating System"
}
] |
Print all pairs of anagrams in a given array of strings | 22 Jun, 2022
Given an array of strings, find all anagram pairs in the given array. Example:
Input: arr[] = {"geeksquiz", "geeksforgeeks", "abcd",
"forgeeksgeeks", "zuiqkeegs"};
Output: (geeksforgeeks, forgeeksgeeks), (geeksquiz, zuiqkeegs)
We can find whether two strings are anagram or not in linear time using count array (see method 2 of this). One simple idea to find whether all anagram pairs is to run two nested loops. The outer loop picks all strings one by one. The inner loop checks whether remaining strings are anagram of the string picked by outer loop. Below is the implementation of this approach :
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;#define NO_OF_CHARS 256 /* function to check whether two strings are anagram of each other */bool areAnagram(string str1, string str2){ // Create two count arrays and initialize all values as 0 int count[NO_OF_CHARS] = {0}; int i; // For each character in input strings, increment count in // the corresponding count array for (i = 0; str1[i] && str2[i]; i++) { count[str1[i]]++; count[str2[i]]--; } // If both strings are of different length. Removing this condition // will make the program fail for strings like "aaca" and "aca" if (str1[i] || str2[i]) return false; // See if there is any non-zero value in count array for (i = 0; i < NO_OF_CHARS; i++) if (count[i]) return false; return true;} // This function prints all anagram pairs in a given array of stringsvoid findAllAnagrams(string arr[], int n){ for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) if (areAnagram(arr[i], arr[j])) cout << arr[i] << " is anagram of " << arr[j] << endl;} /* Driver program to test to print printDups*/int main(){ string arr[] = {"geeksquiz", "geeksforgeeks", "abcd", "forgeeksgeeks", "zuiqkeegs"}; int n = sizeof(arr)/sizeof(arr[0]); findAllAnagrams(arr, n); return 0;}
// Java program to Print all pairs of// anagrams in a given array of stringspublic class GFG{ static final int NO_OF_CHARS = 256; /* function to check whether two strings are anagram of each other */ static boolean areAnagram(String str1, String str2) { // Create two count arrays and initialize // all values as 0 int[] count = new int[NO_OF_CHARS]; int i; // For each character in input strings, // increment count in the corresponding // count array for (i = 0; i < str1.length() && i < str2.length(); i++) { count[str1.charAt(i)]++; count[str2.charAt(i)]--; } // If both strings are of different length. // Removing this condition will make the program // fail for strings like "aaca" and "aca" if (str1.length() != str2.length()) return false; // See if there is any non-zero value in // count array for (i = 0; i < NO_OF_CHARS; i++) if (count[i] != 0) return false; return true; } // This function prints all anagram pairs in a // given array of strings static void findAllAnagrams(String arr[], int n) { for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) if (areAnagram(arr[i], arr[j])) System.out.println(arr[i] + " is anagram of " + arr[j]); } /* Driver program to test to print printDups*/ public static void main(String args[]) { String arr[] = {"geeksquiz", "geeksforgeeks", "abcd", "forgeeksgeeks", "zuiqkeegs"}; int n = arr.length; findAllAnagrams(arr, n); }}// This code is contributed by Sumit Ghosh
# Python3 program to find# best meeting point in 2D arrayNO_OF_CHARS = 256 # function to check whether two strings# are anagram of each otherdef areAnagram(str1: str, str2: str) -> bool: # Create two count arrays and # initialize all values as 0 count = [0] * NO_OF_CHARS i = 0 # For each character in input strings, # increment count in the corresponding # count array while i < len(str1) and i < len(str2): count[ord(str1[i])] += 1 count[ord(str2[i])] -= 1 i += 1 # If both strings are of different length. # Removing this condition will make the program # fail for strings like "aaca" and "aca" if len(str1) != len(str2): return False # See if there is any non-zero value # in count array for i in range(NO_OF_CHARS): if count[i]: return False return True # This function prints all anagram pairs# in a given array of stringsdef findAllAnagrams(arr: list, n: int): for i in range(n): for j in range(i + 1, n): if areAnagram(arr[i], arr[j]): print(arr[i], "is anagram of", arr[j]) # Driver Codeif __name__ == "__main__": arr = ["geeksquiz", "geeksforgeeks", "abcd", "forgeeksgeeks", "zuiqkeegs"] n = len(arr) findAllAnagrams(arr, n) # This code is contributed by# sanjeev2552
// C# program to Print all pairs of// anagrams in a given array of stringsusing System; class GFG{ static int NO_OF_CHARS = 256; /* function to check whether two strings are anagram of each other */ static bool areAnagram(String str1, String str2) { // Create two count arrays and initialize // all values as 0 int[] count = new int[NO_OF_CHARS]; int i; // For each character in input strings, // increment count in the corresponding // count array for (i = 0; i < str1.Length && i < str2.Length; i++) { count[str1[i]]++; count[str2[i]]--; } // If both strings are of different length. // Removing this condition will make the program // fail for strings like "aaca" and "aca" if (str1.Length != str2.Length) return false; // See if there is any non-zero value in // count array for (i = 0; i < NO_OF_CHARS; i++) if (count[i] != 0) return false; return true; } // This function prints all anagram pairs in a // given array of strings static void findAllAnagrams(String []arr, int n) { for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) if (areAnagram(arr[i], arr[j])) Console.WriteLine(arr[i] + " is anagram of " + arr[j]); } /* Driver program to test to print printDups*/ public static void Main() { String []arr = {"geeksquiz", "geeksforgeeks", "abcd", "forgeeksgeeks", "zuiqkeegs"}; int n = arr.Length; findAllAnagrams(arr, n); }} // This code is contributed by nitin mittal
<script>// JavaScript program to find// best meeting point in 2D arraylet NO_OF_CHARS = 256 // function to check whether two strings// are anagram of each otherfunction areAnagram(str1, str2){ // Create two count arrays and // initialize all values as 0 let count = []; for(let i = 0;i< NO_OF_CHARS;i++) count[i] = 0; let i = 0; // For each character in input strings, // increment count in the corresponding // count array while(i < (str1).length && i < (str2).length){ count[ord(str1[i])] += 1; count[ord(str2[i])] -= 1; i += 1; } // If both strings are of different length. // Removing this condition will make the program // fail for strings like "aaca" and "aca" if ( (str1).length != (str2).length) return false; // See if there is any non-zero value // in count array for(let i = 0; i < NO_OF_CHARS; i++){ if (count[i]) return false; return True; }} // This function prints all anagram pairs// in a given array of stringsfunction findAllAnagrams(arr, n){ for(let i = 0; i < n; i++){ for(let j = i + 1; j < n; j++){ if areAnagram(arr[i], arr[j]) document.write(arr[i]+"is anagram of"+arr[j]) } }} // Driver Code let arr = ["geeksquiz", "geeksforgeeks", "abcd", "forgeeksgeeks", "zuiqkeegs"]; let n = (arr).length; findAllAnagrams(arr, n); // This code is contributed by Rohitsingh07052.</script>
Output:
geeksquiz is anagram of zuiqkeegs
geeksforgeeks is anagram of forgeeksgeeks
The time complexity of the above solution is O(n2*m) where n is number of strings and m is maximum length of a string.
Auxiliary Space: O(1) or O(256).Optimizations: We can optimize the above solution using following approaches. 1) Using sorting: We can sort array of strings so that all anagrams come together. Then print all anagrams by linearly traversing the sorted array. The time complexity of this solution is O(mnLogn) (We would be doing O(nLogn) comparisons in sorting and a comparison would take O(m) time)2) Using Hashing: We can build a hash function like XOR or sum of ASCII values of all characters for a string. Using such a hash function, we can build a hash table. While building the hash table, we can check if a value is already hashed. If yes, we can call areAnagrams() to check if two strings are actually anagrams (Note that xor or sum of ASCII values is not sufficient, see Kaushik Lele’s comment here)This article is contributed by Abhishek. Please write comments if you find anything incorrect or want to share more information about above topic.
nitin mittal
sanjeev2552
rohitsingh07052
kk773572498
prachisoda1234
sagartomar9927
anandkumarshivam2266
anagram
Strings
Strings
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 135,
"s": 54,
"text": "Given an array of strings, find all anagram pairs in the given array. Example: "
},
{
"code": null,
"e": 301,
"s": 135,
"text": "Input: arr[] = {\"geeksquiz\", \"geeksforgeeks\", \"abcd\",\n \"forgeeksgeeks\", \"zuiqkeegs\"};\nOutput: (geeksforgeeks, forgeeksgeeks), (geeksquiz, zuiqkeegs)"
},
{
"code": null,
"e": 676,
"s": 301,
"text": "We can find whether two strings are anagram or not in linear time using count array (see method 2 of this). One simple idea to find whether all anagram pairs is to run two nested loops. The outer loop picks all strings one by one. The inner loop checks whether remaining strings are anagram of the string picked by outer loop. Below is the implementation of this approach : "
},
{
"code": null,
"e": 680,
"s": 676,
"text": "C++"
},
{
"code": null,
"e": 685,
"s": 680,
"text": "Java"
},
{
"code": null,
"e": 693,
"s": 685,
"text": "Python3"
},
{
"code": null,
"e": 696,
"s": 693,
"text": "C#"
},
{
"code": null,
"e": 707,
"s": 696,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;#define NO_OF_CHARS 256 /* function to check whether two strings are anagram of each other */bool areAnagram(string str1, string str2){ // Create two count arrays and initialize all values as 0 int count[NO_OF_CHARS] = {0}; int i; // For each character in input strings, increment count in // the corresponding count array for (i = 0; str1[i] && str2[i]; i++) { count[str1[i]]++; count[str2[i]]--; } // If both strings are of different length. Removing this condition // will make the program fail for strings like \"aaca\" and \"aca\" if (str1[i] || str2[i]) return false; // See if there is any non-zero value in count array for (i = 0; i < NO_OF_CHARS; i++) if (count[i]) return false; return true;} // This function prints all anagram pairs in a given array of stringsvoid findAllAnagrams(string arr[], int n){ for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) if (areAnagram(arr[i], arr[j])) cout << arr[i] << \" is anagram of \" << arr[j] << endl;} /* Driver program to test to print printDups*/int main(){ string arr[] = {\"geeksquiz\", \"geeksforgeeks\", \"abcd\", \"forgeeksgeeks\", \"zuiqkeegs\"}; int n = sizeof(arr)/sizeof(arr[0]); findAllAnagrams(arr, n); return 0;}",
"e": 2075,
"s": 707,
"text": null
},
{
"code": "// Java program to Print all pairs of// anagrams in a given array of stringspublic class GFG{ static final int NO_OF_CHARS = 256; /* function to check whether two strings are anagram of each other */ static boolean areAnagram(String str1, String str2) { // Create two count arrays and initialize // all values as 0 int[] count = new int[NO_OF_CHARS]; int i; // For each character in input strings, // increment count in the corresponding // count array for (i = 0; i < str1.length() && i < str2.length(); i++) { count[str1.charAt(i)]++; count[str2.charAt(i)]--; } // If both strings are of different length. // Removing this condition will make the program // fail for strings like \"aaca\" and \"aca\" if (str1.length() != str2.length()) return false; // See if there is any non-zero value in // count array for (i = 0; i < NO_OF_CHARS; i++) if (count[i] != 0) return false; return true; } // This function prints all anagram pairs in a // given array of strings static void findAllAnagrams(String arr[], int n) { for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) if (areAnagram(arr[i], arr[j])) System.out.println(arr[i] + \" is anagram of \" + arr[j]); } /* Driver program to test to print printDups*/ public static void main(String args[]) { String arr[] = {\"geeksquiz\", \"geeksforgeeks\", \"abcd\", \"forgeeksgeeks\", \"zuiqkeegs\"}; int n = arr.length; findAllAnagrams(arr, n); }}// This code is contributed by Sumit Ghosh",
"e": 3928,
"s": 2075,
"text": null
},
{
"code": "# Python3 program to find# best meeting point in 2D arrayNO_OF_CHARS = 256 # function to check whether two strings# are anagram of each otherdef areAnagram(str1: str, str2: str) -> bool: # Create two count arrays and # initialize all values as 0 count = [0] * NO_OF_CHARS i = 0 # For each character in input strings, # increment count in the corresponding # count array while i < len(str1) and i < len(str2): count[ord(str1[i])] += 1 count[ord(str2[i])] -= 1 i += 1 # If both strings are of different length. # Removing this condition will make the program # fail for strings like \"aaca\" and \"aca\" if len(str1) != len(str2): return False # See if there is any non-zero value # in count array for i in range(NO_OF_CHARS): if count[i]: return False return True # This function prints all anagram pairs# in a given array of stringsdef findAllAnagrams(arr: list, n: int): for i in range(n): for j in range(i + 1, n): if areAnagram(arr[i], arr[j]): print(arr[i], \"is anagram of\", arr[j]) # Driver Codeif __name__ == \"__main__\": arr = [\"geeksquiz\", \"geeksforgeeks\", \"abcd\", \"forgeeksgeeks\", \"zuiqkeegs\"] n = len(arr) findAllAnagrams(arr, n) # This code is contributed by# sanjeev2552",
"e": 5264,
"s": 3928,
"text": null
},
{
"code": "// C# program to Print all pairs of// anagrams in a given array of stringsusing System; class GFG{ static int NO_OF_CHARS = 256; /* function to check whether two strings are anagram of each other */ static bool areAnagram(String str1, String str2) { // Create two count arrays and initialize // all values as 0 int[] count = new int[NO_OF_CHARS]; int i; // For each character in input strings, // increment count in the corresponding // count array for (i = 0; i < str1.Length && i < str2.Length; i++) { count[str1[i]]++; count[str2[i]]--; } // If both strings are of different length. // Removing this condition will make the program // fail for strings like \"aaca\" and \"aca\" if (str1.Length != str2.Length) return false; // See if there is any non-zero value in // count array for (i = 0; i < NO_OF_CHARS; i++) if (count[i] != 0) return false; return true; } // This function prints all anagram pairs in a // given array of strings static void findAllAnagrams(String []arr, int n) { for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) if (areAnagram(arr[i], arr[j])) Console.WriteLine(arr[i] + \" is anagram of \" + arr[j]); } /* Driver program to test to print printDups*/ public static void Main() { String []arr = {\"geeksquiz\", \"geeksforgeeks\", \"abcd\", \"forgeeksgeeks\", \"zuiqkeegs\"}; int n = arr.Length; findAllAnagrams(arr, n); }} // This code is contributed by nitin mittal",
"e": 7042,
"s": 5264,
"text": null
},
{
"code": "<script>// JavaScript program to find// best meeting point in 2D arraylet NO_OF_CHARS = 256 // function to check whether two strings// are anagram of each otherfunction areAnagram(str1, str2){ // Create two count arrays and // initialize all values as 0 let count = []; for(let i = 0;i< NO_OF_CHARS;i++) count[i] = 0; let i = 0; // For each character in input strings, // increment count in the corresponding // count array while(i < (str1).length && i < (str2).length){ count[ord(str1[i])] += 1; count[ord(str2[i])] -= 1; i += 1; } // If both strings are of different length. // Removing this condition will make the program // fail for strings like \"aaca\" and \"aca\" if ( (str1).length != (str2).length) return false; // See if there is any non-zero value // in count array for(let i = 0; i < NO_OF_CHARS; i++){ if (count[i]) return false; return True; }} // This function prints all anagram pairs// in a given array of stringsfunction findAllAnagrams(arr, n){ for(let i = 0; i < n; i++){ for(let j = i + 1; j < n; j++){ if areAnagram(arr[i], arr[j]) document.write(arr[i]+\"is anagram of\"+arr[j]) } }} // Driver Code let arr = [\"geeksquiz\", \"geeksforgeeks\", \"abcd\", \"forgeeksgeeks\", \"zuiqkeegs\"]; let n = (arr).length; findAllAnagrams(arr, n); // This code is contributed by Rohitsingh07052.</script>",
"e": 8532,
"s": 7042,
"text": null
},
{
"code": null,
"e": 8542,
"s": 8532,
"text": "Output: "
},
{
"code": null,
"e": 8618,
"s": 8542,
"text": "geeksquiz is anagram of zuiqkeegs\ngeeksforgeeks is anagram of forgeeksgeeks"
},
{
"code": null,
"e": 8737,
"s": 8618,
"text": "The time complexity of the above solution is O(n2*m) where n is number of strings and m is maximum length of a string."
},
{
"code": null,
"e": 9690,
"s": 8737,
"text": "Auxiliary Space: O(1) or O(256).Optimizations: We can optimize the above solution using following approaches. 1) Using sorting: We can sort array of strings so that all anagrams come together. Then print all anagrams by linearly traversing the sorted array. The time complexity of this solution is O(mnLogn) (We would be doing O(nLogn) comparisons in sorting and a comparison would take O(m) time)2) Using Hashing: We can build a hash function like XOR or sum of ASCII values of all characters for a string. Using such a hash function, we can build a hash table. While building the hash table, we can check if a value is already hashed. If yes, we can call areAnagrams() to check if two strings are actually anagrams (Note that xor or sum of ASCII values is not sufficient, see Kaushik Lele’s comment here)This article is contributed by Abhishek. Please write comments if you find anything incorrect or want to share more information about above topic."
},
{
"code": null,
"e": 9703,
"s": 9690,
"text": "nitin mittal"
},
{
"code": null,
"e": 9715,
"s": 9703,
"text": "sanjeev2552"
},
{
"code": null,
"e": 9731,
"s": 9715,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 9743,
"s": 9731,
"text": "kk773572498"
},
{
"code": null,
"e": 9758,
"s": 9743,
"text": "prachisoda1234"
},
{
"code": null,
"e": 9773,
"s": 9758,
"text": "sagartomar9927"
},
{
"code": null,
"e": 9794,
"s": 9773,
"text": "anandkumarshivam2266"
},
{
"code": null,
"e": 9802,
"s": 9794,
"text": "anagram"
},
{
"code": null,
"e": 9810,
"s": 9802,
"text": "Strings"
},
{
"code": null,
"e": 9818,
"s": 9810,
"text": "Strings"
},
{
"code": null,
"e": 9826,
"s": 9818,
"text": "anagram"
}
] |
Optimum location of point to minimize total distance | 25 Jun, 2022
Given a set of points as and a line as ax+by+c = 0. We need to find a point on given line for which sum of distances from given set of points is minimum.
Example:
In above figure optimum location of point of x - y - 3 = 0 line
is (2, -1), whose total distance with other points is 20.77,
which is minimum obtainable total distance.
If we take one point on given line at infinite distance then total distance cost will be infinite, now when we move this point on line towards given points the total distance cost starts decreasing and after some time, it again starts increasing which reached to infinite on the other infinite end of line so distance cost curve looks like a U-curve and we have to find the bottom value of this U-curve.
As U-curve is not monotonically increasing or decreasing we can’t use binary search for finding bottom most point, here we will use ternary search for finding bottom most point, ternary search skips one third of search space at each iteration, you can read more about ternary search here.
So solution proceeds as follows, we start with low and high initialized as some smallest and largest values respectively, then we start iteration, in each iteration we calculate two mids, mid1 and mid2, which represent 1/3rd and 2/3rd position in search space, we calculate total distance of all points with mid1 and mid2 and update low or high by comparing these distance cost, this iteration continues until low and high become approximately equal.
C++
Java
Python3
C#
Javascript
// C/C++ program to find optimum location and total cost#include <bits/stdc++.h>using namespace std;#define sq(x) ((x) * (x))#define EPS 1e-6#define N 5 // structure defining a pointstruct point { int x, y; point() {} point(int x, int y) : x(x) , y(y) { }}; // structure defining a line of ax + by + c = 0 formstruct line { int a, b, c; line(int a, int b, int c) : a(a) , b(b) , c(c) { }}; // method to get distance of point (x, y) from point pdouble dist(double x, double y, point p){ return sqrt(sq(x - p.x) + sq(y - p.y));} /* Utility method to compute total distance all points when choose point on given line has x-coordinate value as X */double compute(point p[], int n, line l, double X){ double res = 0; // calculating Y of chosen point by line equation double Y = -1 * (l.c + l.a * X) / l.b; for (int i = 0; i < n; i++) res += dist(X, Y, p[i]); return res;} // Utility method to find minimum total distancedouble findOptimumCostUtil(point p[], int n, line l){ double low = -1e6; double high = 1e6; // loop until difference between low and high // become less than EPS while ((high - low) > EPS) { // mid1 and mid2 are representative x co-ordiantes // of search space double mid1 = low + (high - low) / 3; double mid2 = high - (high - low) / 3; // double dist1 = compute(p, n, l, mid1); double dist2 = compute(p, n, l, mid2); // if mid2 point gives more total distance, // skip third part if (dist1 < dist2) high = mid2; // if mid1 point gives more total distance, // skip first part else low = mid1; } // compute optimum distance cost by sending average // of low and high as X return compute(p, n, l, (low + high) / 2);} // method to find optimum costdouble findOptimumCost(int points[N][2], line l){ point p[N]; // converting 2D array input to point array for (int i = 0; i < N; i++) p[i] = point(points[i][0], points[i][1]); return findOptimumCostUtil(p, N, l);} // Driver code to test above methodint main(){ line l(1, -1, -3); int points[N][2] = { { -3, -2 }, { -1, 0 }, { -1, 2 }, { 1, 2 }, { 3, 4 } }; cout << findOptimumCost(points, l) << endl; return 0;}
// A Java program to find optimum location// and total costclass GFG { static double sq(double x) { return ((x) * (x)); } static int EPS = (int)(1e-6) + 1; static int N = 5; // structure defining a point static class point { int x, y; point() {} public point(int x, int y) { this.x = x; this.y = y; } }; // structure defining a line of ax + by + c = 0 form static class line { int a, b, c; public line(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } }; // method to get distance of point (x, y) from point p static double dist(double x, double y, point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } /* Utility method to compute total distance all points when choose point on given line has x-coordinate value as X */ static double compute(point p[], int n, line l, double X) { double res = 0; // calculating Y of chosen point by line equation double Y = -1 * (l.c + l.a * X) / l.b; for (int i = 0; i < n; i++) res += dist(X, Y, p[i]); return res; } // Utility method to find minimum total distance static double findOptimumCostUtil(point p[], int n, line l) { double low = -1e6; double high = 1e6; // loop until difference between low and high // become less than EPS while ((high - low) > EPS) { // mid1 and mid2 are representative x // co-ordiantes of search space double mid1 = low + (high - low) / 3; double mid2 = high - (high - low) / 3; double dist1 = compute(p, n, l, mid1); double dist2 = compute(p, n, l, mid2); // if mid2 point gives more total distance, // skip third part if (dist1 < dist2) high = mid2; // if mid1 point gives more total distance, // skip first part else low = mid1; } // compute optimum distance cost by sending average // of low and high as X return compute(p, n, l, (low + high) / 2); } // method to find optimum cost static double findOptimumCost(int points[][], line l) { point[] p = new point[N]; // converting 2D array input to point array for (int i = 0; i < N; i++) p[i] = new point(points[i][0], points[i][1]); return findOptimumCostUtil(p, N, l); } // Driver Code public static void main(String[] args) { line l = new line(1, -1, -3); int points[][] = { { -3, -2 }, { -1, 0 }, { -1, 2 }, { 1, 2 }, { 3, 4 } }; System.out.println(findOptimumCost(points, l)); }} // This code is contributed by Rajput-Ji
# A Python3 program to find optimum location# and total costimport math class Optimum_distance: # Class defining a point class Point: def __init__(self, x, y): self.x = x self.y = y # Class defining a line of ax + by + c = 0 form class Line: def __init__(self, a, b, c): self.a = a self.b = b self.c = c # Method to get distance of point # (x, y) from point p def dist(self, x, y, p): return math.sqrt((x - p.x) ** 2 + (y - p.y) ** 2) # Utility method to compute total distance # all points when choose point on given # line has x-coordinate value as X def compute(self, p, n, l, x): res = 0 y = -1 * (l.a*x + l.c) / l.b # Calculating Y of chosen point # by line equation for i in range(n): res += self.dist(x, y, p[i]) return res # Utility method to find minimum total distance def find_Optimum_cost_untill(self, p, n, l): low = -1e6 high = 1e6 eps = 1e-6 + 1 # Loop until difference between low # and high become less than EPS while((high - low) > eps): # mid1 and mid2 are representative x # co-ordiantes of search space mid1 = low + (high - low) / 3 mid2 = high - (high - low) / 3 dist1 = self.compute(p, n, l, mid1) dist2 = self.compute(p, n, l, mid2) # If mid2 point gives more total # distance, skip third part if (dist1 < dist2): high = mid2 # If mid1 point gives more total # distance, skip first part else: low = mid1 # Compute optimum distance cost by # sending average of low and high as X return self.compute(p, n, l, (low + high) / 2) # Method to find optimum cost def find_Optimum_cost(self, p, l): n = len(p) p_arr = [None] * n # Converting 2D array input to point array for i in range(n): p_obj = self.Point(p[i][0], p[i][1]) p_arr[i] = p_obj return self.find_Optimum_cost_untill(p_arr, n, l) # Driver Codeif __name__ == "__main__": obj = Optimum_distance() l = obj.Line(1, -1, -3) p = [ [ -3, -2 ], [ -1, 0 ], [ -1, 2 ], [ 1, 2 ], [ 3, 4 ] ] print(obj.find_Optimum_cost(p, l)) # This code is contributed by Sulu_mufi
// C# program to find optimum location// and total costusing System; class GFG { static double sq(double x) { return ((x) * (x)); } static int EPS = (int)(1e-6) + 1; static int N = 5; // structure defining a point public class point { public int x, y; public point() {} public point(int x, int y) { this.x = x; this.y = y; } }; // structure defining a line // of ax + by + c = 0 form public class line { public int a, b, c; public line(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } }; // method to get distance of // point (x, y) from point p static double dist(double x, double y, point p) { return Math.Sqrt(sq(x - p.x) + sq(y - p.y)); } /* Utility method to compute total distance of all points when choose point on given line has x-coordinate value as X */ static double compute(point[] p, int n, line l, double X) { double res = 0; // calculating Y of chosen point // by line equation double Y = -1 * (l.c + l.a * X) / l.b; for (int i = 0; i < n; i++) res += dist(X, Y, p[i]); return res; } // Utility method to find minimum total distance static double findOptimumCostUtil(point[] p, int n, line l) { double low = -1e6; double high = 1e6; // loop until difference between // low and high become less than EPS while ((high - low) > EPS) { // mid1 and mid2 are representative // x co-ordiantes of search space double mid1 = low + (high - low) / 3; double mid2 = high - (high - low) / 3; double dist1 = compute(p, n, l, mid1); double dist2 = compute(p, n, l, mid2); // if mid2 point gives more total distance, // skip third part if (dist1 < dist2) high = mid2; // if mid1 point gives more total distance, // skip first part else low = mid1; } // compute optimum distance cost by // sending average of low and high as X return compute(p, n, l, (low + high) / 2); } // method to find optimum cost static double findOptimumCost(int[, ] points, line l) { point[] p = new point[N]; // converting 2D array input to point array for (int i = 0; i < N; i++) p[i] = new point(points[i, 0], points[i, 1]); return findOptimumCostUtil(p, N, l); } // Driver Code public static void Main(String[] args) { line l = new line(1, -1, -3); int[, ] points = { { -3, -2 }, { -1, 0 }, { -1, 2 }, { 1, 2 }, { 3, 4 } }; Console.WriteLine(findOptimumCost(points, l)); }} // This code is contributed by 29AjayKumar
<script> // A JavaScript program to find optimum location// and total cost function sq(x){ return x*x;} let EPS = (1e-6) + 1;let N = 5; // structure defining a pointclass point{ constructor(x,y) { this.x=x; this.y=y; }} // structure defining a line of ax + by + c = 0 formclass line{ constructor(a,b,c) { this.a = a; this.b = b; this.c = c; } } // method to get distance of point (x, y) from point pfunction dist(x,y,p){ return Math.sqrt(sq(x - p.x) + sq(y - p.y));} /* Utility method to compute total distance all points when choose point on given line has x-coordinate value as X */function compute(p,n,l,X){ let res = 0; // calculating Y of chosen point by line equation let Y = -1 * (l.c + l.a * X) / l.b; for (let i = 0; i < n; i++) res += dist(X, Y, p[i]); return res;}// Utility method to find minimum total distancefunction findOptimumCostUtil(p,n,l){ let low = -1e6; let high = 1e6; // loop until difference between low and high // become less than EPS while ((high - low) > EPS) { // mid1 and mid2 are representative x // co-ordiantes of search space let mid1 = low + (high - low) / 3; let mid2 = high - (high - low) / 3; let dist1 = compute(p, n, l, mid1); let dist2 = compute(p, n, l, mid2); // if mid2 point gives more total distance, // skip third part if (dist1 < dist2) high = mid2; // if mid1 point gives more total distance, // skip first part else low = mid1; } // compute optimum distance cost by sending average // of low and high as X return compute(p, n, l, (low + high) / 2);} // method to find optimum costfunction findOptimumCost(points,l){ let p = new Array(N); // converting 2D array input to point array for (let i = 0; i < N; i++) p[i] = new point(points[i][0], points[i][1]); return findOptimumCostUtil(p, N, l);} // Driver Codelet l = new line(1, -1, -3);let points= [[ -3, -2 ], [ -1, 0 ], [ -1, 2 ], [ 1, 2 ], [ 3, 4 ]];document.write(findOptimumCost(points, l)); // This code is contributed by rag2127 </script>
20.7652
Time Complexity: O(n2) Auxiliary Space: O(n)
This article is contributed by Aarti_Rathi and 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rajput-Ji
29AjayKumar
suluksm
sumitgumber28
rag2127
ruhelaa48
akshaysingh98088
_shinchancode
Geometric
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Jun, 2022"
},
{
"code": null,
"e": 207,
"s": 52,
"text": "Given a set of points as and a line as ax+by+c = 0. We need to find a point on given line for which sum of distances from given set of points is minimum. "
},
{
"code": null,
"e": 217,
"s": 207,
"text": "Example: "
},
{
"code": null,
"e": 388,
"s": 217,
"text": "In above figure optimum location of point of x - y - 3 = 0 line \nis (2, -1), whose total distance with other points is 20.77, \nwhich is minimum obtainable total distance."
},
{
"code": null,
"e": 793,
"s": 388,
"text": "If we take one point on given line at infinite distance then total distance cost will be infinite, now when we move this point on line towards given points the total distance cost starts decreasing and after some time, it again starts increasing which reached to infinite on the other infinite end of line so distance cost curve looks like a U-curve and we have to find the bottom value of this U-curve. "
},
{
"code": null,
"e": 1083,
"s": 793,
"text": "As U-curve is not monotonically increasing or decreasing we can’t use binary search for finding bottom most point, here we will use ternary search for finding bottom most point, ternary search skips one third of search space at each iteration, you can read more about ternary search here. "
},
{
"code": null,
"e": 1535,
"s": 1083,
"text": "So solution proceeds as follows, we start with low and high initialized as some smallest and largest values respectively, then we start iteration, in each iteration we calculate two mids, mid1 and mid2, which represent 1/3rd and 2/3rd position in search space, we calculate total distance of all points with mid1 and mid2 and update low or high by comparing these distance cost, this iteration continues until low and high become approximately equal. "
},
{
"code": null,
"e": 1539,
"s": 1535,
"text": "C++"
},
{
"code": null,
"e": 1544,
"s": 1539,
"text": "Java"
},
{
"code": null,
"e": 1552,
"s": 1544,
"text": "Python3"
},
{
"code": null,
"e": 1555,
"s": 1552,
"text": "C#"
},
{
"code": null,
"e": 1566,
"s": 1555,
"text": "Javascript"
},
{
"code": "// C/C++ program to find optimum location and total cost#include <bits/stdc++.h>using namespace std;#define sq(x) ((x) * (x))#define EPS 1e-6#define N 5 // structure defining a pointstruct point { int x, y; point() {} point(int x, int y) : x(x) , y(y) { }}; // structure defining a line of ax + by + c = 0 formstruct line { int a, b, c; line(int a, int b, int c) : a(a) , b(b) , c(c) { }}; // method to get distance of point (x, y) from point pdouble dist(double x, double y, point p){ return sqrt(sq(x - p.x) + sq(y - p.y));} /* Utility method to compute total distance all points when choose point on given line has x-coordinate value as X */double compute(point p[], int n, line l, double X){ double res = 0; // calculating Y of chosen point by line equation double Y = -1 * (l.c + l.a * X) / l.b; for (int i = 0; i < n; i++) res += dist(X, Y, p[i]); return res;} // Utility method to find minimum total distancedouble findOptimumCostUtil(point p[], int n, line l){ double low = -1e6; double high = 1e6; // loop until difference between low and high // become less than EPS while ((high - low) > EPS) { // mid1 and mid2 are representative x co-ordiantes // of search space double mid1 = low + (high - low) / 3; double mid2 = high - (high - low) / 3; // double dist1 = compute(p, n, l, mid1); double dist2 = compute(p, n, l, mid2); // if mid2 point gives more total distance, // skip third part if (dist1 < dist2) high = mid2; // if mid1 point gives more total distance, // skip first part else low = mid1; } // compute optimum distance cost by sending average // of low and high as X return compute(p, n, l, (low + high) / 2);} // method to find optimum costdouble findOptimumCost(int points[N][2], line l){ point p[N]; // converting 2D array input to point array for (int i = 0; i < N; i++) p[i] = point(points[i][0], points[i][1]); return findOptimumCostUtil(p, N, l);} // Driver code to test above methodint main(){ line l(1, -1, -3); int points[N][2] = { { -3, -2 }, { -1, 0 }, { -1, 2 }, { 1, 2 }, { 3, 4 } }; cout << findOptimumCost(points, l) << endl; return 0;}",
"e": 3934,
"s": 1566,
"text": null
},
{
"code": "// A Java program to find optimum location// and total costclass GFG { static double sq(double x) { return ((x) * (x)); } static int EPS = (int)(1e-6) + 1; static int N = 5; // structure defining a point static class point { int x, y; point() {} public point(int x, int y) { this.x = x; this.y = y; } }; // structure defining a line of ax + by + c = 0 form static class line { int a, b, c; public line(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } }; // method to get distance of point (x, y) from point p static double dist(double x, double y, point p) { return Math.sqrt(sq(x - p.x) + sq(y - p.y)); } /* Utility method to compute total distance all points when choose point on given line has x-coordinate value as X */ static double compute(point p[], int n, line l, double X) { double res = 0; // calculating Y of chosen point by line equation double Y = -1 * (l.c + l.a * X) / l.b; for (int i = 0; i < n; i++) res += dist(X, Y, p[i]); return res; } // Utility method to find minimum total distance static double findOptimumCostUtil(point p[], int n, line l) { double low = -1e6; double high = 1e6; // loop until difference between low and high // become less than EPS while ((high - low) > EPS) { // mid1 and mid2 are representative x // co-ordiantes of search space double mid1 = low + (high - low) / 3; double mid2 = high - (high - low) / 3; double dist1 = compute(p, n, l, mid1); double dist2 = compute(p, n, l, mid2); // if mid2 point gives more total distance, // skip third part if (dist1 < dist2) high = mid2; // if mid1 point gives more total distance, // skip first part else low = mid1; } // compute optimum distance cost by sending average // of low and high as X return compute(p, n, l, (low + high) / 2); } // method to find optimum cost static double findOptimumCost(int points[][], line l) { point[] p = new point[N]; // converting 2D array input to point array for (int i = 0; i < N; i++) p[i] = new point(points[i][0], points[i][1]); return findOptimumCostUtil(p, N, l); } // Driver Code public static void main(String[] args) { line l = new line(1, -1, -3); int points[][] = { { -3, -2 }, { -1, 0 }, { -1, 2 }, { 1, 2 }, { 3, 4 } }; System.out.println(findOptimumCost(points, l)); }} // This code is contributed by Rajput-Ji",
"e": 6937,
"s": 3934,
"text": null
},
{
"code": "# A Python3 program to find optimum location# and total costimport math class Optimum_distance: # Class defining a point class Point: def __init__(self, x, y): self.x = x self.y = y # Class defining a line of ax + by + c = 0 form class Line: def __init__(self, a, b, c): self.a = a self.b = b self.c = c # Method to get distance of point # (x, y) from point p def dist(self, x, y, p): return math.sqrt((x - p.x) ** 2 + (y - p.y) ** 2) # Utility method to compute total distance # all points when choose point on given # line has x-coordinate value as X def compute(self, p, n, l, x): res = 0 y = -1 * (l.a*x + l.c) / l.b # Calculating Y of chosen point # by line equation for i in range(n): res += self.dist(x, y, p[i]) return res # Utility method to find minimum total distance def find_Optimum_cost_untill(self, p, n, l): low = -1e6 high = 1e6 eps = 1e-6 + 1 # Loop until difference between low # and high become less than EPS while((high - low) > eps): # mid1 and mid2 are representative x # co-ordiantes of search space mid1 = low + (high - low) / 3 mid2 = high - (high - low) / 3 dist1 = self.compute(p, n, l, mid1) dist2 = self.compute(p, n, l, mid2) # If mid2 point gives more total # distance, skip third part if (dist1 < dist2): high = mid2 # If mid1 point gives more total # distance, skip first part else: low = mid1 # Compute optimum distance cost by # sending average of low and high as X return self.compute(p, n, l, (low + high) / 2) # Method to find optimum cost def find_Optimum_cost(self, p, l): n = len(p) p_arr = [None] * n # Converting 2D array input to point array for i in range(n): p_obj = self.Point(p[i][0], p[i][1]) p_arr[i] = p_obj return self.find_Optimum_cost_untill(p_arr, n, l) # Driver Codeif __name__ == \"__main__\": obj = Optimum_distance() l = obj.Line(1, -1, -3) p = [ [ -3, -2 ], [ -1, 0 ], [ -1, 2 ], [ 1, 2 ], [ 3, 4 ] ] print(obj.find_Optimum_cost(p, l)) # This code is contributed by Sulu_mufi",
"e": 9683,
"s": 6937,
"text": null
},
{
"code": "// C# program to find optimum location// and total costusing System; class GFG { static double sq(double x) { return ((x) * (x)); } static int EPS = (int)(1e-6) + 1; static int N = 5; // structure defining a point public class point { public int x, y; public point() {} public point(int x, int y) { this.x = x; this.y = y; } }; // structure defining a line // of ax + by + c = 0 form public class line { public int a, b, c; public line(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } }; // method to get distance of // point (x, y) from point p static double dist(double x, double y, point p) { return Math.Sqrt(sq(x - p.x) + sq(y - p.y)); } /* Utility method to compute total distance of all points when choose point on given line has x-coordinate value as X */ static double compute(point[] p, int n, line l, double X) { double res = 0; // calculating Y of chosen point // by line equation double Y = -1 * (l.c + l.a * X) / l.b; for (int i = 0; i < n; i++) res += dist(X, Y, p[i]); return res; } // Utility method to find minimum total distance static double findOptimumCostUtil(point[] p, int n, line l) { double low = -1e6; double high = 1e6; // loop until difference between // low and high become less than EPS while ((high - low) > EPS) { // mid1 and mid2 are representative // x co-ordiantes of search space double mid1 = low + (high - low) / 3; double mid2 = high - (high - low) / 3; double dist1 = compute(p, n, l, mid1); double dist2 = compute(p, n, l, mid2); // if mid2 point gives more total distance, // skip third part if (dist1 < dist2) high = mid2; // if mid1 point gives more total distance, // skip first part else low = mid1; } // compute optimum distance cost by // sending average of low and high as X return compute(p, n, l, (low + high) / 2); } // method to find optimum cost static double findOptimumCost(int[, ] points, line l) { point[] p = new point[N]; // converting 2D array input to point array for (int i = 0; i < N; i++) p[i] = new point(points[i, 0], points[i, 1]); return findOptimumCostUtil(p, N, l); } // Driver Code public static void Main(String[] args) { line l = new line(1, -1, -3); int[, ] points = { { -3, -2 }, { -1, 0 }, { -1, 2 }, { 1, 2 }, { 3, 4 } }; Console.WriteLine(findOptimumCost(points, l)); }} // This code is contributed by 29AjayKumar",
"e": 12736,
"s": 9683,
"text": null
},
{
"code": "<script> // A JavaScript program to find optimum location// and total cost function sq(x){ return x*x;} let EPS = (1e-6) + 1;let N = 5; // structure defining a pointclass point{ constructor(x,y) { this.x=x; this.y=y; }} // structure defining a line of ax + by + c = 0 formclass line{ constructor(a,b,c) { this.a = a; this.b = b; this.c = c; } } // method to get distance of point (x, y) from point pfunction dist(x,y,p){ return Math.sqrt(sq(x - p.x) + sq(y - p.y));} /* Utility method to compute total distance all points when choose point on given line has x-coordinate value as X */function compute(p,n,l,X){ let res = 0; // calculating Y of chosen point by line equation let Y = -1 * (l.c + l.a * X) / l.b; for (let i = 0; i < n; i++) res += dist(X, Y, p[i]); return res;}// Utility method to find minimum total distancefunction findOptimumCostUtil(p,n,l){ let low = -1e6; let high = 1e6; // loop until difference between low and high // become less than EPS while ((high - low) > EPS) { // mid1 and mid2 are representative x // co-ordiantes of search space let mid1 = low + (high - low) / 3; let mid2 = high - (high - low) / 3; let dist1 = compute(p, n, l, mid1); let dist2 = compute(p, n, l, mid2); // if mid2 point gives more total distance, // skip third part if (dist1 < dist2) high = mid2; // if mid1 point gives more total distance, // skip first part else low = mid1; } // compute optimum distance cost by sending average // of low and high as X return compute(p, n, l, (low + high) / 2);} // method to find optimum costfunction findOptimumCost(points,l){ let p = new Array(N); // converting 2D array input to point array for (let i = 0; i < N; i++) p[i] = new point(points[i][0], points[i][1]); return findOptimumCostUtil(p, N, l);} // Driver Codelet l = new line(1, -1, -3);let points= [[ -3, -2 ], [ -1, 0 ], [ -1, 2 ], [ 1, 2 ], [ 3, 4 ]];document.write(findOptimumCost(points, l)); // This code is contributed by rag2127 </script>",
"e": 15134,
"s": 12736,
"text": null
},
{
"code": null,
"e": 15142,
"s": 15134,
"text": "20.7652"
},
{
"code": null,
"e": 15187,
"s": 15142,
"text": "Time Complexity: O(n2) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 15627,
"s": 15187,
"text": "This article is contributed by Aarti_Rathi and 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 15637,
"s": 15627,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 15649,
"s": 15637,
"text": "29AjayKumar"
},
{
"code": null,
"e": 15657,
"s": 15649,
"text": "suluksm"
},
{
"code": null,
"e": 15671,
"s": 15657,
"text": "sumitgumber28"
},
{
"code": null,
"e": 15679,
"s": 15671,
"text": "rag2127"
},
{
"code": null,
"e": 15689,
"s": 15679,
"text": "ruhelaa48"
},
{
"code": null,
"e": 15706,
"s": 15689,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 15720,
"s": 15706,
"text": "_shinchancode"
},
{
"code": null,
"e": 15730,
"s": 15720,
"text": "Geometric"
},
{
"code": null,
"e": 15740,
"s": 15730,
"text": "Geometric"
}
] |
How to Change the Background Color After Clicking the Button in Android? | 14 May, 2021
In this article, we will see how we can change the background of the screen by clicking a button. For this, we will be using the onClick() method. When we click on the button the onClick function is called. To set the click handler event for the button we need to define the android:onClick attribute in the XML file. We can also use onClickListener() in the Java file to call this function programmatically when the button is clicked. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Define Colors
It is always better to pre-define strings and colors instead of hard coding them hence we will define the colors.
Open the colors.xml file by navigating to the app -> res -> values -> colors.xml
Create a color tag inside the resources tag with a name and set a color with its hex code.
Add the below lines inside the colors.xml file.
XML
<color name="colorPrimary">#6200EE</color><color name="colorPrimaryDark">#3700B3</color><color name="colorAccent">#03DAC5</color><color name="green">#0F9D58</color><color name="cool">#188FCF</color><color name="warm">#F1D416</color>
Step 3: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rlVar1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/green" tools:context=".MainActivity"> <TextView android:id="@+id/tvVar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="240dp" android:text="What whould you like?" android:textSize="30dp" android:textStyle="bold" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tvVar1" android:layout_centerInParent="true" android:layout_marginTop="60dp" android:orientation="horizontal" android:padding="10dp"> <Button android:id="@+id/btVar1" android:layout_width="150dp" android:layout_height="wrap_content" android:padding="20dp" android:text="Cool" android:textSize="25dp" /> <Button android:id="@+id/btVar2" android:layout_width="150dp" android:layout_height="wrap_content" android:padding="20dp" android:text="Warm" android:textSize="25dp" /> </LinearLayout> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Set onClick() attribute with a function name android:onClick=”changeBackground”,
After that in your activity that hosts this layout create a function with the same name, or
You can instead of using the onClick() attribute directly set the onClickListener() and code its function
Inside the function use setBackgroundResource(R.color.button_color) function, this will set the background with color button_color.
Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.RelativeLayout; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button1, button2; final RelativeLayout relativeLayout; // set button 1 with its id button1 = findViewById(R.id.btVar1); // set button 2 with its id button2 = findViewById(R.id.btVar2); // set relative layout with its id relativeLayout = findViewById(R.id.rlVar1); // onClick function for button 1 button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // set the color to relative layout relativeLayout.setBackgroundResource(R.color.cool); } }); // onClick function for button 2 button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // set the color to relative layout relativeLayout.setBackgroundResource(R.color.warm); } }); }}
Output:
clintra
Android-Button
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Navigation Drawer in Android
How to Create and Add Data to SQLite Database in Android?
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 653,
"s": 52,
"text": "In this article, we will see how we can change the background of the screen by clicking a button. For this, we will be using the onClick() method. When we click on the button the onClick function is called. To set the click handler event for the button we need to define the android:onClick attribute in the XML file. We can also use onClickListener() in the Java file to call this function programmatically when the button is clicked. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 682,
"s": 653,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 844,
"s": 682,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 866,
"s": 844,
"text": "Step 2: Define Colors"
},
{
"code": null,
"e": 980,
"s": 866,
"text": "It is always better to pre-define strings and colors instead of hard coding them hence we will define the colors."
},
{
"code": null,
"e": 1061,
"s": 980,
"text": "Open the colors.xml file by navigating to the app -> res -> values -> colors.xml"
},
{
"code": null,
"e": 1152,
"s": 1061,
"text": "Create a color tag inside the resources tag with a name and set a color with its hex code."
},
{
"code": null,
"e": 1200,
"s": 1152,
"text": "Add the below lines inside the colors.xml file."
},
{
"code": null,
"e": 1204,
"s": 1200,
"text": "XML"
},
{
"code": "<color name=\"colorPrimary\">#6200EE</color><color name=\"colorPrimaryDark\">#3700B3</color><color name=\"colorAccent\">#03DAC5</color><color name=\"green\">#0F9D58</color><color name=\"cool\">#188FCF</color><color name=\"warm\">#F1D416</color>",
"e": 1437,
"s": 1204,
"text": null
},
{
"code": null,
"e": 1486,
"s": 1437,
"text": " Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1602,
"s": 1486,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 1606,
"s": 1602,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/rlVar1\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/green\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/tvVar1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"240dp\" android:text=\"What whould you like?\" android:textSize=\"30dp\" android:textStyle=\"bold\" /> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/tvVar1\" android:layout_centerInParent=\"true\" android:layout_marginTop=\"60dp\" android:orientation=\"horizontal\" android:padding=\"10dp\"> <Button android:id=\"@+id/btVar1\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:padding=\"20dp\" android:text=\"Cool\" android:textSize=\"25dp\" /> <Button android:id=\"@+id/btVar2\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:padding=\"20dp\" android:text=\"Warm\" android:textSize=\"25dp\" /> </LinearLayout> </RelativeLayout>",
"e": 3104,
"s": 1606,
"text": null
},
{
"code": null,
"e": 3153,
"s": 3104,
"text": "Step 4: Working with the MainActivity.java file "
},
{
"code": null,
"e": 3234,
"s": 3153,
"text": "Set onClick() attribute with a function name android:onClick=”changeBackground”,"
},
{
"code": null,
"e": 3326,
"s": 3234,
"text": "After that in your activity that hosts this layout create a function with the same name, or"
},
{
"code": null,
"e": 3432,
"s": 3326,
"text": "You can instead of using the onClick() attribute directly set the onClickListener() and code its function"
},
{
"code": null,
"e": 3564,
"s": 3432,
"text": "Inside the function use setBackgroundResource(R.color.button_color) function, this will set the background with color button_color."
},
{
"code": null,
"e": 3689,
"s": 3564,
"text": "Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 3694,
"s": 3689,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.RelativeLayout; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button1, button2; final RelativeLayout relativeLayout; // set button 1 with its id button1 = findViewById(R.id.btVar1); // set button 2 with its id button2 = findViewById(R.id.btVar2); // set relative layout with its id relativeLayout = findViewById(R.id.rlVar1); // onClick function for button 1 button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // set the color to relative layout relativeLayout.setBackgroundResource(R.color.cool); } }); // onClick function for button 2 button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // set the color to relative layout relativeLayout.setBackgroundResource(R.color.warm); } }); }}",
"e": 5081,
"s": 3694,
"text": null
},
{
"code": null,
"e": 5089,
"s": 5081,
"text": "Output:"
},
{
"code": null,
"e": 5099,
"s": 5091,
"text": "clintra"
},
{
"code": null,
"e": 5114,
"s": 5099,
"text": "Android-Button"
},
{
"code": null,
"e": 5122,
"s": 5114,
"text": "Android"
},
{
"code": null,
"e": 5127,
"s": 5122,
"text": "Java"
},
{
"code": null,
"e": 5132,
"s": 5127,
"text": "Java"
},
{
"code": null,
"e": 5140,
"s": 5132,
"text": "Android"
},
{
"code": null,
"e": 5238,
"s": 5140,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5270,
"s": 5238,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 5301,
"s": 5270,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 5344,
"s": 5301,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 5373,
"s": 5344,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 5431,
"s": 5373,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 5446,
"s": 5431,
"text": "Arrays in Java"
},
{
"code": null,
"e": 5490,
"s": 5446,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 5526,
"s": 5490,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 5577,
"s": 5526,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Binding rows and columns of a Data Frame in R – bind_rows() and bind_cols() Function | 26 May, 2020
bind_rows() function in R Programming is used to combine rows of two data frames.
Syntax:bind_rows(data1, data2, id)
Parameter:id: dataframe identifierdata1, data2: data frame to combine
Example: Combining Rows
# R program to illustrate# combine rows # Install dplyr packageinstall.packages("dplyr") # Load dplyr package library("dplyr") # Create three data framesdata1 <- data.frame(x1 = 1:5, x2 = letters[1:5])data2 <- data.frame(x1 = 0, x3 = 5:9)data3 <- data.frame(x3 = 5:9, x4 = letters[5:9]) # Apply bind_rows functionbind_rows(data1, data2, id = NULL)
Output:
x1 x2 x3
1 1 a NA
2 2 b NA
3 3 c NA
4 4 d NA
5 5 e NA
6 0 5
7 0 6
8 0 7
9 0 8
10 0 9
Here in the above code, we created 3 data frames data1, data2, data3 with rows and columns in it and then we use bind_rows() function to combine the rows that were present in the data frame. Also where the variable name is not listed bind_rows() inserted NA value.
bind_cols() function is used to combine columns of two data frames.
Syntax:bind_cols(data1, data2, id)
Parameter:id: dataframe identifierdata1, data2: data frame to combine
Example: Combining Columns
# R program to illustrate# combine rows # Install dplyr packageinstall.packages("dplyr") # Load dplyr package library("dplyr") # Create three data framesdata1 <- data.frame(x1 = 1:5, x2 = letters[1:5])data2 <- data.frame(x1 = 0, x3 = 5:9)data3 <- data.frame(x3 = 5:9, x4 = letters[5:9]) # Apply bind_cols functionbind_cols(data1, data3, id = NULL)
Output:
x1 x2 x3 x4
1 1 a 5 e
2 2 b 6 f
3 3 c 7 g
4 4 d 8 h
5 5 e 9 i
Here in the above code we have created 3 data frames and then combine their columns by using bind_cols() function.Here we have combined the var. x1, x2 of data1 and x3, x4 of data2 with each other.
Programming Language
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 110,
"s": 28,
"text": "bind_rows() function in R Programming is used to combine rows of two data frames."
},
{
"code": null,
"e": 145,
"s": 110,
"text": "Syntax:bind_rows(data1, data2, id)"
},
{
"code": null,
"e": 215,
"s": 145,
"text": "Parameter:id: dataframe identifierdata1, data2: data frame to combine"
},
{
"code": null,
"e": 239,
"s": 215,
"text": "Example: Combining Rows"
},
{
"code": "# R program to illustrate# combine rows # Install dplyr packageinstall.packages(\"dplyr\") # Load dplyr package library(\"dplyr\") # Create three data framesdata1 <- data.frame(x1 = 1:5, x2 = letters[1:5])data2 <- data.frame(x1 = 0, x3 = 5:9)data3 <- data.frame(x3 = 5:9, x4 = letters[5:9]) # Apply bind_rows functionbind_rows(data1, data2, id = NULL) ",
"e": 733,
"s": 239,
"text": null
},
{
"code": null,
"e": 741,
"s": 733,
"text": "Output:"
},
{
"code": null,
"e": 898,
"s": 741,
"text": " x1 x2 x3\n 1 1 a NA\n 2 2 b NA\n 3 3 c NA\n 4 4 d NA\n 5 5 e NA\n 6 0 5\n 7 0 6\n 8 0 7\n 9 0 8\n 10 0 9\n"
},
{
"code": null,
"e": 1163,
"s": 898,
"text": "Here in the above code, we created 3 data frames data1, data2, data3 with rows and columns in it and then we use bind_rows() function to combine the rows that were present in the data frame. Also where the variable name is not listed bind_rows() inserted NA value."
},
{
"code": null,
"e": 1231,
"s": 1163,
"text": "bind_cols() function is used to combine columns of two data frames."
},
{
"code": null,
"e": 1266,
"s": 1231,
"text": "Syntax:bind_cols(data1, data2, id)"
},
{
"code": null,
"e": 1336,
"s": 1266,
"text": "Parameter:id: dataframe identifierdata1, data2: data frame to combine"
},
{
"code": null,
"e": 1363,
"s": 1336,
"text": "Example: Combining Columns"
},
{
"code": "# R program to illustrate# combine rows # Install dplyr packageinstall.packages(\"dplyr\") # Load dplyr package library(\"dplyr\") # Create three data framesdata1 <- data.frame(x1 = 1:5, x2 = letters[1:5])data2 <- data.frame(x1 = 0, x3 = 5:9)data3 <- data.frame(x3 = 5:9, x4 = letters[5:9]) # Apply bind_cols functionbind_cols(data1, data3, id = NULL) ",
"e": 1857,
"s": 1363,
"text": null
},
{
"code": null,
"e": 1865,
"s": 1857,
"text": "Output:"
},
{
"code": null,
"e": 1956,
"s": 1865,
"text": " x1 x2 x3 x4\n 1 1 a 5 e\n 2 2 b 6 f\n 3 3 c 7 g\n 4 4 d 8 h\n 5 5 e 9 i "
},
{
"code": null,
"e": 2154,
"s": 1956,
"text": "Here in the above code we have created 3 data frames and then combine their columns by using bind_cols() function.Here we have combined the var. x1, x2 of data1 and x3, x4 of data2 with each other."
},
{
"code": null,
"e": 2175,
"s": 2154,
"text": "Programming Language"
},
{
"code": null,
"e": 2186,
"s": 2175,
"text": "R Language"
}
] |
Sorting 2D Vector in C++ | Set 3 (By number of columns) | 20 Dec, 2021
We have discussed some of the cases of sorting 2D vector in below set 1 and set 2.Sorting 2D Vector in C++ | Set 1 (By row and column) Sorting 2D Vector in C++ | Set 2 (In descending order by row and column)More cases are discussed in this articleAs mentioned in one of the article published of this set, A 2D Vector can also have rows with different number of columns. This property is unlike the 2D Array in which all rows have same number of columns.
CPP
// C++ code to demonstrate 2D Vector// with different no. of columns#include<iostream>#include<vector> // for 2D vectorusing namespace std;int main(){ // Initializing 2D vector "vect" with // values vector< vector<int> > vect{{1, 2}, {3, 4, 5}, {6}}; // Displaying the 2D vector for (int i=0; i<vect.size(); i++) { //loop till the size of particular //row for (int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << " "; cout << endl; } return 0; }
Output:
1 2
3 4 5
6
Case 5 : Sorting the 2D Vector on basis of no. of columns in row in ascending order.In this type of sorting, 2D vector is sorted on basis of a no. of column in ascending order. This is achieved by passing a third argument in “sort()” as a call to user defined explicit function.
CPP
// C++ code to demonstrate sorting of// 2D vector on basis of no. of columns// in ascending order#include<iostream>#include<vector> // for 2D vector#include<algorithm> // for sort()using namespace std; // Driver function to sort the 2D vector// on basis of a no. of columns in// ascending orderbool sizecom(const vector<int>& v1, const vector<int>& v2){ return v1.size() < v2.size();} int main(){ // Initializing 2D vector "vect" with // values vector< vector<int> > vect{{1, 2}, {3, 4, 5}, {6}}; // Displaying the 2D vector before sorting cout << "The Matrix before sorting is:\n"; for (int i=0; i<vect.size(); i++) { //loop till the size of particular //row for (int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << " "; cout << endl; } //Use of "sort()" for sorting on //basis of no. of columns in //ascending order. sort(vect.begin(), vect.end(), sizecom); // Displaying the 2D vector after sorting cout << "The Matrix after sorting is:\n"; for (int i=0; i<vect.size(); i++) { //loop till the size of particular //row for (int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << " "; cout << endl; } return 0; }
Output:
The Matrix before sorting is:
1 2
3 4 5
6
The Matrix after sorting is:
6
1 2
3 4 5
Case 6 : Sorting the 2D Vector on basis of no. of columns in row in descending order.In this type of sorting, 2D vector is sorted on basis of a no. of column in descending order. This is achieved by passing a third argument in “sort()” as a call to user defined explicit function.
CPP
// C++ code to demonstrate sorting of// 2D vector on basis of no. of columns// in descending order#include<iostream>#include<vector> // for 2D vector#include<algorithm> // for sort()using namespace std; // Driver function to sort the 2D vector// on basis of a no. of columns in// descending orderbool sizecom(const vector<int>& v1, const vector<int>& v2){ return v1.size() > v2.size();} int main(){ // Initializing 2D vector "vect" with // values vector< vector<int> > vect{{1, 2}, {3, 4, 5}, {6}}; // Displaying the 2D vector before sorting cout << "The Matrix before sorting is:\n"; for (int i=0; i<vect.size(); i++) { //loop till the size of particular //row for (int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << " "; cout << endl; } //Use of "sort()" for sorting on //basis of no. of columns in //descending order. sort(vect.begin(), vect.end(), sizecom); // Displaying the 2D vector after sorting cout << "The Matrix after sorting is:\n"; for (int i=0; i<vect.size(); i++) { //loop till the size of particular //row for (int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << " "; cout << endl; } return 0; }
Output:
The Matrix before sorting is:
1 2
3 4 5
6
The Matrix after sorting is:
3 4 5
1 2
6
This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
surinderdawra388
cpp-vector
STL
C Language
C++
Sorting
Sorting
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 507,
"s": 52,
"text": "We have discussed some of the cases of sorting 2D vector in below set 1 and set 2.Sorting 2D Vector in C++ | Set 1 (By row and column) Sorting 2D Vector in C++ | Set 2 (In descending order by row and column)More cases are discussed in this articleAs mentioned in one of the article published of this set, A 2D Vector can also have rows with different number of columns. This property is unlike the 2D Array in which all rows have same number of columns. "
},
{
"code": null,
"e": 511,
"s": 507,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate 2D Vector// with different no. of columns#include<iostream>#include<vector> // for 2D vectorusing namespace std;int main(){ // Initializing 2D vector \"vect\" with // values vector< vector<int> > vect{{1, 2}, {3, 4, 5}, {6}}; // Displaying the 2D vector for (int i=0; i<vect.size(); i++) { //loop till the size of particular //row for (int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << \" \"; cout << endl; } return 0; }",
"e": 1084,
"s": 511,
"text": null
},
{
"code": null,
"e": 1094,
"s": 1084,
"text": "Output: "
},
{
"code": null,
"e": 1106,
"s": 1094,
"text": "1 2\n3 4 5\n6"
},
{
"code": null,
"e": 1386,
"s": 1106,
"text": "Case 5 : Sorting the 2D Vector on basis of no. of columns in row in ascending order.In this type of sorting, 2D vector is sorted on basis of a no. of column in ascending order. This is achieved by passing a third argument in “sort()” as a call to user defined explicit function. "
},
{
"code": null,
"e": 1390,
"s": 1386,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate sorting of// 2D vector on basis of no. of columns// in ascending order#include<iostream>#include<vector> // for 2D vector#include<algorithm> // for sort()using namespace std; // Driver function to sort the 2D vector// on basis of a no. of columns in// ascending orderbool sizecom(const vector<int>& v1, const vector<int>& v2){ return v1.size() < v2.size();} int main(){ // Initializing 2D vector \"vect\" with // values vector< vector<int> > vect{{1, 2}, {3, 4, 5}, {6}}; // Displaying the 2D vector before sorting cout << \"The Matrix before sorting is:\\n\"; for (int i=0; i<vect.size(); i++) { //loop till the size of particular //row for (int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << \" \"; cout << endl; } //Use of \"sort()\" for sorting on //basis of no. of columns in //ascending order. sort(vect.begin(), vect.end(), sizecom); // Displaying the 2D vector after sorting cout << \"The Matrix after sorting is:\\n\"; for (int i=0; i<vect.size(); i++) { //loop till the size of particular //row for (int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << \" \"; cout << endl; } return 0; }",
"e": 2704,
"s": 1390,
"text": null
},
{
"code": null,
"e": 2714,
"s": 2704,
"text": "Output: "
},
{
"code": null,
"e": 2803,
"s": 2714,
"text": "The Matrix before sorting is:\n1 2 \n3 4 5 \n6 \nThe Matrix after sorting is:\n6 \n1 2 \n3 4 5 "
},
{
"code": null,
"e": 3085,
"s": 2803,
"text": "Case 6 : Sorting the 2D Vector on basis of no. of columns in row in descending order.In this type of sorting, 2D vector is sorted on basis of a no. of column in descending order. This is achieved by passing a third argument in “sort()” as a call to user defined explicit function. "
},
{
"code": null,
"e": 3089,
"s": 3085,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate sorting of// 2D vector on basis of no. of columns// in descending order#include<iostream>#include<vector> // for 2D vector#include<algorithm> // for sort()using namespace std; // Driver function to sort the 2D vector// on basis of a no. of columns in// descending orderbool sizecom(const vector<int>& v1, const vector<int>& v2){ return v1.size() > v2.size();} int main(){ // Initializing 2D vector \"vect\" with // values vector< vector<int> > vect{{1, 2}, {3, 4, 5}, {6}}; // Displaying the 2D vector before sorting cout << \"The Matrix before sorting is:\\n\"; for (int i=0; i<vect.size(); i++) { //loop till the size of particular //row for (int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << \" \"; cout << endl; } //Use of \"sort()\" for sorting on //basis of no. of columns in //descending order. sort(vect.begin(), vect.end(), sizecom); // Displaying the 2D vector after sorting cout << \"The Matrix after sorting is:\\n\"; for (int i=0; i<vect.size(); i++) { //loop till the size of particular //row for (int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << \" \"; cout << endl; } return 0; }",
"e": 4384,
"s": 3089,
"text": null
},
{
"code": null,
"e": 4394,
"s": 4384,
"text": "Output: "
},
{
"code": null,
"e": 4483,
"s": 4394,
"text": "The Matrix before sorting is:\n1 2 \n3 4 5 \n6 \nThe Matrix after sorting is:\n3 4 5 \n1 2 \n6 "
},
{
"code": null,
"e": 4905,
"s": 4483,
"text": "This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4922,
"s": 4905,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4933,
"s": 4922,
"text": "cpp-vector"
},
{
"code": null,
"e": 4937,
"s": 4933,
"text": "STL"
},
{
"code": null,
"e": 4948,
"s": 4937,
"text": "C Language"
},
{
"code": null,
"e": 4952,
"s": 4948,
"text": "C++"
},
{
"code": null,
"e": 4960,
"s": 4952,
"text": "Sorting"
},
{
"code": null,
"e": 4968,
"s": 4960,
"text": "Sorting"
},
{
"code": null,
"e": 4972,
"s": 4968,
"text": "STL"
},
{
"code": null,
"e": 4976,
"s": 4972,
"text": "CPP"
},
{
"code": null,
"e": 5074,
"s": 4976,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5122,
"s": 5074,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 5143,
"s": 5122,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 5169,
"s": 5143,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 5214,
"s": 5169,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 5252,
"s": 5214,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 5270,
"s": 5252,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 5313,
"s": 5270,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5359,
"s": 5313,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 5402,
"s": 5359,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
PrintWriter print(int) method in Java with Examples | 31 Jan, 2019
The print(int) method of PrintWriter Class in Java is used to print the specified int value on the stream. This int value is taken as a parameter.
Syntax:
public void print(int intValue)
Parameters: This method accepts a mandatory parameter intValue which is the int value to be written on the stream.
Return Value: This method do not returns any value.
Below methods illustrates the working of print(int) method:
Program 1:
// Java program to demonstrate// PrintWriter print(int) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintWriter instance PrintWriter printr = new PrintWriter(System.out); // Print the int value '4' // to this stream using print() method // This will put the intValue in the // stream till it is printed on the console printr.print(4); printr.flush(); } catch (Exception e) { System.out.println(e); } }}
4
Program 2:
// Java program to demonstrate// PrintWriter print(int) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintWriter instance PrintWriter printr = new PrintWriter(System.out); // Print the int value '65' // to this stream using print() method // This will put the intValue in the // stream till it is printed on the console printr.print(65); printr.flush(); } catch (Exception e) { System.out.println(e); } }}
65
Java-Functions
Java-IO package
Java-PrintWriter
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 175,
"s": 28,
"text": "The print(int) method of PrintWriter Class in Java is used to print the specified int value on the stream. This int value is taken as a parameter."
},
{
"code": null,
"e": 183,
"s": 175,
"text": "Syntax:"
},
{
"code": null,
"e": 215,
"s": 183,
"text": "public void print(int intValue)"
},
{
"code": null,
"e": 330,
"s": 215,
"text": "Parameters: This method accepts a mandatory parameter intValue which is the int value to be written on the stream."
},
{
"code": null,
"e": 382,
"s": 330,
"text": "Return Value: This method do not returns any value."
},
{
"code": null,
"e": 442,
"s": 382,
"text": "Below methods illustrates the working of print(int) method:"
},
{
"code": null,
"e": 453,
"s": 442,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// PrintWriter print(int) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintWriter instance PrintWriter printr = new PrintWriter(System.out); // Print the int value '4' // to this stream using print() method // This will put the intValue in the // stream till it is printed on the console printr.print(4); printr.flush(); } catch (Exception e) { System.out.println(e); } }}",
"e": 1069,
"s": 453,
"text": null
},
{
"code": null,
"e": 1072,
"s": 1069,
"text": "4\n"
},
{
"code": null,
"e": 1083,
"s": 1072,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// PrintWriter print(int) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintWriter instance PrintWriter printr = new PrintWriter(System.out); // Print the int value '65' // to this stream using print() method // This will put the intValue in the // stream till it is printed on the console printr.print(65); printr.flush(); } catch (Exception e) { System.out.println(e); } }}",
"e": 1701,
"s": 1083,
"text": null
},
{
"code": null,
"e": 1705,
"s": 1701,
"text": "65\n"
},
{
"code": null,
"e": 1720,
"s": 1705,
"text": "Java-Functions"
},
{
"code": null,
"e": 1736,
"s": 1720,
"text": "Java-IO package"
},
{
"code": null,
"e": 1753,
"s": 1736,
"text": "Java-PrintWriter"
},
{
"code": null,
"e": 1758,
"s": 1753,
"text": "Java"
},
{
"code": null,
"e": 1763,
"s": 1758,
"text": "Java"
}
] |
Java.lang.Process class in Java | 08 Mar, 2022
The abstract Process class a process- that is, an executing program. Methods provided by the Process is used to perform input, output, waiting for the process to complete, checking exit status of the process and destroying process.
It extends class Object.
It is used primarily as a superclass for the type of object created by exec() in the Runtime class.
ProcessBuilder.start() and Runtime.getRuntime.exec() methods creates a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it.
ProcessBuilder.start() is the most preferred way to create process.
ProcessBuilder.start() vs Runtime.getRuntime.exec(): ProcessBuilder allows us to redirect the standard error of the child process into its standard output. Now we don’t need two separate threads one reading from stdout and one reading from stderr.
Constructor
Process(): This is the only constructor.
Methods:
void destroy(): Kills the subprocess.Syntax: public abstract void destroy().
Returns: NA.
Exception: NA.
// Java code illustrating destroy() // method for windows operating systempublic class ProcessDemo public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process pro = builder.start(); // wait 10 seconds System.out.println("Waiting"); Thread.sleep(10000); // kill the process pro.destroy(); System.out.println("Process destroyed"); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process
Waiting
Process destroyed
// Java code illustrating destroy()// method for Mac Operating Systemimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { System.out.println("Creating process"); //creating process ProcessBuilder p = new ProcessBuilder(new String[] {"open", "/Applications/Facetime.app"}); Process pro = p.start(); //waiting for 10 second Thread.sleep(10000); System.out.println("destroying process"); //destroying process pro.destroy(); }}Output:Creating process
destroying process
int exitValue(): This method returns the exit value for the subprocess.Syntax: public abstract int exitValue().
Returns: This method returns the exit value of
the subprocess represented by this Process object.
By convention, the value 0 indicates normal termination.
Exception: IllegalThreadStateException ,
if the subprocess represented by this Process object has not yet terminated.
// Java code illustrating exitValue() methodpublic class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process pro = builder.start(); // kill the process pro.destroy(); // checking the exit value of subprocess System.out.println("exit value: " + pro.exitValue()); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process
1
abstract InputStream getErrorStream(): This method gets the input stream of the subprocess.Syntax: public abstract InputStream getInputStream().
Returns: input stream that reads input from the process out output stream.
Exception: NA.
// Java code illustrating// getInputStream() methodimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { // creating the process Runtime r = Runtime.getRuntime(); // shell script for loop from 1 to 3 String[] nargs = {"sh", "-c", "for i in 1 2 3; do echo $i; done"}; Process p = r.exec(nargs); BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; // reading the output while ((line = is.readLine()) != null) System.out.println(line); }}Output:1
2
3
abstract OutputStream getOutputStream(): This method gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by this Process object.Syntax: public abstract OutputStream getOutputStream()
Returns: the output stream connected to the normal input of the subprocess.
Exception: NA.
// Java code illustrating // getOutputStream() methodimport java.io.BufferedOutputStream;import java.io.OutputStream; public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); Process p = Runtime.getRuntime().exec("notepad.exe"); // get the output stream OutputStream out = p.getOutputStream(); // close the output stream System.out.println("Closing the output stream"); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process...
Closing the output stream...
abstract InputStream getErrorStream(): It returns an input stream that reads input from the process err output stream.Syntax: public abstract InputStream getErrorStream().
Returns: the input stream connected to the error stream of the subprocess.
Exception: NA.
// Java code illustrating // getErrorStream() methodimport java.io.InputStream; public class ProcessDemo{ public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); Process p = Runtime.getRuntime().exec("notepad.exe"); // get the error stream of the process and print it InputStream error = p.getErrorStream(); for (int i = 0; i < error.available(); i++) { System.out.println("" + error.read()); } // wait for 10 seconds and then destroy the process Thread.sleep(10000); p.destroy(); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process
int waitFor(): Returns the exit code returned by the process. This method does not return until the process on which it is called terminates.Syntax: public int waitFor().
Returns: the exit value of the process. By convention, 0 indicates normal termination.
Exception: throws InterruptedException.
// Java code illustrating // waitFor() method public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); Process p = Runtime.getRuntime().exec("notepad.exe"); // cause this process to stop // until process p is terminated p.waitFor(); // when you manually close notepad.exe // program will continue here System.out.println("Waiting over"); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process...
Waiting over.
void destroy(): Kills the subprocess.Syntax: public abstract void destroy().
Returns: NA.
Exception: NA.
// Java code illustrating destroy() // method for windows operating systempublic class ProcessDemo public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process pro = builder.start(); // wait 10 seconds System.out.println("Waiting"); Thread.sleep(10000); // kill the process pro.destroy(); System.out.println("Process destroyed"); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process
Waiting
Process destroyed
// Java code illustrating destroy()// method for Mac Operating Systemimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { System.out.println("Creating process"); //creating process ProcessBuilder p = new ProcessBuilder(new String[] {"open", "/Applications/Facetime.app"}); Process pro = p.start(); //waiting for 10 second Thread.sleep(10000); System.out.println("destroying process"); //destroying process pro.destroy(); }}Output:Creating process
destroying process
Syntax: public abstract void destroy().
Returns: NA.
Exception: NA.
// Java code illustrating destroy() // method for windows operating systempublic class ProcessDemo public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process pro = builder.start(); // wait 10 seconds System.out.println("Waiting"); Thread.sleep(10000); // kill the process pro.destroy(); System.out.println("Process destroyed"); } catch (Exception ex) { ex.printStackTrace(); } }}
Output:
Creating Process
Waiting
Process destroyed
// Java code illustrating destroy()// method for Mac Operating Systemimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { System.out.println("Creating process"); //creating process ProcessBuilder p = new ProcessBuilder(new String[] {"open", "/Applications/Facetime.app"}); Process pro = p.start(); //waiting for 10 second Thread.sleep(10000); System.out.println("destroying process"); //destroying process pro.destroy(); }}
Output:
Creating process
destroying process
int exitValue(): This method returns the exit value for the subprocess.Syntax: public abstract int exitValue().
Returns: This method returns the exit value of
the subprocess represented by this Process object.
By convention, the value 0 indicates normal termination.
Exception: IllegalThreadStateException ,
if the subprocess represented by this Process object has not yet terminated.
// Java code illustrating exitValue() methodpublic class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process pro = builder.start(); // kill the process pro.destroy(); // checking the exit value of subprocess System.out.println("exit value: " + pro.exitValue()); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process
1
Syntax: public abstract int exitValue().
Returns: This method returns the exit value of
the subprocess represented by this Process object.
By convention, the value 0 indicates normal termination.
Exception: IllegalThreadStateException ,
if the subprocess represented by this Process object has not yet terminated.
// Java code illustrating exitValue() methodpublic class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); ProcessBuilder builder = new ProcessBuilder("notepad.exe"); Process pro = builder.start(); // kill the process pro.destroy(); // checking the exit value of subprocess System.out.println("exit value: " + pro.exitValue()); } catch (Exception ex) { ex.printStackTrace(); } }}
Output:
Creating Process
1
abstract InputStream getErrorStream(): This method gets the input stream of the subprocess.Syntax: public abstract InputStream getInputStream().
Returns: input stream that reads input from the process out output stream.
Exception: NA.
// Java code illustrating// getInputStream() methodimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { // creating the process Runtime r = Runtime.getRuntime(); // shell script for loop from 1 to 3 String[] nargs = {"sh", "-c", "for i in 1 2 3; do echo $i; done"}; Process p = r.exec(nargs); BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; // reading the output while ((line = is.readLine()) != null) System.out.println(line); }}Output:1
2
3
Syntax: public abstract InputStream getInputStream().
Returns: input stream that reads input from the process out output stream.
Exception: NA.
// Java code illustrating// getInputStream() methodimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { // creating the process Runtime r = Runtime.getRuntime(); // shell script for loop from 1 to 3 String[] nargs = {"sh", "-c", "for i in 1 2 3; do echo $i; done"}; Process p = r.exec(nargs); BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; // reading the output while ((line = is.readLine()) != null) System.out.println(line); }}
Output:
1
2
3
abstract OutputStream getOutputStream(): This method gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by this Process object.Syntax: public abstract OutputStream getOutputStream()
Returns: the output stream connected to the normal input of the subprocess.
Exception: NA.
// Java code illustrating // getOutputStream() methodimport java.io.BufferedOutputStream;import java.io.OutputStream; public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); Process p = Runtime.getRuntime().exec("notepad.exe"); // get the output stream OutputStream out = p.getOutputStream(); // close the output stream System.out.println("Closing the output stream"); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process...
Closing the output stream...
Syntax: public abstract OutputStream getOutputStream()
Returns: the output stream connected to the normal input of the subprocess.
Exception: NA.
// Java code illustrating // getOutputStream() methodimport java.io.BufferedOutputStream;import java.io.OutputStream; public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); Process p = Runtime.getRuntime().exec("notepad.exe"); // get the output stream OutputStream out = p.getOutputStream(); // close the output stream System.out.println("Closing the output stream"); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }}
Output:
Creating Process...
Closing the output stream...
abstract InputStream getErrorStream(): It returns an input stream that reads input from the process err output stream.Syntax: public abstract InputStream getErrorStream().
Returns: the input stream connected to the error stream of the subprocess.
Exception: NA.
// Java code illustrating // getErrorStream() methodimport java.io.InputStream; public class ProcessDemo{ public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); Process p = Runtime.getRuntime().exec("notepad.exe"); // get the error stream of the process and print it InputStream error = p.getErrorStream(); for (int i = 0; i < error.available(); i++) { System.out.println("" + error.read()); } // wait for 10 seconds and then destroy the process Thread.sleep(10000); p.destroy(); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process
Syntax: public abstract InputStream getErrorStream().
Returns: the input stream connected to the error stream of the subprocess.
Exception: NA.
// Java code illustrating // getErrorStream() methodimport java.io.InputStream; public class ProcessDemo{ public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); Process p = Runtime.getRuntime().exec("notepad.exe"); // get the error stream of the process and print it InputStream error = p.getErrorStream(); for (int i = 0; i < error.available(); i++) { System.out.println("" + error.read()); } // wait for 10 seconds and then destroy the process Thread.sleep(10000); p.destroy(); } catch (Exception ex) { ex.printStackTrace(); } }}
Output:
Creating Process
int waitFor(): Returns the exit code returned by the process. This method does not return until the process on which it is called terminates.Syntax: public int waitFor().
Returns: the exit value of the process. By convention, 0 indicates normal termination.
Exception: throws InterruptedException.
// Java code illustrating // waitFor() method public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); Process p = Runtime.getRuntime().exec("notepad.exe"); // cause this process to stop // until process p is terminated p.waitFor(); // when you manually close notepad.exe // program will continue here System.out.println("Waiting over"); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process...
Waiting over.
Syntax: public int waitFor().
Returns: the exit value of the process. By convention, 0 indicates normal termination.
Exception: throws InterruptedException.
// Java code illustrating // waitFor() method public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println("Creating Process"); Process p = Runtime.getRuntime().exec("notepad.exe"); // cause this process to stop // until process p is terminated p.waitFor(); // when you manually close notepad.exe // program will continue here System.out.println("Waiting over"); } catch (Exception ex) { ex.printStackTrace(); } }}
Output:
Creating Process...
Waiting over.
This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
akshitsaxenaa09
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Initializing a List in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 286,
"s": 54,
"text": "The abstract Process class a process- that is, an executing program. Methods provided by the Process is used to perform input, output, waiting for the process to complete, checking exit status of the process and destroying process."
},
{
"code": null,
"e": 311,
"s": 286,
"text": "It extends class Object."
},
{
"code": null,
"e": 411,
"s": 311,
"text": "It is used primarily as a superclass for the type of object created by exec() in the Runtime class."
},
{
"code": null,
"e": 618,
"s": 411,
"text": "ProcessBuilder.start() and Runtime.getRuntime.exec() methods creates a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it."
},
{
"code": null,
"e": 686,
"s": 618,
"text": "ProcessBuilder.start() is the most preferred way to create process."
},
{
"code": null,
"e": 934,
"s": 686,
"text": "ProcessBuilder.start() vs Runtime.getRuntime.exec(): ProcessBuilder allows us to redirect the standard error of the child process into its standard output. Now we don’t need two separate threads one reading from stdout and one reading from stderr."
},
{
"code": null,
"e": 946,
"s": 934,
"text": "Constructor"
},
{
"code": null,
"e": 987,
"s": 946,
"text": "Process(): This is the only constructor."
},
{
"code": null,
"e": 996,
"s": 987,
"text": "Methods:"
},
{
"code": null,
"e": 7809,
"s": 996,
"text": "void destroy(): Kills the subprocess.Syntax: public abstract void destroy().\nReturns: NA.\nException: NA.\n// Java code illustrating destroy() // method for windows operating systempublic class ProcessDemo public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); ProcessBuilder builder = new ProcessBuilder(\"notepad.exe\"); Process pro = builder.start(); // wait 10 seconds System.out.println(\"Waiting\"); Thread.sleep(10000); // kill the process pro.destroy(); System.out.println(\"Process destroyed\"); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process\nWaiting\nProcess destroyed\n// Java code illustrating destroy()// method for Mac Operating Systemimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { System.out.println(\"Creating process\"); //creating process ProcessBuilder p = new ProcessBuilder(new String[] {\"open\", \"/Applications/Facetime.app\"}); Process pro = p.start(); //waiting for 10 second Thread.sleep(10000); System.out.println(\"destroying process\"); //destroying process pro.destroy(); }}Output:Creating process\ndestroying process\nint exitValue(): This method returns the exit value for the subprocess.Syntax: public abstract int exitValue().\nReturns: This method returns the exit value of \nthe subprocess represented by this Process object. \nBy convention, the value 0 indicates normal termination.\nException: IllegalThreadStateException ,\nif the subprocess represented by this Process object has not yet terminated.\n// Java code illustrating exitValue() methodpublic class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); ProcessBuilder builder = new ProcessBuilder(\"notepad.exe\"); Process pro = builder.start(); // kill the process pro.destroy(); // checking the exit value of subprocess System.out.println(\"exit value: \" + pro.exitValue()); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process\n1\nabstract InputStream getErrorStream(): This method gets the input stream of the subprocess.Syntax: public abstract InputStream getInputStream().\nReturns: input stream that reads input from the process out output stream.\nException: NA.\n// Java code illustrating// getInputStream() methodimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { // creating the process Runtime r = Runtime.getRuntime(); // shell script for loop from 1 to 3 String[] nargs = {\"sh\", \"-c\", \"for i in 1 2 3; do echo $i; done\"}; Process p = r.exec(nargs); BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; // reading the output while ((line = is.readLine()) != null) System.out.println(line); }}Output:1\n2\n3\nabstract OutputStream getOutputStream(): This method gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by this Process object.Syntax: public abstract OutputStream getOutputStream()\nReturns: the output stream connected to the normal input of the subprocess.\nException: NA.\n// Java code illustrating // getOutputStream() methodimport java.io.BufferedOutputStream;import java.io.OutputStream; public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); Process p = Runtime.getRuntime().exec(\"notepad.exe\"); // get the output stream OutputStream out = p.getOutputStream(); // close the output stream System.out.println(\"Closing the output stream\"); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process...\nClosing the output stream...\nabstract InputStream getErrorStream(): It returns an input stream that reads input from the process err output stream.Syntax: public abstract InputStream getErrorStream().\nReturns: the input stream connected to the error stream of the subprocess.\nException: NA.\n// Java code illustrating // getErrorStream() methodimport java.io.InputStream; public class ProcessDemo{ public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); Process p = Runtime.getRuntime().exec(\"notepad.exe\"); // get the error stream of the process and print it InputStream error = p.getErrorStream(); for (int i = 0; i < error.available(); i++) { System.out.println(\"\" + error.read()); } // wait for 10 seconds and then destroy the process Thread.sleep(10000); p.destroy(); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process\nint waitFor(): Returns the exit code returned by the process. This method does not return until the process on which it is called terminates.Syntax: public int waitFor().\nReturns: the exit value of the process. By convention, 0 indicates normal termination.\nException: throws InterruptedException.\n// Java code illustrating // waitFor() method public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); Process p = Runtime.getRuntime().exec(\"notepad.exe\"); // cause this process to stop // until process p is terminated p.waitFor(); // when you manually close notepad.exe // program will continue here System.out.println(\"Waiting over\"); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process...\nWaiting over.\n"
},
{
"code": null,
"e": 9381,
"s": 7809,
"text": "void destroy(): Kills the subprocess.Syntax: public abstract void destroy().\nReturns: NA.\nException: NA.\n// Java code illustrating destroy() // method for windows operating systempublic class ProcessDemo public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); ProcessBuilder builder = new ProcessBuilder(\"notepad.exe\"); Process pro = builder.start(); // wait 10 seconds System.out.println(\"Waiting\"); Thread.sleep(10000); // kill the process pro.destroy(); System.out.println(\"Process destroyed\"); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process\nWaiting\nProcess destroyed\n// Java code illustrating destroy()// method for Mac Operating Systemimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { System.out.println(\"Creating process\"); //creating process ProcessBuilder p = new ProcessBuilder(new String[] {\"open\", \"/Applications/Facetime.app\"}); Process pro = p.start(); //waiting for 10 second Thread.sleep(10000); System.out.println(\"destroying process\"); //destroying process pro.destroy(); }}Output:Creating process\ndestroying process\n"
},
{
"code": null,
"e": 9450,
"s": 9381,
"text": "Syntax: public abstract void destroy().\nReturns: NA.\nException: NA.\n"
},
{
"code": "// Java code illustrating destroy() // method for windows operating systempublic class ProcessDemo public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); ProcessBuilder builder = new ProcessBuilder(\"notepad.exe\"); Process pro = builder.start(); // wait 10 seconds System.out.println(\"Waiting\"); Thread.sleep(10000); // kill the process pro.destroy(); System.out.println(\"Process destroyed\"); } catch (Exception ex) { ex.printStackTrace(); } }}",
"e": 10177,
"s": 9450,
"text": null
},
{
"code": null,
"e": 10185,
"s": 10177,
"text": "Output:"
},
{
"code": null,
"e": 10229,
"s": 10185,
"text": "Creating Process\nWaiting\nProcess destroyed\n"
},
{
"code": "// Java code illustrating destroy()// method for Mac Operating Systemimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { System.out.println(\"Creating process\"); //creating process ProcessBuilder p = new ProcessBuilder(new String[] {\"open\", \"/Applications/Facetime.app\"}); Process pro = p.start(); //waiting for 10 second Thread.sleep(10000); System.out.println(\"destroying process\"); //destroying process pro.destroy(); }}",
"e": 10877,
"s": 10229,
"text": null
},
{
"code": null,
"e": 10885,
"s": 10877,
"text": "Output:"
},
{
"code": null,
"e": 10922,
"s": 10885,
"text": "Creating process\ndestroying process\n"
},
{
"code": null,
"e": 11987,
"s": 10922,
"text": "int exitValue(): This method returns the exit value for the subprocess.Syntax: public abstract int exitValue().\nReturns: This method returns the exit value of \nthe subprocess represented by this Process object. \nBy convention, the value 0 indicates normal termination.\nException: IllegalThreadStateException ,\nif the subprocess represented by this Process object has not yet terminated.\n// Java code illustrating exitValue() methodpublic class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); ProcessBuilder builder = new ProcessBuilder(\"notepad.exe\"); Process pro = builder.start(); // kill the process pro.destroy(); // checking the exit value of subprocess System.out.println(\"exit value: \" + pro.exitValue()); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process\n1\n"
},
{
"code": null,
"e": 12304,
"s": 11987,
"text": "Syntax: public abstract int exitValue().\nReturns: This method returns the exit value of \nthe subprocess represented by this Process object. \nBy convention, the value 0 indicates normal termination.\nException: IllegalThreadStateException ,\nif the subprocess represented by this Process object has not yet terminated.\n"
},
{
"code": "// Java code illustrating exitValue() methodpublic class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); ProcessBuilder builder = new ProcessBuilder(\"notepad.exe\"); Process pro = builder.start(); // kill the process pro.destroy(); // checking the exit value of subprocess System.out.println(\"exit value: \" + pro.exitValue()); } catch (Exception ex) { ex.printStackTrace(); } }}",
"e": 12956,
"s": 12304,
"text": null
},
{
"code": null,
"e": 12964,
"s": 12956,
"text": "Output:"
},
{
"code": null,
"e": 12984,
"s": 12964,
"text": "Creating Process\n1\n"
},
{
"code": null,
"e": 13941,
"s": 12984,
"text": "abstract InputStream getErrorStream(): This method gets the input stream of the subprocess.Syntax: public abstract InputStream getInputStream().\nReturns: input stream that reads input from the process out output stream.\nException: NA.\n// Java code illustrating// getInputStream() methodimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { // creating the process Runtime r = Runtime.getRuntime(); // shell script for loop from 1 to 3 String[] nargs = {\"sh\", \"-c\", \"for i in 1 2 3; do echo $i; done\"}; Process p = r.exec(nargs); BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; // reading the output while ((line = is.readLine()) != null) System.out.println(line); }}Output:1\n2\n3\n"
},
{
"code": null,
"e": 14086,
"s": 13941,
"text": "Syntax: public abstract InputStream getInputStream().\nReturns: input stream that reads input from the process out output stream.\nException: NA.\n"
},
{
"code": "// Java code illustrating// getInputStream() methodimport java.lang.*;import java.io.*;class ProcessDemo{ public static void main(String arg[]) throws IOException, Exception { // creating the process Runtime r = Runtime.getRuntime(); // shell script for loop from 1 to 3 String[] nargs = {\"sh\", \"-c\", \"for i in 1 2 3; do echo $i; done\"}; Process p = r.exec(nargs); BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; // reading the output while ((line = is.readLine()) != null) System.out.println(line); }}",
"e": 14795,
"s": 14086,
"text": null
},
{
"code": null,
"e": 14803,
"s": 14795,
"text": "Output:"
},
{
"code": null,
"e": 14810,
"s": 14803,
"text": "1\n2\n3\n"
},
{
"code": null,
"e": 15904,
"s": 14810,
"text": "abstract OutputStream getOutputStream(): This method gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by this Process object.Syntax: public abstract OutputStream getOutputStream()\nReturns: the output stream connected to the normal input of the subprocess.\nException: NA.\n// Java code illustrating // getOutputStream() methodimport java.io.BufferedOutputStream;import java.io.OutputStream; public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); Process p = Runtime.getRuntime().exec(\"notepad.exe\"); // get the output stream OutputStream out = p.getOutputStream(); // close the output stream System.out.println(\"Closing the output stream\"); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process...\nClosing the output stream...\n"
},
{
"code": null,
"e": 16051,
"s": 15904,
"text": "Syntax: public abstract OutputStream getOutputStream()\nReturns: the output stream connected to the normal input of the subprocess.\nException: NA.\n"
},
{
"code": "// Java code illustrating // getOutputStream() methodimport java.io.BufferedOutputStream;import java.io.OutputStream; public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); Process p = Runtime.getRuntime().exec(\"notepad.exe\"); // get the output stream OutputStream out = p.getOutputStream(); // close the output stream System.out.println(\"Closing the output stream\"); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }}",
"e": 16737,
"s": 16051,
"text": null
},
{
"code": null,
"e": 16745,
"s": 16737,
"text": "Output:"
},
{
"code": null,
"e": 16795,
"s": 16745,
"text": "Creating Process...\nClosing the output stream...\n"
},
{
"code": null,
"e": 17929,
"s": 16795,
"text": "abstract InputStream getErrorStream(): It returns an input stream that reads input from the process err output stream.Syntax: public abstract InputStream getErrorStream().\nReturns: the input stream connected to the error stream of the subprocess.\nException: NA.\n// Java code illustrating // getErrorStream() methodimport java.io.InputStream; public class ProcessDemo{ public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); Process p = Runtime.getRuntime().exec(\"notepad.exe\"); // get the error stream of the process and print it InputStream error = p.getErrorStream(); for (int i = 0; i < error.available(); i++) { System.out.println(\"\" + error.read()); } // wait for 10 seconds and then destroy the process Thread.sleep(10000); p.destroy(); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process\n"
},
{
"code": null,
"e": 18074,
"s": 17929,
"text": "Syntax: public abstract InputStream getErrorStream().\nReturns: the input stream connected to the error stream of the subprocess.\nException: NA.\n"
},
{
"code": "// Java code illustrating // getErrorStream() methodimport java.io.InputStream; public class ProcessDemo{ public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); Process p = Runtime.getRuntime().exec(\"notepad.exe\"); // get the error stream of the process and print it InputStream error = p.getErrorStream(); for (int i = 0; i < error.available(); i++) { System.out.println(\"\" + error.read()); } // wait for 10 seconds and then destroy the process Thread.sleep(10000); p.destroy(); } catch (Exception ex) { ex.printStackTrace(); } }}",
"e": 18922,
"s": 18074,
"text": null
},
{
"code": null,
"e": 18930,
"s": 18922,
"text": "Output:"
},
{
"code": null,
"e": 18948,
"s": 18930,
"text": "Creating Process\n"
},
{
"code": null,
"e": 19944,
"s": 18948,
"text": "int waitFor(): Returns the exit code returned by the process. This method does not return until the process on which it is called terminates.Syntax: public int waitFor().\nReturns: the exit value of the process. By convention, 0 indicates normal termination.\nException: throws InterruptedException.\n// Java code illustrating // waitFor() method public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); Process p = Runtime.getRuntime().exec(\"notepad.exe\"); // cause this process to stop // until process p is terminated p.waitFor(); // when you manually close notepad.exe // program will continue here System.out.println(\"Waiting over\"); } catch (Exception ex) { ex.printStackTrace(); } }}Output:Creating Process...\nWaiting over.\n"
},
{
"code": null,
"e": 20102,
"s": 19944,
"text": "Syntax: public int waitFor().\nReturns: the exit value of the process. By convention, 0 indicates normal termination.\nException: throws InterruptedException.\n"
},
{
"code": "// Java code illustrating // waitFor() method public class ProcessDemo { public static void main(String[] args) { try { // create a new process System.out.println(\"Creating Process\"); Process p = Runtime.getRuntime().exec(\"notepad.exe\"); // cause this process to stop // until process p is terminated p.waitFor(); // when you manually close notepad.exe // program will continue here System.out.println(\"Waiting over\"); } catch (Exception ex) { ex.printStackTrace(); } }}",
"e": 20759,
"s": 20102,
"text": null
},
{
"code": null,
"e": 20767,
"s": 20759,
"text": "Output:"
},
{
"code": null,
"e": 20802,
"s": 20767,
"text": "Creating Process...\nWaiting over.\n"
},
{
"code": null,
"e": 21100,
"s": 20802,
"text": "This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 21225,
"s": 21100,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 21241,
"s": 21225,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 21259,
"s": 21241,
"text": "Java-lang package"
},
{
"code": null,
"e": 21264,
"s": 21259,
"text": "Java"
},
{
"code": null,
"e": 21269,
"s": 21264,
"text": "Java"
},
{
"code": null,
"e": 21367,
"s": 21269,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 21418,
"s": 21367,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 21449,
"s": 21418,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 21479,
"s": 21449,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 21497,
"s": 21479,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 21517,
"s": 21497,
"text": "Collections in Java"
},
{
"code": null,
"e": 21532,
"s": 21517,
"text": "Stream In Java"
},
{
"code": null,
"e": 21564,
"s": 21532,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 21588,
"s": 21564,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 21600,
"s": 21588,
"text": "Set in Java"
}
] |
Difference Array | Range update query in O(1) | Difficulty Level :
Medium
Consider an array A[] of integers and following two types of queries.
update(l, r, x) : Adds x to all values from A[l] to A[r] (both inclusive).printArray() : Prints the current modified array.
update(l, r, x) : Adds x to all values from A[l] to A[r] (both inclusive).
printArray() : Prints the current modified array.
Examples :
Input : A [] { 10, 5, 20, 40 }
update(0, 1, 10)
printArray()
update(1, 3, 20)
update(2, 2, 30)
printArray()
Output : 20 15 20 40
20 35 70 60
Explanation : The query update(0, 1, 10)
adds 10 to A[0] and A[1]. After update,
A[] becomes {20, 15, 20, 40}
Query update(1, 3, 20) adds 20 to A[1],
A[2] and A[3]. After update, A[] becomes
{20, 35, 40, 60}.
Query update(2, 2, 30) adds 30 to A[2].
After update, A[] becomes {20, 35, 70, 60}.
A simple solution is to do following :
update(l, r, x) : Run a loop from l to r and add x to all elements from A[l] to A[r]printArray() : Simply print A[].
update(l, r, x) : Run a loop from l to r and add x to all elements from A[l] to A[r]
printArray() : Simply print A[].
Time complexities of both of the above operations is O(n)An efficient solution is to use difference array. Difference array D[i] of a given array A[i] is defined as D[i] = A[i]-A[i-1] (for 0 < i < N ) and D[0] = A[0] considering 0 based indexing. Difference array can be used to perform range update queries “l r x” where l is left index, r is right index and x is value to be added and after all queries you can return original array from it. Where update range operations can be performed in O(1) complexity.
update(l, r, x) : Add x to D[l] and subtract it from D[r+1], i.e., we do D[l] += x, D[r+1] -= xprintArray() : Do A[0] = D[0] and print it. For rest of the elements, do A[i] = A[i-1] + D[i] and print them.
update(l, r, x) : Add x to D[l] and subtract it from D[r+1], i.e., we do D[l] += x, D[r+1] -= x
printArray() : Do A[0] = D[0] and print it. For rest of the elements, do A[i] = A[i-1] + D[i] and print them.
Time complexity of update here is improved to O(1). Note that printArray() still takes O(n) time.
C++
Java
Python3
C#
Javascript
// C++ code to demonstrate Difference Array#include <bits/stdc++.h>using namespace std; // Creates a diff array D[] for A[] and returns// it after filling initial values.vector<int> initializeDiffArray(vector<int>& A){ int n = A.size(); // We use one extra space because // update(l, r, x) updates D[r+1] vector<int> D(n + 1); D[0] = A[0], D[n] = 0; for (int i = 1; i < n; i++) D[i] = A[i] - A[i - 1]; return D;} // Does range updatevoid update(vector<int>& D, int l, int r, int x){ D[l] += x; D[r + 1] -= x;} // Prints updated Arrayint printArray(vector<int>& A, vector<int>& D){ for (int i = 0; i < A.size(); i++) { if (i == 0) A[i] = D[i]; // Note that A[0] or D[0] decides // values of rest of the elements. else A[i] = D[i] + A[i - 1]; cout << A[i] << " "; } cout << endl;} // Driver Codeint main(){ // Array to be updated vector<int> A{ 10, 5, 20, 40 }; // Create and fill difference Array vector<int> D = initializeDiffArray(A); // After below update(l, r, x), the // elements should become 20, 15, 20, 40 update(D, 0, 1, 10); printArray(A, D); // After below updates, the // array should become 30, 35, 70, 60 update(D, 1, 3, 20); update(D, 2, 2, 30); printArray(A, D); return 0;}
// Java code to demonstrate Difference Arrayclass GFG { // Creates a diff array D[] for A[] and returns // it after filling initial values. static void initializeDiffArray(int A[], int D[]) { int n = A.length; D[0] = A[0]; D[n] = 0; for (int i = 1; i < n; i++) D[i] = A[i] - A[i - 1]; } // Does range update static void update(int D[], int l, int r, int x) { D[l] += x; D[r + 1] -= x; } // Prints updated Array static int printArray(int A[], int D[]) { for (int i = 0; i < A.length; i++) { if (i == 0) A[i] = D[i]; // Note that A[0] or D[0] decides // values of rest of the elements. else A[i] = D[i] + A[i - 1]; System.out.print(A[i] + " "); } System.out.println(); return 0; } // Driver Code public static void main(String[] args) { // Array to be updated int A[] = { 10, 5, 20, 40 }; int n = A.length; // Create and fill difference Array // We use one extra space because // update(l, r, x) updates D[r+1] int D[] = new int[n + 1]; initializeDiffArray(A, D); // After below update(l, r, x), the // elements should become 20, 15, 20, 40 update(D, 0, 1, 10); printArray(A, D); // After below updates, the // array should become 30, 35, 70, 60 update(D, 1, 3, 20); update(D, 2, 2, 30); printArray(A, D); }} // This code is contributed by Anant Agarwal.
# Python3 code to demonstrate Difference Array # Creates a diff array D[] for A[] and returns# it after filling initial values.def initializeDiffArray( A): n = len(A) # We use one extra space because # update(l, r, x) updates D[r+1] D = [0 for i in range(0 , n + 1)] D[0] = A[0]; D[n] = 0 for i in range(1, n ): D[i] = A[i] - A[i - 1] return D # Does range updatedef update(D, l, r, x): D[l] += x D[r + 1] -= x # Prints updated Arraydef printArray(A, D): for i in range(0 , len(A)): if (i == 0): A[i] = D[i] # Note that A[0] or D[0] decides # values of rest of the elements. else: A[i] = D[i] + A[i - 1] print(A[i], end = " ") print ("") # Driver CodeA = [ 10, 5, 20, 40 ] # Create and fill difference ArrayD = initializeDiffArray(A) # After below update(l, r, x), the# elements should become 20, 15, 20, 40update(D, 0, 1, 10)printArray(A, D) # After below updates, the# array should become 30, 35, 70, 60update(D, 1, 3, 20)update(D, 2, 2, 30)printArray(A, D) # This code is contributed by Gitanjali.
// C# code to demonstrate Difference Arrayusing System; class GFG { // Creates a diff array D[] for A[] and returns // it after filling initial values. static void initializeDiffArray(int []A, int []D) { int n = A.Length; D[0] = A[0]; D[n] = 0; for (int i = 1; i < n; i++) D[i] = A[i] - A[i - 1]; } // Does range update static void update(int []D, int l, int r, int x) { D[l] += x; D[r + 1] -= x; } // Prints updated Array static int printArray(int []A, int []D) { for (int i = 0; i < A.Length; i++) { if (i == 0) A[i] = D[i]; // Note that A[0] or D[0] decides // values of rest of the elements. else A[i] = D[i] + A[i - 1]; Console.Write(A[i] + " "); } Console.WriteLine(); return 0; } // Driver Code public static void Main() { // Array to be updated int []A = { 10, 5, 20, 40 }; int n = A.Length; // Create and fill difference Array // We use one extra space because // update(l, r, x) updates D[r+1] int []D = new int[n + 1]; initializeDiffArray(A, D); // After below update(l, r, x), the // elements should become 20, 15, 20, 40 update(D, 0, 1, 10); printArray(A, D); // After below updates, the // array should become 30, 35, 70, 60 update(D, 1, 3, 20); update(D, 2, 2, 30); printArray(A, D); }} // This code is contributed by vt_m.
<script>// JavaScript code to demonstrate Difference Array // Creates a diff array D[] for A[] and returns// it after filling initial values.function initializeDiffArray( A){ let n = A.length; // We use one extra space because // update(l, r, x) updates D[r+1] let D= []; D[0] = A[0], D[n] = 0; for (let i = 1; i < n; i++) D[i] = A[i] - A[i - 1]; return D;} // Does range updatefunction update(D, l, r, x){ D[l] += x; D[r + 1] -= x; return D;} // Prints updated Arrayfunction printArray( A, D){ for (let i = 0; i < A.length; i++) { if (i == 0) A[i] = D[i]; // Note that A[0] or D[0] decides // values of rest of the elements. else A[i] = D[i] + A[i - 1]; document.write( A[i]+ " "); } document.write("<br>");} // Driver Code// Array to be updatedlet A = [ 10, 5, 20, 40 ]; // Create and fill difference Arraylet D = initializeDiffArray(A); // After below update(l, r, x), the// elements should become 20, 15, 20, 40D = update(D, 0, 1, 10);printArray(A, D); // After below updates, the// array should become 30, 35, 70, 60D = update(D, 1, 3, 20);D = update(D, 2, 2, 30);printArray(A, D); </script>
Output:
20 15 20 40
20 35 70 60
Time complexity: O(n)
Auxiliary Space: O(n)
ndsingh
rohitsingh07052
sachinvinod1904
array-range-queries
Advanced Data Structure
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AVL Tree | Set 1 (Insertion)
LRU Cache Implementation
Introduction of B-Tree
Agents in Artificial Intelligence
Red-Black Tree | Set 1 (Introduction)
Arrays in Java
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Arrays in C/C++ | [
{
"code": null,
"e": 26,
"s": 0,
"text": "Difficulty Level :\nMedium"
},
{
"code": null,
"e": 98,
"s": 26,
"text": "Consider an array A[] of integers and following two types of queries. "
},
{
"code": null,
"e": 222,
"s": 98,
"text": "update(l, r, x) : Adds x to all values from A[l] to A[r] (both inclusive).printArray() : Prints the current modified array."
},
{
"code": null,
"e": 297,
"s": 222,
"text": "update(l, r, x) : Adds x to all values from A[l] to A[r] (both inclusive)."
},
{
"code": null,
"e": 347,
"s": 297,
"text": "printArray() : Prints the current modified array."
},
{
"code": null,
"e": 360,
"s": 347,
"text": "Examples : "
},
{
"code": null,
"e": 852,
"s": 360,
"text": "Input : A [] { 10, 5, 20, 40 }\n update(0, 1, 10)\n printArray()\n update(1, 3, 20)\n update(2, 2, 30)\n printArray()\nOutput : 20 15 20 40\n 20 35 70 60\nExplanation : The query update(0, 1, 10) \nadds 10 to A[0] and A[1]. After update,\nA[] becomes {20, 15, 20, 40} \nQuery update(1, 3, 20) adds 20 to A[1],\nA[2] and A[3]. After update, A[] becomes\n{20, 35, 40, 60}.\nQuery update(2, 2, 30) adds 30 to A[2]. \nAfter update, A[] becomes {20, 35, 70, 60}."
},
{
"code": null,
"e": 895,
"s": 854,
"text": "A simple solution is to do following : "
},
{
"code": null,
"e": 1012,
"s": 895,
"text": "update(l, r, x) : Run a loop from l to r and add x to all elements from A[l] to A[r]printArray() : Simply print A[]."
},
{
"code": null,
"e": 1097,
"s": 1012,
"text": "update(l, r, x) : Run a loop from l to r and add x to all elements from A[l] to A[r]"
},
{
"code": null,
"e": 1130,
"s": 1097,
"text": "printArray() : Simply print A[]."
},
{
"code": null,
"e": 1642,
"s": 1130,
"text": "Time complexities of both of the above operations is O(n)An efficient solution is to use difference array. Difference array D[i] of a given array A[i] is defined as D[i] = A[i]-A[i-1] (for 0 < i < N ) and D[0] = A[0] considering 0 based indexing. Difference array can be used to perform range update queries “l r x” where l is left index, r is right index and x is value to be added and after all queries you can return original array from it. Where update range operations can be performed in O(1) complexity. "
},
{
"code": null,
"e": 1847,
"s": 1642,
"text": "update(l, r, x) : Add x to D[l] and subtract it from D[r+1], i.e., we do D[l] += x, D[r+1] -= xprintArray() : Do A[0] = D[0] and print it. For rest of the elements, do A[i] = A[i-1] + D[i] and print them."
},
{
"code": null,
"e": 1943,
"s": 1847,
"text": "update(l, r, x) : Add x to D[l] and subtract it from D[r+1], i.e., we do D[l] += x, D[r+1] -= x"
},
{
"code": null,
"e": 2053,
"s": 1943,
"text": "printArray() : Do A[0] = D[0] and print it. For rest of the elements, do A[i] = A[i-1] + D[i] and print them."
},
{
"code": null,
"e": 2153,
"s": 2053,
"text": "Time complexity of update here is improved to O(1). Note that printArray() still takes O(n) time. "
},
{
"code": null,
"e": 2157,
"s": 2153,
"text": "C++"
},
{
"code": null,
"e": 2162,
"s": 2157,
"text": "Java"
},
{
"code": null,
"e": 2170,
"s": 2162,
"text": "Python3"
},
{
"code": null,
"e": 2173,
"s": 2170,
"text": "C#"
},
{
"code": null,
"e": 2184,
"s": 2173,
"text": "Javascript"
},
{
"code": "// C++ code to demonstrate Difference Array#include <bits/stdc++.h>using namespace std; // Creates a diff array D[] for A[] and returns// it after filling initial values.vector<int> initializeDiffArray(vector<int>& A){ int n = A.size(); // We use one extra space because // update(l, r, x) updates D[r+1] vector<int> D(n + 1); D[0] = A[0], D[n] = 0; for (int i = 1; i < n; i++) D[i] = A[i] - A[i - 1]; return D;} // Does range updatevoid update(vector<int>& D, int l, int r, int x){ D[l] += x; D[r + 1] -= x;} // Prints updated Arrayint printArray(vector<int>& A, vector<int>& D){ for (int i = 0; i < A.size(); i++) { if (i == 0) A[i] = D[i]; // Note that A[0] or D[0] decides // values of rest of the elements. else A[i] = D[i] + A[i - 1]; cout << A[i] << \" \"; } cout << endl;} // Driver Codeint main(){ // Array to be updated vector<int> A{ 10, 5, 20, 40 }; // Create and fill difference Array vector<int> D = initializeDiffArray(A); // After below update(l, r, x), the // elements should become 20, 15, 20, 40 update(D, 0, 1, 10); printArray(A, D); // After below updates, the // array should become 30, 35, 70, 60 update(D, 1, 3, 20); update(D, 2, 2, 30); printArray(A, D); return 0;}",
"e": 3523,
"s": 2184,
"text": null
},
{
"code": "// Java code to demonstrate Difference Arrayclass GFG { // Creates a diff array D[] for A[] and returns // it after filling initial values. static void initializeDiffArray(int A[], int D[]) { int n = A.length; D[0] = A[0]; D[n] = 0; for (int i = 1; i < n; i++) D[i] = A[i] - A[i - 1]; } // Does range update static void update(int D[], int l, int r, int x) { D[l] += x; D[r + 1] -= x; } // Prints updated Array static int printArray(int A[], int D[]) { for (int i = 0; i < A.length; i++) { if (i == 0) A[i] = D[i]; // Note that A[0] or D[0] decides // values of rest of the elements. else A[i] = D[i] + A[i - 1]; System.out.print(A[i] + \" \"); } System.out.println(); return 0; } // Driver Code public static void main(String[] args) { // Array to be updated int A[] = { 10, 5, 20, 40 }; int n = A.length; // Create and fill difference Array // We use one extra space because // update(l, r, x) updates D[r+1] int D[] = new int[n + 1]; initializeDiffArray(A, D); // After below update(l, r, x), the // elements should become 20, 15, 20, 40 update(D, 0, 1, 10); printArray(A, D); // After below updates, the // array should become 30, 35, 70, 60 update(D, 1, 3, 20); update(D, 2, 2, 30); printArray(A, D); }} // This code is contributed by Anant Agarwal.",
"e": 5178,
"s": 3523,
"text": null
},
{
"code": "# Python3 code to demonstrate Difference Array # Creates a diff array D[] for A[] and returns# it after filling initial values.def initializeDiffArray( A): n = len(A) # We use one extra space because # update(l, r, x) updates D[r+1] D = [0 for i in range(0 , n + 1)] D[0] = A[0]; D[n] = 0 for i in range(1, n ): D[i] = A[i] - A[i - 1] return D # Does range updatedef update(D, l, r, x): D[l] += x D[r + 1] -= x # Prints updated Arraydef printArray(A, D): for i in range(0 , len(A)): if (i == 0): A[i] = D[i] # Note that A[0] or D[0] decides # values of rest of the elements. else: A[i] = D[i] + A[i - 1] print(A[i], end = \" \") print (\"\") # Driver CodeA = [ 10, 5, 20, 40 ] # Create and fill difference ArrayD = initializeDiffArray(A) # After below update(l, r, x), the# elements should become 20, 15, 20, 40update(D, 0, 1, 10)printArray(A, D) # After below updates, the# array should become 30, 35, 70, 60update(D, 1, 3, 20)update(D, 2, 2, 30)printArray(A, D) # This code is contributed by Gitanjali.",
"e": 6295,
"s": 5178,
"text": null
},
{
"code": "// C# code to demonstrate Difference Arrayusing System; class GFG { // Creates a diff array D[] for A[] and returns // it after filling initial values. static void initializeDiffArray(int []A, int []D) { int n = A.Length; D[0] = A[0]; D[n] = 0; for (int i = 1; i < n; i++) D[i] = A[i] - A[i - 1]; } // Does range update static void update(int []D, int l, int r, int x) { D[l] += x; D[r + 1] -= x; } // Prints updated Array static int printArray(int []A, int []D) { for (int i = 0; i < A.Length; i++) { if (i == 0) A[i] = D[i]; // Note that A[0] or D[0] decides // values of rest of the elements. else A[i] = D[i] + A[i - 1]; Console.Write(A[i] + \" \"); } Console.WriteLine(); return 0; } // Driver Code public static void Main() { // Array to be updated int []A = { 10, 5, 20, 40 }; int n = A.Length; // Create and fill difference Array // We use one extra space because // update(l, r, x) updates D[r+1] int []D = new int[n + 1]; initializeDiffArray(A, D); // After below update(l, r, x), the // elements should become 20, 15, 20, 40 update(D, 0, 1, 10); printArray(A, D); // After below updates, the // array should become 30, 35, 70, 60 update(D, 1, 3, 20); update(D, 2, 2, 30); printArray(A, D); }} // This code is contributed by vt_m.",
"e": 7936,
"s": 6295,
"text": null
},
{
"code": "<script>// JavaScript code to demonstrate Difference Array // Creates a diff array D[] for A[] and returns// it after filling initial values.function initializeDiffArray( A){ let n = A.length; // We use one extra space because // update(l, r, x) updates D[r+1] let D= []; D[0] = A[0], D[n] = 0; for (let i = 1; i < n; i++) D[i] = A[i] - A[i - 1]; return D;} // Does range updatefunction update(D, l, r, x){ D[l] += x; D[r + 1] -= x; return D;} // Prints updated Arrayfunction printArray( A, D){ for (let i = 0; i < A.length; i++) { if (i == 0) A[i] = D[i]; // Note that A[0] or D[0] decides // values of rest of the elements. else A[i] = D[i] + A[i - 1]; document.write( A[i]+ \" \"); } document.write(\"<br>\");} // Driver Code// Array to be updatedlet A = [ 10, 5, 20, 40 ]; // Create and fill difference Arraylet D = initializeDiffArray(A); // After below update(l, r, x), the// elements should become 20, 15, 20, 40D = update(D, 0, 1, 10);printArray(A, D); // After below updates, the// array should become 30, 35, 70, 60D = update(D, 1, 3, 20);D = update(D, 2, 2, 30);printArray(A, D); </script>",
"e": 9140,
"s": 7936,
"text": null
},
{
"code": null,
"e": 9150,
"s": 9140,
"text": "Output: "
},
{
"code": null,
"e": 9176,
"s": 9150,
"text": "20 15 20 40 \n20 35 70 60 "
},
{
"code": null,
"e": 9198,
"s": 9176,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 9221,
"s": 9198,
"text": "Auxiliary Space: O(n) "
},
{
"code": null,
"e": 9229,
"s": 9221,
"text": "ndsingh"
},
{
"code": null,
"e": 9245,
"s": 9229,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 9261,
"s": 9245,
"text": "sachinvinod1904"
},
{
"code": null,
"e": 9281,
"s": 9261,
"text": "array-range-queries"
},
{
"code": null,
"e": 9305,
"s": 9281,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 9312,
"s": 9305,
"text": "Arrays"
},
{
"code": null,
"e": 9319,
"s": 9312,
"text": "Arrays"
},
{
"code": null,
"e": 9417,
"s": 9319,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9446,
"s": 9417,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 9471,
"s": 9446,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 9494,
"s": 9471,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 9528,
"s": 9494,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 9566,
"s": 9528,
"text": "Red-Black Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 9581,
"s": 9566,
"text": "Arrays in Java"
},
{
"code": null,
"e": 9649,
"s": 9581,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 9693,
"s": 9649,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 9725,
"s": 9693,
"text": "Largest Sum Contiguous Subarray"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.