title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Program to find the maximum difference between the index of any two different numbers
09 Jun, 2022 Given an array of N integers. The task is to find the maximum difference between the index of any two different numbers. Note that there is a minimum of two different numbers. Examples: Input: a[] = {1, 2, 3, 2, 3} Output: 4 The difference between 1 and last 3.Input: a[] = {1, 1, 3, 1, 1, 1} Output: 3 The difference between the index of 3 and last 1. Approach: Initially, check the first number which is different from a[0] starting from the end, store the difference of their index as ind1. Also, check for the first number which is different from a[n – 1] from the beginning, store the difference of their index as ind2. The answer will be max(ind1, ind2). Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum differenceint findMaximumDiff(int a[], int n){ int ind1 = 0; // Iteratively check from back for (int i = n - 1; i > 0; i--) { // Different numbers if (a[0] != a[i]) { ind1 = i; break; } } int ind2 = 0; // Iteratively check from // the beginning for (int i = 0; i < n - 1; i++) { // Different numbers if (a[n - 1] != a[i]) { ind2 = (n - 1 - i); break; } } return max(ind1, ind2);} // Driver codeint main(){ int a[] = { 1, 2, 3, 2, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << findMaximumDiff(a, n); return 0;} // Java implementation of the approachclass GFG{ // Function to return the maximum differencestatic int findMaximumDiff(int []a, int n){ int ind1 = 0; // Iteratively check from back for (int i = n - 1; i > 0; i--) { // Different numbers if (a[0] != a[i]) { ind1 = i; break; } } int ind2 = 0; // Iteratively check from // the beginning for (int i = 0; i < n - 1; i++) { // Different numbers if (a[n - 1] != a[i]) { ind2 = (n - 1 - i); break; } } return Math.max(ind1, ind2);} // Driver codepublic static void main(String args[]){ int []a = { 1, 2, 3, 2, 3 }; int n = a.length; System.out.println(findMaximumDiff(a, n));}} // This code is contributed by Akanksha_Rai # Python3 implementation of the approach # Function to return the maximum differencedef findMaximumDiff(a, n): ind1 = 0 # Iteratively check from back for i in range(n - 1, -1, -1): # Different numbers if (a[0] != a[i]): ind1 = i break ind2 = 0 # Iteratively check from # the beginning for i in range(n - 1): # Different numbers if (a[n - 1] != a[i]): ind2 = (n - 1 - i) break return max(ind1, ind2) # Driver codea = [1, 2, 3, 2, 3]n = len(a)print(findMaximumDiff(a, n)) # This code is contributed by mohit kumar // C# implementation of the approachusing System; class GFG{ // Function to return the maximum differencestatic int findMaximumDiff(int []a, int n){ int ind1 = 0; // Iteratively check from back for (int i = n - 1; i > 0; i--) { // Different numbers if (a[0] != a[i]) { ind1 = i; break; } } int ind2 = 0; // Iteratively check from // the beginning for (int i = 0; i < n - 1; i++) { // Different numbers if (a[n - 1] != a[i]) { ind2 = (n - 1 - i); break; } } return Math.Max(ind1, ind2);} // Driver codestatic void Main(){ int []a = { 1, 2, 3, 2, 3 }; int n = a.Length; Console.WriteLine(findMaximumDiff(a, n));}} // This code is contributed by mits <?php// PHP implementation of the approach // Function to return the maximum differencefunction findMaximumDiff($a, $n){ $ind1 = 0; // Iteratively check from back for ($i = $n - 1; $i > 0; $i--) { // Different numbers if ($a[0] != $a[$i]) { $ind1 = $i; break; } } $ind2 = 0; // Iteratively check from // the beginning for ($i = 0; $i < $n - 1; $i++) { // Different numbers if ($a[$n - 1] != $a[$i]) { $ind2 = ($n - 1 - $i); break; } } return max($ind1, $ind2);} // Driver code$a = array( 1, 2, 3, 2, 3 );$n = count($a); echo findMaximumDiff($a, $n); // This code is contributed by Ryuga?> <script>// javascript implementation of the approach // Function to return the maximum difference function findMaximumDiff(a , n) { var ind1 = 0; // Iteratively check from back for (i = n - 1; i > 0; i--) { // Different numbers if (a[0] != a[i]) { ind1 = i; break; } } var ind2 = 0; // Iteratively check from // the beginning for (i = 0; i < n - 1; i++) { // Different numbers if (a[n - 1] != a[i]) { ind2 = (n - 1 - i); break; } } return Math.max(ind1, ind2); } // Driver code var a = [ 1, 2, 3, 2, 3 ]; var n = a.length; document.write(findMaximumDiff(a, n)); // This code is contributed by todaysgaurav</script> 4 Time Complexity: O(n)Auxiliary Space: O(1) mohit kumar 29 ankthon Mithun Kumar Akanksha_Rai todaysgaurav rishavnitro Arrays Competitive Programming Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Introduction to Arrays Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Jun, 2022" }, { "code": null, "e": 241, "s": 53, "text": "Given an array of N integers. The task is to find the maximum difference between the index of any two different numbers. Note that there is a minimum of two different numbers. Examples: " }, { "code": null, "e": 410, "s": 241, "text": "Input: a[] = {1, 2, 3, 2, 3} Output: 4 The difference between 1 and last 3.Input: a[] = {1, 1, 3, 1, 1, 1} Output: 3 The difference between the index of 3 and last 1. " }, { "code": null, "e": 773, "s": 412, "text": "Approach: Initially, check the first number which is different from a[0] starting from the end, store the difference of their index as ind1. Also, check for the first number which is different from a[n – 1] from the beginning, store the difference of their index as ind2. The answer will be max(ind1, ind2). Below is the implementation of the above approach: " }, { "code": null, "e": 777, "s": 773, "text": "C++" }, { "code": null, "e": 782, "s": 777, "text": "Java" }, { "code": null, "e": 790, "s": 782, "text": "Python3" }, { "code": null, "e": 793, "s": 790, "text": "C#" }, { "code": null, "e": 797, "s": 793, "text": "PHP" }, { "code": null, "e": 808, "s": 797, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum differenceint findMaximumDiff(int a[], int n){ int ind1 = 0; // Iteratively check from back for (int i = n - 1; i > 0; i--) { // Different numbers if (a[0] != a[i]) { ind1 = i; break; } } int ind2 = 0; // Iteratively check from // the beginning for (int i = 0; i < n - 1; i++) { // Different numbers if (a[n - 1] != a[i]) { ind2 = (n - 1 - i); break; } } return max(ind1, ind2);} // Driver codeint main(){ int a[] = { 1, 2, 3, 2, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << findMaximumDiff(a, n); return 0;}", "e": 1570, "s": 808, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the maximum differencestatic int findMaximumDiff(int []a, int n){ int ind1 = 0; // Iteratively check from back for (int i = n - 1; i > 0; i--) { // Different numbers if (a[0] != a[i]) { ind1 = i; break; } } int ind2 = 0; // Iteratively check from // the beginning for (int i = 0; i < n - 1; i++) { // Different numbers if (a[n - 1] != a[i]) { ind2 = (n - 1 - i); break; } } return Math.max(ind1, ind2);} // Driver codepublic static void main(String args[]){ int []a = { 1, 2, 3, 2, 3 }; int n = a.length; System.out.println(findMaximumDiff(a, n));}} // This code is contributed by Akanksha_Rai", "e": 2390, "s": 1570, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum differencedef findMaximumDiff(a, n): ind1 = 0 # Iteratively check from back for i in range(n - 1, -1, -1): # Different numbers if (a[0] != a[i]): ind1 = i break ind2 = 0 # Iteratively check from # the beginning for i in range(n - 1): # Different numbers if (a[n - 1] != a[i]): ind2 = (n - 1 - i) break return max(ind1, ind2) # Driver codea = [1, 2, 3, 2, 3]n = len(a)print(findMaximumDiff(a, n)) # This code is contributed by mohit kumar", "e": 3004, "s": 2390, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum differencestatic int findMaximumDiff(int []a, int n){ int ind1 = 0; // Iteratively check from back for (int i = n - 1; i > 0; i--) { // Different numbers if (a[0] != a[i]) { ind1 = i; break; } } int ind2 = 0; // Iteratively check from // the beginning for (int i = 0; i < n - 1; i++) { // Different numbers if (a[n - 1] != a[i]) { ind2 = (n - 1 - i); break; } } return Math.Max(ind1, ind2);} // Driver codestatic void Main(){ int []a = { 1, 2, 3, 2, 3 }; int n = a.Length; Console.WriteLine(findMaximumDiff(a, n));}} // This code is contributed by mits", "e": 3807, "s": 3004, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the maximum differencefunction findMaximumDiff($a, $n){ $ind1 = 0; // Iteratively check from back for ($i = $n - 1; $i > 0; $i--) { // Different numbers if ($a[0] != $a[$i]) { $ind1 = $i; break; } } $ind2 = 0; // Iteratively check from // the beginning for ($i = 0; $i < $n - 1; $i++) { // Different numbers if ($a[$n - 1] != $a[$i]) { $ind2 = ($n - 1 - $i); break; } } return max($ind1, $ind2);} // Driver code$a = array( 1, 2, 3, 2, 3 );$n = count($a); echo findMaximumDiff($a, $n); // This code is contributed by Ryuga?>", "e": 4538, "s": 3807, "text": null }, { "code": "<script>// javascript implementation of the approach // Function to return the maximum difference function findMaximumDiff(a , n) { var ind1 = 0; // Iteratively check from back for (i = n - 1; i > 0; i--) { // Different numbers if (a[0] != a[i]) { ind1 = i; break; } } var ind2 = 0; // Iteratively check from // the beginning for (i = 0; i < n - 1; i++) { // Different numbers if (a[n - 1] != a[i]) { ind2 = (n - 1 - i); break; } } return Math.max(ind1, ind2); } // Driver code var a = [ 1, 2, 3, 2, 3 ]; var n = a.length; document.write(findMaximumDiff(a, n)); // This code is contributed by todaysgaurav</script>", "e": 5393, "s": 4538, "text": null }, { "code": null, "e": 5395, "s": 5393, "text": "4" }, { "code": null, "e": 5440, "s": 5397, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 5455, "s": 5440, "text": "mohit kumar 29" }, { "code": null, "e": 5463, "s": 5455, "text": "ankthon" }, { "code": null, "e": 5476, "s": 5463, "text": "Mithun Kumar" }, { "code": null, "e": 5489, "s": 5476, "text": "Akanksha_Rai" }, { "code": null, "e": 5502, "s": 5489, "text": "todaysgaurav" }, { "code": null, "e": 5514, "s": 5502, "text": "rishavnitro" }, { "code": null, "e": 5521, "s": 5514, "text": "Arrays" }, { "code": null, "e": 5545, "s": 5521, "text": "Competitive Programming" }, { "code": null, "e": 5558, "s": 5545, "text": "Mathematical" }, { "code": null, "e": 5565, "s": 5558, "text": "Arrays" }, { "code": null, "e": 5578, "s": 5565, "text": "Mathematical" }, { "code": null, "e": 5676, "s": 5578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5708, "s": 5676, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5731, "s": 5708, "text": "Introduction to Arrays" }, { "code": null, "e": 5816, "s": 5731, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 5872, "s": 5816, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 5899, "s": 5872, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 5942, "s": 5899, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 5985, "s": 5942, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 6026, "s": 5985, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 6053, "s": 6026, "text": "Modulo 10^9+7 (1000000007)" } ]
Report Styles
JasperReports has a feature <style> which helps to control text properties in a report template. This element is a collection of style settings declared at the report level. Properties like foreground color, background color, whether the font is bold, italic, or normal, the font size, a border for the font, and many other attributes are controlled by <style> element. Styles can extend other styles, and add to, or override properties of the parent style as well. A <style> element has many attributes. Some of the most commonly used are listed in the table given below − name Is mandatory. It must be unique because it references the corresponding report style throughout the report. isDefault Indicates whether this style is the document's default style. style Is a reference to the parent style. mode Specifies the element's transparency. Possible values are Opaque and Transparent. forecolor Is the foreground color of object. backcolor Is the background color of object. fill Determines the fill pattern used to fill the object. At the moment, the single value allowed is Solid. radius Specifies the radius of the rectangle's corner arc. scaleImage Specifies scale for the images only. Possible values: Clip, FillFrame, RetainShape, RealHeight, and RealSize. hAlign Specifies the horizontal alignment. Possible values: Left, Center, Right, and Justified. vAlign Specifies the vertical alignment. Possible values: Top, Middle, and Bottom. rotation Specifies the element's rotation. Possible values: None, Left, Right, and UpsideDown. lineSpacing Specifies the line spacing between lines of text. Possible values: Single, 1_1_2, Double. markup Specifies the markup style for styled texts. fontName Specifies the font name. fontSize Specifies the font size. isBold Indicates if the font style is bold. isItalic Indicates if the font style is italic. isUnderline Indicates if the font style is underline. isStrikeThrough Indicates if the font style is strikethrough. pdfFontName Specifies the related PDF font name. pdfEncoding Specifies the character encoding for the PDF output format. isPdfEmbedded Indicates if the PDF font is embedded. pattern Specifies the format pattern for formatted texts. isBlankWhenNull Indicates if an empty string (whitespace) should be shown if the expression evaluates to null. In some situations, a style should be applied only when certain condition is met (for example, to alternate adjacent row colors in a report detail section). This can be achieved using conditional styles. A conditional style has two elements − a Boolean condition expression a style The style is used only if the condition evaluates to true. Any type of report element can reference a report style definition using the style attribute. Hence, all the style properties declared by the style definition that are applicable to the current element will be inherited. To override the inherited values, style properties specified at the report element level can be used. We can make a set of reports with a common look by defining the style at a common place. This common style template can then be referenced by the report templates. A style template is an XML file that contains one or more style definitions. Style template files used by convention the *.jrtx extension, but this is not mandatory. A style template contains following elements − <jasperTemplate> − This is the root element of a style template file. <jasperTemplate> − This is the root element of a style template file. <template> − This element is used to include references to other template files. The contents of this element are interpreted as the location of the referred template file. <template> − This element is used to include references to other template files. The contents of this element are interpreted as the location of the referred template file. <style> − This element is identical to the element with the same name from report design templates (JRXML files), with the exception that a style in a style template cannot contain conditional styles. This limitation is caused by the fact that conditional styles involve report expressions, and expressions can only be interpreted in the context of a single report definition. <style> − This element is identical to the element with the same name from report design templates (JRXML files), with the exception that a style in a style template cannot contain conditional styles. This limitation is caused by the fact that conditional styles involve report expressions, and expressions can only be interpreted in the context of a single report definition. References to style templates are included in JRXML reports as <template> elements. The style templates are loaded at report fill time, and style name references are resolved once all the templates have been loaded. When loading style templates and resolving style names to styles, a tree/graph of style templates is created, the top of the tree being the set of styles defined in the report. On this tree, style name references are resolved to the last style that matches the name in a depth-first traversal. Let's try out the conditional styles and style templates. Let's add the <style> element alternateStyle to our existing report template (Chapter Report Designs). Based on the condition, font color changes to blue for even count. We have also included a style template "styles.jrtx". The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test directory − <?xml version = "1.0"?> <!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"> <jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name = "jasper_report_template" pageWidth = "595" pageHeight = "842" columnWidth = "515" leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50"> <template>"styles.jrtx"</template> <style name = "alternateStyle" fontName = "Arial" forecolor = "red"> <conditionalStyle> <conditionExpression> <![CDATA[new Boolean($V{countNumber}.intValue() % 2 == 0)]]> </conditionExpression> <style forecolor = "blue" isBold = "true"/> </conditionalStyle> </style> <parameter name = "ReportTitle" class = "java.lang.String"/> <parameter name = "Author" class = "java.lang.String"/> <queryString> <![CDATA[]]> </queryString> <field name = "country" class = "java.lang.String"> <fieldDescription><![CDATA[country]]></fieldDescription> </field> <field name = "name" class = "java.lang.String"> <fieldDescription><![CDATA[name]]></fieldDescription> </field> <variable name = "countNumber" class = "java.lang.Integer" calculation = "Count"> <variableExpression><![CDATA[Boolean.TRUE]]></variableExpression> </variable> <title> <band height = "70"> <line> <reportElement x = "0" y = "0" width = "515" height = "1"/> </line> <textField isBlankWhenNull = "true" bookmarkLevel = "1"> <reportElement x = "0" y = "10" width = "515" height = "30"/> <textElement textAlignment = "Center"> <font size = "22"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$P{ReportTitle}]]> </textFieldExpression> <anchorNameExpression><![CDATA["Title"]]></anchorNameExpression> </textField> <textField isBlankWhenNull = "true"> <reportElement x = "0" y = "40" width = "515" height = "20"/> <textElement textAlignment = "Center"> <font size = "10"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$P{Author}]]> </textFieldExpression> </textField> </band> </title> <columnHeader> <band height = "23"> <staticText> <reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15" backcolor = "#70A9A9" /> <box> <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" /> </box> <textElement /> <text> <![CDATA[]]> </text> </staticText> <staticText> <reportElement x = "414" y = "3" width = "121" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font isBold = "true" /> </textElement> <text><![CDATA[Country]]></text> </staticText> <staticText> <reportElement x = "0" y = "3" width = "136" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font isBold = "true" /> </textElement> <text><![CDATA[Name]]></text> </staticText> </band> </columnHeader> <detail> <band height = "16"> <staticText> <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14" backcolor = "#E5ECF9" /> <box> <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" /> </box> <textElement /> <text> <![CDATA[]]> </text> </staticText> <textField> <reportElement style = "alternateStyle" x = "414" y = "0" width = "121" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font size = "9" /> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{country}]]> </textFieldExpression> </textField> <textField> <reportElement x = "0" y = "0" width = "136" height = "15" style = "Strong"/> <textElement textAlignment = "Center" verticalAlignment = "Middle" /> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{name}]]> </textFieldExpression> </textField> </band> </detail> </jasperReport> The contents of style template styles.jrtx are as follows. Save it to C:\tools\jasperreports-5.0.1\test directory. <?xml version = "1.0"?> <!DOCTYPE jasperTemplate PUBLIC "-//JasperReports//DTD Template//EN" "http://jasperreports.sourceforge.net/dtds/jaspertemplate.dtd"> <jasperTemplate> <style name = "Strong" isBold = "true" pdfFontName = "Helvetica-Bold" backcolor = "lightGray forecolor = "green"/> </jasperTemplate> The java codes for report filling remain unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below − package com.tutorialspoint; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; public class JasperReportFill { @SuppressWarnings("unchecked") public static void main(String[] args) { String sourceFileName = "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper"; DataBeanList DataBeanList = new DataBeanList(); ArrayList<DataBean> dataList = DataBeanList.getDataBeanList(); JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList); Map parameters = new HashMap(); /** * Passing ReportTitle and Author as parameters */ parameters.put("ReportTitle", "List of Contacts"); parameters.put("Author", "Prepared By Manisha"); try { JasperFillManager.fillReportToFile( sourceFileName, parameters, beanColDataSource); } catch (JRException e) { e.printStackTrace(); } } } The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as below − package com.tutorialspoint; public class DataBean { private String name; private String country; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as below − package com.tutorialspoint; import java.util.ArrayList; public class DataBeanList { public ArrayList<DataBean> getDataBeanList() { ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>(); dataBeanList.add(produce("Manisha", "India")); dataBeanList.add(produce("Dennis Ritchie", "USA")); dataBeanList.add(produce("V.Anand", "India")); dataBeanList.add(produce("Shrinath", "California")); return dataBeanList; } /** * This method returns a DataBean object, * with name and country set in it. */ private DataBean produce(String name, String country) { DataBean dataBean = new DataBean(); dataBean.setName(name); dataBean.setCountry(country); return dataBean; } } We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below. The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml. <?xml version = "1.0" encoding = "UTF-8"?> <project name = "JasperReportTest" default = "viewFillReport" basedir = "."> <import file = "baseBuild.xml" /> <target name = "viewFillReport" depends = "compile,compilereportdesing,run" description = "Launches the report viewer to preview the report stored in the .JRprint file."> <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true"> <arg value = "-F${file.name}.JRprint" /> <classpath refid = "classpath" /> </java> </target> <target name = "compilereportdesing" description = "Compiles the JXML file and produces the .jasper file."> <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask"> <classpath refid = "classpath" /> </taskdef> <jrc destdir = "."> <src> <fileset dir = "."> <include name = "*.jrxml" /> </fileset> </src> <classpath refid = "classpath" /> </jrc> </target> </project> Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as − C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml clean-sample: [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint compile: [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds [javac] Compiling 3 source files to C:\tools\jasperreports-5.0.1\test\classes compilereportdesing: [jrc] Compiling 1 report design files. [jrc] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory). [jrc] log4j:WARN Please initialize the log4j system properly. [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK. run: [echo] Runnin class : com.tutorialspoint.JasperReportFill [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. viewFillReport: [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. As a result of above compilation, a JasperViewer window opens up as shown in the screen given below − Here, we can see that the color of the font is changed to blue for even count (in column country). In the column name, the font color is changed to green (this style is referenced from the style template).
[ { "code": null, "e": 2854, "s": 2388, "text": "JasperReports has a feature <style> which helps to control text properties in a report template. This element is a collection of style settings declared at the report level. Properties like foreground color, background color, whether the font is bold, italic, or normal, the font size, a border for the font, and many other attributes are controlled by <style> element. Styles can extend other styles, and add to, or override properties of the parent style as well." }, { "code": null, "e": 2962, "s": 2854, "text": "A <style> element has many attributes. Some of the most commonly used are listed in the table given below −" }, { "code": null, "e": 2967, "s": 2962, "text": "name" }, { "code": null, "e": 3075, "s": 2967, "text": "Is mandatory. It must be unique because it references the corresponding report style throughout the report." }, { "code": null, "e": 3085, "s": 3075, "text": "isDefault" }, { "code": null, "e": 3147, "s": 3085, "text": "Indicates whether this style is the document's default style." }, { "code": null, "e": 3153, "s": 3147, "text": "style" }, { "code": null, "e": 3189, "s": 3153, "text": "Is a reference to the parent style." }, { "code": null, "e": 3194, "s": 3189, "text": "mode" }, { "code": null, "e": 3276, "s": 3194, "text": "Specifies the element's transparency. Possible values are Opaque and Transparent." }, { "code": null, "e": 3286, "s": 3276, "text": "forecolor" }, { "code": null, "e": 3321, "s": 3286, "text": "Is the foreground color of object." }, { "code": null, "e": 3331, "s": 3321, "text": "backcolor" }, { "code": null, "e": 3366, "s": 3331, "text": "Is the background color of object." }, { "code": null, "e": 3371, "s": 3366, "text": "fill" }, { "code": null, "e": 3474, "s": 3371, "text": "Determines the fill pattern used to fill the object. At the moment, the single value allowed is Solid." }, { "code": null, "e": 3481, "s": 3474, "text": "radius" }, { "code": null, "e": 3533, "s": 3481, "text": "Specifies the radius of the rectangle's corner arc." }, { "code": null, "e": 3544, "s": 3533, "text": "scaleImage" }, { "code": null, "e": 3654, "s": 3544, "text": "Specifies scale for the images only. Possible values: Clip, FillFrame, RetainShape, RealHeight, and RealSize." }, { "code": null, "e": 3661, "s": 3654, "text": "hAlign" }, { "code": null, "e": 3750, "s": 3661, "text": "Specifies the horizontal alignment. Possible values: Left, Center, Right, and Justified." }, { "code": null, "e": 3757, "s": 3750, "text": "vAlign" }, { "code": null, "e": 3833, "s": 3757, "text": "Specifies the vertical alignment. Possible values: Top, Middle, and Bottom." }, { "code": null, "e": 3842, "s": 3833, "text": "rotation" }, { "code": null, "e": 3928, "s": 3842, "text": "Specifies the element's rotation. Possible values: None, Left, Right, and UpsideDown." }, { "code": null, "e": 3940, "s": 3928, "text": "lineSpacing" }, { "code": null, "e": 4030, "s": 3940, "text": "Specifies the line spacing between lines of text. Possible values: Single, 1_1_2, Double." }, { "code": null, "e": 4037, "s": 4030, "text": "markup" }, { "code": null, "e": 4082, "s": 4037, "text": "Specifies the markup style for styled texts." }, { "code": null, "e": 4091, "s": 4082, "text": "fontName" }, { "code": null, "e": 4116, "s": 4091, "text": "Specifies the font name." }, { "code": null, "e": 4125, "s": 4116, "text": "fontSize" }, { "code": null, "e": 4150, "s": 4125, "text": "Specifies the font size." }, { "code": null, "e": 4157, "s": 4150, "text": "isBold" }, { "code": null, "e": 4194, "s": 4157, "text": "Indicates if the font style is bold." }, { "code": null, "e": 4203, "s": 4194, "text": "isItalic" }, { "code": null, "e": 4242, "s": 4203, "text": "Indicates if the font style is italic." }, { "code": null, "e": 4254, "s": 4242, "text": "isUnderline" }, { "code": null, "e": 4296, "s": 4254, "text": "Indicates if the font style is underline." }, { "code": null, "e": 4312, "s": 4296, "text": "isStrikeThrough" }, { "code": null, "e": 4358, "s": 4312, "text": "Indicates if the font style is strikethrough." }, { "code": null, "e": 4370, "s": 4358, "text": "pdfFontName" }, { "code": null, "e": 4407, "s": 4370, "text": "Specifies the related PDF font name." }, { "code": null, "e": 4419, "s": 4407, "text": "pdfEncoding" }, { "code": null, "e": 4479, "s": 4419, "text": "Specifies the character encoding for the PDF output format." }, { "code": null, "e": 4493, "s": 4479, "text": "isPdfEmbedded" }, { "code": null, "e": 4532, "s": 4493, "text": "Indicates if the PDF font is embedded." }, { "code": null, "e": 4540, "s": 4532, "text": "pattern" }, { "code": null, "e": 4590, "s": 4540, "text": "Specifies the format pattern for formatted texts." }, { "code": null, "e": 4606, "s": 4590, "text": "isBlankWhenNull" }, { "code": null, "e": 4701, "s": 4606, "text": "Indicates if an empty string (whitespace) should be shown if the expression evaluates to null." }, { "code": null, "e": 4905, "s": 4701, "text": "In some situations, a style should be applied only when certain condition is met (for example, to alternate adjacent row colors in a report detail section). This can be achieved using conditional styles." }, { "code": null, "e": 4944, "s": 4905, "text": "A conditional style has two elements −" }, { "code": null, "e": 4975, "s": 4944, "text": "a Boolean condition expression" }, { "code": null, "e": 4983, "s": 4975, "text": "a style" }, { "code": null, "e": 5042, "s": 4983, "text": "The style is used only if the condition evaluates to true." }, { "code": null, "e": 5365, "s": 5042, "text": "Any type of report element can reference a report style definition using the style attribute. Hence, all the style properties declared by the style definition that are applicable to the current element will be inherited. To override the inherited values, style properties specified at the report element level can be used." }, { "code": null, "e": 5695, "s": 5365, "text": "We can make a set of reports with a common look by defining the style at a common place. This common style template can then be referenced by the report templates. A style template is an XML file that contains one or more style definitions. Style template files used by convention the *.jrtx extension, but this is not mandatory." }, { "code": null, "e": 5742, "s": 5695, "text": "A style template contains following elements −" }, { "code": null, "e": 5812, "s": 5742, "text": "<jasperTemplate> − This is the root element of a style template file." }, { "code": null, "e": 5882, "s": 5812, "text": "<jasperTemplate> − This is the root element of a style template file." }, { "code": null, "e": 6055, "s": 5882, "text": "<template> − This element is used to include references to other template files. The contents of this element are interpreted as the location of the referred template file." }, { "code": null, "e": 6228, "s": 6055, "text": "<template> − This element is used to include references to other template files. The contents of this element are interpreted as the location of the referred template file." }, { "code": null, "e": 6605, "s": 6228, "text": "<style> − This element is identical to the element with the same name from report design templates (JRXML files), with the exception that a style in a style template cannot contain conditional styles. This limitation is caused by the fact that conditional styles involve report expressions, and expressions can only be interpreted in the context of a single report definition." }, { "code": null, "e": 6982, "s": 6605, "text": "<style> − This element is identical to the element with the same name from report design templates (JRXML files), with the exception that a style in a style template cannot contain conditional styles. This limitation is caused by the fact that conditional styles involve report expressions, and expressions can only be interpreted in the context of a single report definition." }, { "code": null, "e": 7492, "s": 6982, "text": "References to style templates are included in JRXML reports as <template> elements. The style templates are loaded at report fill time, and style name references are resolved once all the templates have been loaded. When loading style templates and resolving style names to styles, a tree/graph of style templates is created, the top of the tree being the set of styles defined in the report. On this tree, style name references are resolved to the last style that matches the name in a depth-first traversal." }, { "code": null, "e": 7905, "s": 7492, "text": "Let's try out the conditional styles and style templates. Let's add the <style> element alternateStyle to our existing report template (Chapter Report Designs). Based on the condition, font color changes to blue for even count. We have also included a style template \"styles.jrtx\". The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\\tools\\jasperreports-5.0.1\\test directory −" }, { "code": null, "e": 13184, "s": 7905, "text": "<?xml version = \"1.0\"?>\n<!DOCTYPE jasperReport PUBLIC\n \"//JasperReports//DTD Report Design//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd\">\n\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"jasper_report_template\" pageWidth = \"595\"\n pageHeight = \"842\" columnWidth = \"515\"\n leftMargin = \"40\" rightMargin = \"40\" topMargin = \"50\" bottomMargin = \"50\">\n\t\n <template>\"styles.jrtx\"</template>\n \n <style name = \"alternateStyle\" fontName = \"Arial\" forecolor = \"red\">\n <conditionalStyle>\n <conditionExpression>\n <![CDATA[new Boolean($V{countNumber}.intValue() % 2 == 0)]]>\n </conditionExpression>\n\t\t\t\n <style forecolor = \"blue\" isBold = \"true\"/>\n </conditionalStyle>\n </style>\n \n <parameter name = \"ReportTitle\" class = \"java.lang.String\"/>\n <parameter name = \"Author\" class = \"java.lang.String\"/>\n\n <queryString>\n <![CDATA[]]>\n </queryString>\n\n <field name = \"country\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[country]]></fieldDescription>\n </field>\n\n <field name = \"name\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[name]]></fieldDescription>\n </field>\n\n <variable name = \"countNumber\" class = \"java.lang.Integer\" calculation = \"Count\">\n <variableExpression><![CDATA[Boolean.TRUE]]></variableExpression>\n </variable>\n\n <title>\n <band height = \"70\">\n \n <line>\n <reportElement x = \"0\" y = \"0\" width = \"515\" height = \"1\"/>\n </line>\n \n <textField isBlankWhenNull = \"true\" bookmarkLevel = \"1\">\n <reportElement x = \"0\" y = \"10\" width = \"515\" height = \"30\"/>\n\t\t\t\t\n <textElement textAlignment = \"Center\">\n <font size = \"22\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{ReportTitle}]]>\n </textFieldExpression>\n \n <anchorNameExpression><![CDATA[\"Title\"]]></anchorNameExpression>\n </textField>\n\n <textField isBlankWhenNull = \"true\">\n <reportElement x = \"0\" y = \"40\" width = \"515\" height = \"20\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"10\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{Author}]]>\n </textFieldExpression>\n\t\t\t\t\n </textField>\n \n </band>\n </title>\n\n <columnHeader>\n <band height = \"23\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"3\" \n width = \"535\" height = \"15\" backcolor = \"#70A9A9\" />\n \n <box>\n <bottomPen lineWidth = \"1.0\" lineColor = \"#CCCCCC\" />\n </box>\n\t\t\t\t\n <textElement />\n\t\t\t\t\n <text>\n <![CDATA[]]>\n </text>\n\t\t\t\t\n </staticText>\n \n <staticText>\n <reportElement x = \"414\" y = \"3\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n\t\t\t\t\n <text><![CDATA[Country]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"3\" width = \"136\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n\t\t\t\t\n <text><![CDATA[Name]]></text>\n </staticText>\n \n </band>\n </columnHeader>\n\n <detail>\n <band height = \"16\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"0\" \n width = \"535\" height = \"14\" backcolor = \"#E5ECF9\" />\n \n <box>\n <bottomPen lineWidth = \"0.25\" lineColor = \"#CCCCCC\" />\n </box>\n \n <textElement />\n\t\t\t\t\n <text>\n <![CDATA[]]>\n </text>\n\t\t\t\t\n </staticText>\n \n <textField>\n <reportElement style = \"alternateStyle\" x = \"414\" y = \"0\" \n width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font size = \"9\" />\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{country}]]>\n </textFieldExpression>\n </textField>\n \n <textField>\n <reportElement x = \"0\" y = \"0\" width = \"136\" height = \"15\" \n style = \"Strong\"/>\n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\" />\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{name}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </detail>\n\n</jasperReport>" }, { "code": null, "e": 13299, "s": 13184, "text": "The contents of style template styles.jrtx are as follows. Save it to C:\\tools\\jasperreports-5.0.1\\test directory." }, { "code": null, "e": 13620, "s": 13299, "text": "<?xml version = \"1.0\"?>\n\n<!DOCTYPE jasperTemplate PUBLIC \"-//JasperReports//DTD Template//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jaspertemplate.dtd\">\n\n<jasperTemplate>\n <style name = \"Strong\" isBold = \"true\" pdfFontName = \"Helvetica-Bold\" \n backcolor = \"lightGray forecolor = \"green\"/>\n</jasperTemplate>" }, { "code": null, "e": 13797, "s": 13620, "text": "The java codes for report filling remain unchanged. The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\JasperReportFill.java are as given below −" }, { "code": null, "e": 14939, "s": 13797, "text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperFillManager;\nimport net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;\n\npublic class JasperReportFill {\n @SuppressWarnings(\"unchecked\")\n public static void main(String[] args) {\n String sourceFileName = \n \"C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper\";\n\n DataBeanList DataBeanList = new DataBeanList();\n ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();\n\n JRBeanCollectionDataSource beanColDataSource = new \n JRBeanCollectionDataSource(dataList);\n\n Map parameters = new HashMap();\n /**\n * Passing ReportTitle and Author as parameters\n */\n parameters.put(\"ReportTitle\", \"List of Contacts\");\n parameters.put(\"Author\", \"Prepared By Manisha\");\n\n try {\n JasperFillManager.fillReportToFile(\n sourceFileName, parameters, beanColDataSource);\n } catch (JRException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 15055, "s": 14939, "text": "The contents of the POJO file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBean.java are as below −" }, { "code": null, "e": 15423, "s": 15055, "text": "package com.tutorialspoint;\n\npublic class DataBean {\n private String name;\n private String country;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n}" }, { "code": null, "e": 15538, "s": 15423, "text": "The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBeanList.java are as below −" }, { "code": null, "e": 16302, "s": 15538, "text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\n\npublic class DataBeanList {\n public ArrayList<DataBean> getDataBeanList() {\n ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();\n\n dataBeanList.add(produce(\"Manisha\", \"India\"));\n dataBeanList.add(produce(\"Dennis Ritchie\", \"USA\"));\n dataBeanList.add(produce(\"V.Anand\", \"India\"));\n dataBeanList.add(produce(\"Shrinath\", \"California\"));\n\n return dataBeanList;\n }\n\n /**\n * This method returns a DataBean object,\n * with name and country set in it.\n */\n private DataBean produce(String name, String country) {\n DataBean dataBean = new DataBean();\n dataBean.setName(name);\n dataBean.setCountry(country);\n \n return dataBean;\n }\n}" }, { "code": null, "e": 16495, "s": 16302, "text": "We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\\tools\\jasperreports-5.0.1\\test) are as given below." }, { "code": null, "e": 16636, "s": 16495, "text": "The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml." }, { "code": null, "e": 17714, "s": 16636, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"viewFillReport\" basedir = \".\">\n <import file = \"baseBuild.xml\" />\n \n <target name = \"viewFillReport\" depends = \"compile,compilereportdesing,run\"\n description = \"Launches the report viewer to preview the \n report stored in the .JRprint file.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.JRprint\" />\n <classpath refid = \"classpath\" />\n </java>\n\t\t\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\" classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n\t\t\n </target>\n\n</project>" }, { "code": null, "e": 17928, "s": 17714, "text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −" }, { "code": null, "e": 19560, "s": 17928, "text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\nclean-sample:\n [delete] Deleting directory C:\\tools\\jasperreports-5.0.1\\test\\classes\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jasper\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrprint\n\ncompile:\n [mkdir] Created dir: C:\\tools\\jasperreports-5.0.1\\test\\classes\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:28: warning:\n 'includeantruntime' was not set, defaulting to build.sysclasspath=last;\n set to false for repeatable builds\n [javac] Compiling 3 source files to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See\n http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.\n [jrc] File : C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml ... OK.\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperReportFill\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nviewFillReport:\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n" }, { "code": null, "e": 19662, "s": 19560, "text": "As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −" } ]
Secure Electronic Transaction (SET) Protocol
31 Aug, 2021 Secure Electronic Transaction or SET is a system that ensures the security and integrity of electronic transactions done using credit cards in a scenario. SET is not some system that enables payment but it is a security protocol applied to those payments. It uses different encryption and hashing techniques to secure payments over the internet done through credit cards. The SET protocol was supported in development by major organizations like Visa, Mastercard, Microsoft which provided its Secure Transaction Technology (STT), and Netscape which provided the technology of Secure Socket Layer (SSL). SET protocol restricts the revealing of credit card details to merchants thus keeping hackers and thieves at bay. The SET protocol includes Certification Authorities for making use of standard Digital Certificates like X.509 Certificate. Before discussing SET further, let’s see a general scenario of electronic transactions, which includes client, payment gateway, client financial institution, merchant, and merchant financial institution. Requirements in SET : The SET protocol has some requirements to meet, some of the important requirements are : It has to provide mutual authentication i.e., customer (or cardholder) authentication by confirming if the customer is an intended user or not, and merchant authentication. It has to keep the PI (Payment Information) and OI (Order Information) confidential by appropriate encryptions. It has to be resistive against message modifications i.e., no changes should be allowed in the content being transmitted. SET also needs to provide interoperability and make use of the best security mechanisms. Participants in SET : In the general scenario of online transactions, SET includes similar participants: Cardholder – customerIssuer – customer financial institutionMerchantAcquirer – Merchant financialCertificate authority – Authority that follows certain standards and issues certificates(like X.509V3) to all other participants. Cardholder – customer Issuer – customer financial institution Merchant Acquirer – Merchant financial Certificate authority – Authority that follows certain standards and issues certificates(like X.509V3) to all other participants. Provide AuthenticationMerchant Authentication – To prevent theft, SET allows customers to check previous relationships between merchants and financial institutions. Standard X.509V3 certificates are used for this verification.Customer / Cardholder Authentication – SET checks if the use of a credit card is done by an authorized user or not using X.509V3 certificates. Merchant Authentication – To prevent theft, SET allows customers to check previous relationships between merchants and financial institutions. Standard X.509V3 certificates are used for this verification. Customer / Cardholder Authentication – SET checks if the use of a credit card is done by an authorized user or not using X.509V3 certificates. Provide Message Confidentiality: Confidentiality refers to preventing unintended people from reading the message being transferred. SET implements confidentiality by using encryption techniques. Traditionally DES is used for encryption purposes. Provide Message Integrity: SET doesn’t allow message modification with the help of signatures. Messages are protected against unauthorized modification using RSA digital signatures with SHA-1 and some using HMAC with SHA-1, Dual Signature : The dual signature is a concept introduced with SET, which aims at connecting two information pieces meant for two different receivers : Order Information (OI) for merchant Payment Information (PI) for bank You might think sending them separately is an easy and more secure way, but sending them in a connected form resolves any future dispute possible. Here is the generation of dual signature: Where, PI stands for payment information OI stands for order information PIMD stands for Payment Information Message Digest OIMD stands for Order Information Message Digest POMD stands for Payment Order Message Digest H stands for Hashing E stands for public key encryption KPc is customer's private key || stands for append operation Dual signature, DS= E(KPc, [H(H(PI)||H(OI))]) Purchase Request Generation : The process of purchase request generation requires three inputs: Payment Information (PI) Dual Signature Order Information Message Digest (OIMD) The purchase request is generated as follows: Here, PI, OIMD, OI all have the same meanings as before. The new things are : EP which is symmetric key encryption Ks is a temporary symmetric key KUbank is public key of bank CA is Cardholder or customer Certificate Digital Envelope = E(KUbank, Ks) Purchase Request Validation on Merchant Side : The Merchant verifies by comparing POMD generated through PIMD hashing with POMD generated through decryption of Dual Signature as follows: Since we used Customer’s private key in encryption here we use KUC which is the public key of the customer or cardholder for decryption ‘D’. Payment Authorization and Payment Capture : Payment authorization as the name suggests is the authorization of payment information by the merchant which ensures payment will be received by the merchant. Payment capture is the process by which a merchant receives payment which includes again generating some request blocks to gateway and payment gateway in turn issues payment to the merchant. chhabradhanvi Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 GSM in Wireless Communication Wireless Application Protocol TCP 3-Way Handshake Process Mobile Internet Protocol (or Mobile IP) UDP Server-Client implementation in C User Datagram Protocol (UDP) Introduction of Mobile Ad hoc Network (MANET) Advanced Encryption Standard (AES) Types of area networks - LAN, MAN and WAN
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Aug, 2021" }, { "code": null, "e": 658, "s": 54, "text": "Secure Electronic Transaction or SET is a system that ensures the security and integrity of electronic transactions done using credit cards in a scenario. SET is not some system that enables payment but it is a security protocol applied to those payments. It uses different encryption and hashing techniques to secure payments over the internet done through credit cards. The SET protocol was supported in development by major organizations like Visa, Mastercard, Microsoft which provided its Secure Transaction Technology (STT), and Netscape which provided the technology of Secure Socket Layer (SSL). " }, { "code": null, "e": 897, "s": 658, "text": "SET protocol restricts the revealing of credit card details to merchants thus keeping hackers and thieves at bay. The SET protocol includes Certification Authorities for making use of standard Digital Certificates like X.509 Certificate. " }, { "code": null, "e": 1103, "s": 897, "text": "Before discussing SET further, let’s see a general scenario of electronic transactions, which includes client, payment gateway, client financial institution, merchant, and merchant financial institution. " }, { "code": null, "e": 1216, "s": 1103, "text": "Requirements in SET : The SET protocol has some requirements to meet, some of the important requirements are : " }, { "code": null, "e": 1389, "s": 1216, "text": "It has to provide mutual authentication i.e., customer (or cardholder) authentication by confirming if the customer is an intended user or not, and merchant authentication." }, { "code": null, "e": 1501, "s": 1389, "text": "It has to keep the PI (Payment Information) and OI (Order Information) confidential by appropriate encryptions." }, { "code": null, "e": 1623, "s": 1501, "text": "It has to be resistive against message modifications i.e., no changes should be allowed in the content being transmitted." }, { "code": null, "e": 1712, "s": 1623, "text": "SET also needs to provide interoperability and make use of the best security mechanisms." }, { "code": null, "e": 1819, "s": 1712, "text": "Participants in SET : In the general scenario of online transactions, SET includes similar participants: " }, { "code": null, "e": 2046, "s": 1819, "text": "Cardholder – customerIssuer – customer financial institutionMerchantAcquirer – Merchant financialCertificate authority – Authority that follows certain standards and issues certificates(like X.509V3) to all other participants." }, { "code": null, "e": 2068, "s": 2046, "text": "Cardholder – customer" }, { "code": null, "e": 2108, "s": 2068, "text": "Issuer – customer financial institution" }, { "code": null, "e": 2117, "s": 2108, "text": "Merchant" }, { "code": null, "e": 2147, "s": 2117, "text": "Acquirer – Merchant financial" }, { "code": null, "e": 2277, "s": 2147, "text": "Certificate authority – Authority that follows certain standards and issues certificates(like X.509V3) to all other participants." }, { "code": null, "e": 2646, "s": 2277, "text": "Provide AuthenticationMerchant Authentication – To prevent theft, SET allows customers to check previous relationships between merchants and financial institutions. Standard X.509V3 certificates are used for this verification.Customer / Cardholder Authentication – SET checks if the use of a credit card is done by an authorized user or not using X.509V3 certificates." }, { "code": null, "e": 2851, "s": 2646, "text": "Merchant Authentication – To prevent theft, SET allows customers to check previous relationships between merchants and financial institutions. Standard X.509V3 certificates are used for this verification." }, { "code": null, "e": 2994, "s": 2851, "text": "Customer / Cardholder Authentication – SET checks if the use of a credit card is done by an authorized user or not using X.509V3 certificates." }, { "code": null, "e": 3240, "s": 2994, "text": "Provide Message Confidentiality: Confidentiality refers to preventing unintended people from reading the message being transferred. SET implements confidentiality by using encryption techniques. Traditionally DES is used for encryption purposes." }, { "code": null, "e": 3464, "s": 3240, "text": "Provide Message Integrity: SET doesn’t allow message modification with the help of signatures. Messages are protected against unauthorized modification using RSA digital signatures with SHA-1 and some using HMAC with SHA-1," }, { "code": null, "e": 3689, "s": 3464, "text": "Dual Signature : The dual signature is a concept introduced with SET, which aims at connecting two information pieces meant for two different receivers : Order Information (OI) for merchant Payment Information (PI) for bank " }, { "code": null, "e": 3880, "s": 3689, "text": "You might think sending them separately is an easy and more secure way, but sending them in a connected form resolves any future dispute possible. Here is the generation of dual signature: " }, { "code": null, "e": 4294, "s": 3882, "text": "Where,\n\n PI stands for payment information\n OI stands for order information\n PIMD stands for Payment Information Message Digest\n OIMD stands for Order Information Message Digest\n POMD stands for Payment Order Message Digest\n H stands for Hashing\n E stands for public key encryption\n KPc is customer's private key\n || stands for append operation\n Dual signature, DS= E(KPc, [H(H(PI)||H(OI))])" }, { "code": null, "e": 4324, "s": 4294, "text": "Purchase Request Generation :" }, { "code": null, "e": 4391, "s": 4324, "text": "The process of purchase request generation requires three inputs: " }, { "code": null, "e": 4416, "s": 4391, "text": "Payment Information (PI)" }, { "code": null, "e": 4431, "s": 4416, "text": "Dual Signature" }, { "code": null, "e": 4471, "s": 4431, "text": "Order Information Message Digest (OIMD)" }, { "code": null, "e": 4519, "s": 4471, "text": "The purchase request is generated as follows: " }, { "code": null, "e": 4771, "s": 4521, "text": "Here,\nPI, OIMD, OI all have the same meanings as before.\nThe new things are :\nEP which is symmetric key encryption\nKs is a temporary symmetric key\nKUbank is public key of bank\nCA is Cardholder or customer Certificate\nDigital Envelope = E(KUbank, Ks)" }, { "code": null, "e": 4960, "s": 4771, "text": "Purchase Request Validation on Merchant Side : The Merchant verifies by comparing POMD generated through PIMD hashing with POMD generated through decryption of Dual Signature as follows: " }, { "code": null, "e": 5498, "s": 4960, "text": "Since we used Customer’s private key in encryption here we use KUC which is the public key of the customer or cardholder for decryption ‘D’. Payment Authorization and Payment Capture : Payment authorization as the name suggests is the authorization of payment information by the merchant which ensures payment will be received by the merchant. Payment capture is the process by which a merchant receives payment which includes again generating some request blocks to gateway and payment gateway in turn issues payment to the merchant. " }, { "code": null, "e": 5512, "s": 5498, "text": "chhabradhanvi" }, { "code": null, "e": 5530, "s": 5512, "text": "Computer Networks" }, { "code": null, "e": 5548, "s": 5530, "text": "Computer Networks" }, { "code": null, "e": 5646, "s": 5548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5680, "s": 5646, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 5710, "s": 5680, "text": "GSM in Wireless Communication" }, { "code": null, "e": 5740, "s": 5710, "text": "Wireless Application Protocol" }, { "code": null, "e": 5768, "s": 5740, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 5808, "s": 5768, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 5846, "s": 5808, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 5875, "s": 5846, "text": "User Datagram Protocol (UDP)" }, { "code": null, "e": 5921, "s": 5875, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 5956, "s": 5921, "text": "Advanced Encryption Standard (AES)" } ]
Pandas – How to reset index in a given DataFrame
25 Aug, 2021 Let us see how to reset the index of a DataFrame after dropping some of the rows from the DataFrame.Approach : Import the Pandas module.Create a DataFrame.Drop some rows from the DataFrame using the drop() method.Reset the index of the DataFrame using the reset_index() method.Display the DataFrame after each step. Import the Pandas module. Create a DataFrame. Drop some rows from the DataFrame using the drop() method. Reset the index of the DataFrame using the reset_index() method. Display the DataFrame after each step. Python3 # importing the modulesimport pandas as pdimport numpy as np # creating a DataFrameODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Ponting', 'Jayasurya', 'Jayawardene', 'Kohli', 'Haq', 'Kallis', 'Ganguly', 'Dravid'], 'runs': [18426, 14234, 13704, 13430, 12650, 11867, 11739, 11579, 11363, 10889]}df = pd.DataFrame(ODI_runs) # displaying the original DataFrameprint("Original DataFrame :")print(df) # dropping the 0th and the 1st indexdf = df.drop([0, 1]) # displaying the altered DataFrameprint("DataFrame after removing the 0th and 1st row")print(df) # resetting the DataFrame indexdf = df.reset_index() # displaying the DataFrame with new indexprint("Dataframe after resetting the index")print(df) Output : anikakapoor pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2021" }, { "code": null, "e": 140, "s": 28, "text": "Let us see how to reset the index of a DataFrame after dropping some of the rows from the DataFrame.Approach : " }, { "code": null, "e": 346, "s": 140, "text": "Import the Pandas module.Create a DataFrame.Drop some rows from the DataFrame using the drop() method.Reset the index of the DataFrame using the reset_index() method.Display the DataFrame after each step. " }, { "code": null, "e": 372, "s": 346, "text": "Import the Pandas module." }, { "code": null, "e": 392, "s": 372, "text": "Create a DataFrame." }, { "code": null, "e": 451, "s": 392, "text": "Drop some rows from the DataFrame using the drop() method." }, { "code": null, "e": 516, "s": 451, "text": "Reset the index of the DataFrame using the reset_index() method." }, { "code": null, "e": 556, "s": 516, "text": "Display the DataFrame after each step. " }, { "code": null, "e": 564, "s": 556, "text": "Python3" }, { "code": "# importing the modulesimport pandas as pdimport numpy as np # creating a DataFrameODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Ponting', 'Jayasurya', 'Jayawardene', 'Kohli', 'Haq', 'Kallis', 'Ganguly', 'Dravid'], 'runs': [18426, 14234, 13704, 13430, 12650, 11867, 11739, 11579, 11363, 10889]}df = pd.DataFrame(ODI_runs) # displaying the original DataFrameprint(\"Original DataFrame :\")print(df) # dropping the 0th and the 1st indexdf = df.drop([0, 1]) # displaying the altered DataFrameprint(\"DataFrame after removing the 0th and 1st row\")print(df) # resetting the DataFrame indexdf = df.reset_index() # displaying the DataFrame with new indexprint(\"Dataframe after resetting the index\")print(df)", "e": 1338, "s": 564, "text": null }, { "code": null, "e": 1349, "s": 1338, "text": "Output : " }, { "code": null, "e": 1367, "s": 1355, "text": "anikakapoor" }, { "code": null, "e": 1392, "s": 1367, "text": "pandas-dataframe-program" }, { "code": null, "e": 1416, "s": 1392, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1430, "s": 1416, "text": "Python-pandas" }, { "code": null, "e": 1437, "s": 1430, "text": "Python" }, { "code": null, "e": 1535, "s": 1437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1567, "s": 1535, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1594, "s": 1567, "text": "Python Classes and Objects" }, { "code": null, "e": 1615, "s": 1594, "text": "Python OOPs Concepts" }, { "code": null, "e": 1638, "s": 1615, "text": "Introduction To PYTHON" }, { "code": null, "e": 1694, "s": 1638, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1725, "s": 1694, "text": "Python | os.path.join() method" }, { "code": null, "e": 1767, "s": 1725, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1809, "s": 1767, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1848, "s": 1809, "text": "Python | Get unique values from a list" } ]
basic_istream::peek() in C++ with Examples
28 May, 2020 The std::basic_istream::peek() used to reads the next character from the input stream without extracting it. This function does not accept any parameter, simply returns the next character in the input string. Below is the syntax for the same: Header File: #include<iostream> Syntax: int peek(); Return Value: The std::basic_istream::peek() return a next character in the input string. Below are the programs to understand the implementation of std::basic_istream::peek() in a better way: Program 1: // C++ code for std::basic_istream::peek()#include <bits/stdc++.h>using namespace std; // main methodint main(){ istringstream gfg("GeeksforGeeks"); char c1 = gfg.peek(); char c2 = gfg.get(); char c3 = gfg.get(); cout << "The first character is: " << c1 << endl << " and the next is: " << c3 << endl;} The first character is: G and the next is: e Program 2: // C++ code for std::basic_istream::peek()#include <bits/stdc++.h>using namespace std; // main methodint main(){ istringstream gfg("Computer"); char c1 = gfg.peek(); char c2 = gfg.get(); char c3 = gfg.get(); cout << "The first character is: " << c1 << endl << " and the next is: " << c3 << endl;} The first character is: C and the next is: o Program 3: // C++ code for std::basic_istream::peek()#include <bits/stdc++.h>using namespace std; // main methodint main(){ istringstream gfg("Laptop"); char c1 = gfg.peek(); char c2 = gfg.get(); char c3 = gfg.get(); char c4 = gfg.get(); cout << "The first character is: " << c1 << endl << " and the next is: " << c3 << endl << " after that next is: " << c4 << endl;} The first character is: L and the next is: a after that next is: p Reference: http://www.cplusplus.com/reference/istream/basic_istream/peek/ CPP-Functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 May, 2020" }, { "code": null, "e": 295, "s": 52, "text": "The std::basic_istream::peek() used to reads the next character from the input stream without extracting it. This function does not accept any parameter, simply returns the next character in the input string. Below is the syntax for the same:" }, { "code": null, "e": 308, "s": 295, "text": "Header File:" }, { "code": null, "e": 328, "s": 308, "text": "#include<iostream>\n" }, { "code": null, "e": 336, "s": 328, "text": "Syntax:" }, { "code": null, "e": 349, "s": 336, "text": "int peek();\n" }, { "code": null, "e": 439, "s": 349, "text": "Return Value: The std::basic_istream::peek() return a next character in the input string." }, { "code": null, "e": 542, "s": 439, "text": "Below are the programs to understand the implementation of std::basic_istream::peek() in a better way:" }, { "code": null, "e": 553, "s": 542, "text": "Program 1:" }, { "code": "// C++ code for std::basic_istream::peek()#include <bits/stdc++.h>using namespace std; // main methodint main(){ istringstream gfg(\"GeeksforGeeks\"); char c1 = gfg.peek(); char c2 = gfg.get(); char c3 = gfg.get(); cout << \"The first character is: \" << c1 << endl << \" and the next is: \" << c3 << endl;}", "e": 899, "s": 553, "text": null }, { "code": null, "e": 946, "s": 899, "text": "The first character is: G \nand the next is: e\n" }, { "code": null, "e": 957, "s": 946, "text": "Program 2:" }, { "code": "// C++ code for std::basic_istream::peek()#include <bits/stdc++.h>using namespace std; // main methodint main(){ istringstream gfg(\"Computer\"); char c1 = gfg.peek(); char c2 = gfg.get(); char c3 = gfg.get(); cout << \"The first character is: \" << c1 << endl << \" and the next is: \" << c3 << endl;}", "e": 1298, "s": 957, "text": null }, { "code": null, "e": 1345, "s": 1298, "text": "The first character is: C \nand the next is: o\n" }, { "code": null, "e": 1356, "s": 1345, "text": "Program 3:" }, { "code": "// C++ code for std::basic_istream::peek()#include <bits/stdc++.h>using namespace std; // main methodint main(){ istringstream gfg(\"Laptop\"); char c1 = gfg.peek(); char c2 = gfg.get(); char c3 = gfg.get(); char c4 = gfg.get(); cout << \"The first character is: \" << c1 << endl << \" and the next is: \" << c3 << endl << \" after that next is: \" << c4 << endl;}", "e": 1776, "s": 1356, "text": null }, { "code": null, "e": 1846, "s": 1776, "text": "The first character is: L \nand the next is: a \nafter that next is: p\n" }, { "code": null, "e": 1920, "s": 1846, "text": "Reference: http://www.cplusplus.com/reference/istream/basic_istream/peek/" }, { "code": null, "e": 1934, "s": 1920, "text": "CPP-Functions" }, { "code": null, "e": 1938, "s": 1934, "text": "C++" }, { "code": null, "e": 1942, "s": 1938, "text": "CPP" } ]
Implementation of AVL Tree using graphics in C++
24 Aug, 2021 AVL Trees are self-balancing Binary Search Trees where the difference between heights of left and right subtrees cannot be more than one for all nodes. Below is the example of the AVL Tree: In this article, we will be implementing the concept of AVL Tree using graphics in C++. As a prerequisite, one must set up graphics. h in their editor. Use this link to install graphics.h in CodeBlocks. Following are functionalities that will be illustrated in this article: Dynamic Insertion Displaying Tree structure (2D printing in the output window and graphical display) AVL Rotations Inorder, Preorder and Postorder traversals. The code accepts only integer values and hence includes functions to throw an error message when the user inputs invalid values. Examples: Input: 500, 400, 200, 150, 100, 700, 650, 600, 900, 450, 550, 50, 20, 800Output: 900 800 700 650 600 550 Root -> 500 450 400 200 150 100 50 20 Preorder: 500 200 100 50 20 150 400 450 650 600 550 800 700 900Inorder: 20 50 100 150 200 400 450 500 550 600 650 700 800 900Postorder: 20 100 50 200 450 400 150 550 600 700 900 800 650 500 Below is the implementation and execution of a self-balancing BST using AVL rotations in graphics: C++ // C++ program for the implementation// and execution of a self-balancing// BST using rotations and graphics #include <algorithm>#include <bits/stdc++.h>#include <cstdio>#include <graphics.h>#include <iostream>#include <sstream>#include <string>using namespace std; #define pow2(n) (1 << (n))const int x = 600;const int y = 100; // Node Declarationstruct avl_node { int data; int height; struct avl_node* left; struct avl_node* right; } * root, *temp1; // Class Declarationclass avlTree {public: int height(avl_node*); int diff(avl_node*); avl_node* rr_rotation(avl_node*); avl_node* ll_rotation(avl_node*); avl_node* lr_rotation(avl_node*); avl_node* rl_rotation(avl_node*); avl_node* balance(avl_node*); avl_node* balanceTree(avl_node*); avl_node* insert(avl_node*, int); void display(avl_node*, int); void drawNode(avl_node*, int, int, int); void drawTree(avl_node*, int, int); void inorder(avl_node*); void preorder(avl_node*); void postorder(avl_node*); int validate(string s); bool checkInput(string s); avlTree() { root = NULL; temp1 = NULL; }}; // Driver Codeint main(){ int choice, item, bf; int c; string str; avlTree avl; // Graphics int gd = DETECT; int gm; initwindow(1200, 700, "AVL Tree Graphics", 0, 0, false, true); cout << "\n---------------------" << endl; cout << "AVL Tree Implementation" << endl; cout << "\n---------------------" << endl; cout << "1.Insert Element into the tree" << endl; cout << "3.Balance Tree" << endl; cout << "4.PreOrder traversal" << endl; cout << "5.InOrder traversal" << endl; cout << "6.PostOrder traversal" << endl; cout << "7.Exit" << endl; while (1) { cout << "\nEnter your Choice: "; cin >> choice; switch (choice) { case 1: // Accept input as string cout << "Enter the value " << "to be inserted: "; cin >> str; // Function call to check // if input is valid or not c = avl.validate(str); if (c == 100) { item = std::stoi( str); root = avl.insert(root, item); cleardevice(); settextstyle(10, HORIZ_DIR, 3); if (root == NULL) { cout << "Tree is Empty" << endl; outtextxy(400, 10, "Tree is Empty"); } outtextxy(10, 50, "Before Rotation : "); avl.drawTree(root, x, y); } else cout << "\n\t\tInvalid Input!" << endl; break; case 2: // Tree structure in // the graphics window if (root == NULL) { cout << "Tree is Empty" << endl; } avl.display(root, 1); cleardevice(); avl.drawTree(root, x, y); break; case 3: // Balance Tree root = avl.balanceTree(root); cleardevice(); settextstyle( 10, HORIZ_DIR, 3); outtextxy(10, 50, "After Rotation : "); avl.drawTree(root, x, y); break; case 4: cout << "Preorder Traversal : "; avl.preorder(root); cout << endl; break; case 5: cout << "Inorder Traversal:" << endl; avl.inorder(root); cout << endl; break; case 6: cout << "Postorder Traversal:" << endl; avl.postorder(root); cout << endl; break; case 7: exit(1); break; default: cout << "Wrong Choice" << endl; } } getch(); closegraph(); return 0;} // Function to find the height// of the AVL Treeint avlTree::height(avl_node* temp){ int h = 0; if (temp != NULL) { int l_height = height(temp->left); int r_height = height(temp->right); int max_height = max(l_height, r_height); h = max_height + 1; } return h;} // Function to find the difference// between the left and the right// height of any node of the treeint avlTree::diff(avl_node* temp){ int l_height = height(temp->left); int r_height = height(temp->right); int b_factor = l_height - r_height; return b_factor;} // Function to perform the Right// Right Rotationavl_node* avlTree::rr_rotation( avl_node* parent){ avl_node* temp; temp = parent->right; parent->right = temp->left; temp->left = parent; return temp;} // Function to perform the Left// Left Rotationavl_node* avlTree::ll_rotation( avl_node* parent){ avl_node* temp; temp = parent->left; parent->left = temp->right; temp->right = parent; return temp;} // Function to perform the Left// Right Rotationavl_node* avlTree::lr_rotation( avl_node* parent){ avl_node* temp; temp = parent->left; parent->left = rr_rotation(temp); return ll_rotation(parent);} // Function to perform the Right// Left Rotationavl_node* avlTree::rl_rotation( avl_node* parent){ avl_node* temp; temp = parent->right; parent->right = ll_rotation(temp); return rr_rotation(parent);} // Function to balance the treeavl_node* avlTree::balance(avl_node* temp){ int bal_factor = diff(temp); if (bal_factor > 1) { if (diff(temp->left) > 0) { temp = ll_rotation(temp); } else { temp = lr_rotation(temp); } } else if (bal_factor < -1) { if (diff(temp->right) > 0) { temp = rl_rotation(temp); } else { temp = rr_rotation(temp); } } return temp;} // Function to display the AVL Treevoid avlTree::display(avl_node* ptr, int level){ int i; if (ptr != NULL) { display(ptr->right, level + 1); printf("\n"); if (ptr == root) cout << "Root -> "; for (i = 0; i < level && ptr != root; i++) { cout << " "; } int j; cout << ptr->data; display(ptr->left, level + 1); }} // Function to balance the treeavl_node* avlTree::balanceTree(avl_node* root){ int choice; if (root == NULL) { return NULL; } root->left = balanceTree(root->left); root->right = balanceTree(root->right); root = balance(root); return root;} // Function to create the node// int the AVL treevoid avlTree::drawNode(avl_node* root, int x, int y, int noderatio){ int bf = diff(root); if (bf > 1 || bf < -1) { setcolor(12); outtextxy(600, 10, "Imbalanced!"); circle(x, y, 25); setfillstyle(SOLID_FILL, 12); } else if (bf == 1 || bf == -1) { setcolor(14); circle(x, y, 25); setfillstyle(SOLID_FILL, 14); floodfill(x, y, YELLOW); } else { setcolor(15); circle(x, y, 25); setfillstyle(SOLID_FILL, 15); floodfill(x, y, WHITE); } char arr[5]; itoa(root->data, arr, 10); outtextxy(x, y, arr); if (root->left != NULL) { line(x, y, x - 20 * noderatio, y + 70); drawNode(root->left, x - 20 * noderatio, y + 70, noderatio - 2); } if (root->right != NULL) { line(x, y, x + 20 * noderatio, y + 70); drawNode(root->right, x + 20 * noderatio, y + 70, noderatio - 2); }} // Function to draw the AVL treevoid avlTree::drawTree(avl_node* root, int x, int y){ settextstyle(10, HORIZ_DIR, 3); outtextxy(10, 10, "Tree"); outtextxy(20, 600, "Balanced : "); circle(190, 605, 10); // Floodfill(190, 605, WHITE); outtextxy(520, 600, "L/R Heavy : "); setcolor(14); circle(700, 605, 10); // Floodfill(700, 605, YELLOW); setcolor(15); outtextxy(950, 600, "Critical : "); setcolor(12); circle(1115, 605, 10); // Floodfill(1115, 605, RED); settextstyle(10, HORIZ_DIR, 2); drawNode(root, x, y, 8);} // Function to insert element// in the treeavl_node* avlTree::insert( avl_node* root, int value){ if (root == NULL) { root = new avl_node; root->data = value; root->left = NULL; root->right = NULL; return root; } if (value < root->data) { root->left = insert( root->left, value); } else if (value > root->data) { root->right = insert( root->right, value); } else cout << "\n\tValue already" << " exists!" << endl; return root;} // Function to perform the Inorder// Traversal of AVL Treevoid avlTree::inorder(avl_node* root){ if (root == NULL) return; inorder(root->left); cout << root->data << " "; inorder(root->right);} // Function to perform the Preorder// Traversal of AVL Treevoid avlTree::preorder(avl_node* root){ if (root == NULL) return; cout << root->data << " "; preorder(root->left); preorder(root->right);} // Function to perform the Postorder// Traversal of AVL Treevoid avlTree::postorder(avl_node* root){ if (root == NULL) return; postorder(root->left); postorder(root->right); cout << root->data << " ";} // Function to check the input// validationbool avlTree::checkInput(string str){ for (int i = 0; i < str.length(); i++) if (isdigit(str[i]) == false) return false; return true;} // Function to validate AVL Treeint avlTree::validate(string str){ if (checkInput(str)) return 100; else return 10;} Output: Imbalanced Tree – Before Rotation Balanced Tree – After Rotation Final Tree reachharshitha AVL-Tree BST c-graphics computer-graphics Self-Balancing-BST Binary Search Tree C++ C++ Programs Tree Binary Search Tree Tree AVL-Tree CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. set vs unordered_set in C++ STL Flatten BST to sorted list | Increasing order Find median of BST in O(n) time and O(1) space Count BST nodes that lie in a given range Largest BST in a Binary Tree | Set 2 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++
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Aug, 2021" }, { "code": null, "e": 244, "s": 54, "text": "AVL Trees are self-balancing Binary Search Trees where the difference between heights of left and right subtrees cannot be more than one for all nodes. Below is the example of the AVL Tree:" }, { "code": null, "e": 448, "s": 244, "text": "In this article, we will be implementing the concept of AVL Tree using graphics in C++. As a prerequisite, one must set up graphics. h in their editor. Use this link to install graphics.h in CodeBlocks. " }, { "code": null, "e": 520, "s": 448, "text": "Following are functionalities that will be illustrated in this article:" }, { "code": null, "e": 538, "s": 520, "text": "Dynamic Insertion" }, { "code": null, "e": 621, "s": 538, "text": "Displaying Tree structure (2D printing in the output window and graphical display)" }, { "code": null, "e": 635, "s": 621, "text": "AVL Rotations" }, { "code": null, "e": 679, "s": 635, "text": "Inorder, Preorder and Postorder traversals." }, { "code": null, "e": 808, "s": 679, "text": "The code accepts only integer values and hence includes functions to throw an error message when the user inputs invalid values." }, { "code": null, "e": 818, "s": 808, "text": "Examples:" }, { "code": null, "e": 899, "s": 818, "text": "Input: 500, 400, 200, 150, 100, 700, 650, 600, 900, 450, 550, 50, 20, 800Output:" }, { "code": null, "e": 945, "s": 899, "text": " 900" }, { "code": null, "e": 1027, "s": 991, "text": " 800" }, { "code": null, "e": 1073, "s": 1027, "text": " 700" }, { "code": null, "e": 1099, "s": 1073, "text": " 650" }, { "code": null, "e": 1135, "s": 1099, "text": " 600" }, { "code": null, "e": 1181, "s": 1135, "text": " 550" }, { "code": null, "e": 1195, "s": 1181, "text": " Root -> 500" }, { "code": null, "e": 1241, "s": 1195, "text": " 450" }, { "code": null, "e": 1277, "s": 1241, "text": " 400" }, { "code": null, "e": 1323, "s": 1277, "text": " 200" }, { "code": null, "e": 1349, "s": 1323, "text": " 150" }, { "code": null, "e": 1395, "s": 1349, "text": " 100" }, { "code": null, "e": 1430, "s": 1395, "text": " 50" }, { "code": null, "e": 1475, "s": 1430, "text": " 20" }, { "code": null, "e": 1780, "s": 1551, "text": "Preorder: 500 200 100 50 20 150 400 450 650 600 550 800 700 900Inorder: 20 50 100 150 200 400 450 500 550 600 650 700 800 900Postorder: 20 100 50 200 450 400 150 550 600 700 900 800 650 500" }, { "code": null, "e": 1879, "s": 1780, "text": "Below is the implementation and execution of a self-balancing BST using AVL rotations in graphics:" }, { "code": null, "e": 1883, "s": 1879, "text": "C++" }, { "code": "// C++ program for the implementation// and execution of a self-balancing// BST using rotations and graphics #include <algorithm>#include <bits/stdc++.h>#include <cstdio>#include <graphics.h>#include <iostream>#include <sstream>#include <string>using namespace std; #define pow2(n) (1 << (n))const int x = 600;const int y = 100; // Node Declarationstruct avl_node { int data; int height; struct avl_node* left; struct avl_node* right; } * root, *temp1; // Class Declarationclass avlTree {public: int height(avl_node*); int diff(avl_node*); avl_node* rr_rotation(avl_node*); avl_node* ll_rotation(avl_node*); avl_node* lr_rotation(avl_node*); avl_node* rl_rotation(avl_node*); avl_node* balance(avl_node*); avl_node* balanceTree(avl_node*); avl_node* insert(avl_node*, int); void display(avl_node*, int); void drawNode(avl_node*, int, int, int); void drawTree(avl_node*, int, int); void inorder(avl_node*); void preorder(avl_node*); void postorder(avl_node*); int validate(string s); bool checkInput(string s); avlTree() { root = NULL; temp1 = NULL; }}; // Driver Codeint main(){ int choice, item, bf; int c; string str; avlTree avl; // Graphics int gd = DETECT; int gm; initwindow(1200, 700, \"AVL Tree Graphics\", 0, 0, false, true); cout << \"\\n---------------------\" << endl; cout << \"AVL Tree Implementation\" << endl; cout << \"\\n---------------------\" << endl; cout << \"1.Insert Element into the tree\" << endl; cout << \"3.Balance Tree\" << endl; cout << \"4.PreOrder traversal\" << endl; cout << \"5.InOrder traversal\" << endl; cout << \"6.PostOrder traversal\" << endl; cout << \"7.Exit\" << endl; while (1) { cout << \"\\nEnter your Choice: \"; cin >> choice; switch (choice) { case 1: // Accept input as string cout << \"Enter the value \" << \"to be inserted: \"; cin >> str; // Function call to check // if input is valid or not c = avl.validate(str); if (c == 100) { item = std::stoi( str); root = avl.insert(root, item); cleardevice(); settextstyle(10, HORIZ_DIR, 3); if (root == NULL) { cout << \"Tree is Empty\" << endl; outtextxy(400, 10, \"Tree is Empty\"); } outtextxy(10, 50, \"Before Rotation : \"); avl.drawTree(root, x, y); } else cout << \"\\n\\t\\tInvalid Input!\" << endl; break; case 2: // Tree structure in // the graphics window if (root == NULL) { cout << \"Tree is Empty\" << endl; } avl.display(root, 1); cleardevice(); avl.drawTree(root, x, y); break; case 3: // Balance Tree root = avl.balanceTree(root); cleardevice(); settextstyle( 10, HORIZ_DIR, 3); outtextxy(10, 50, \"After Rotation : \"); avl.drawTree(root, x, y); break; case 4: cout << \"Preorder Traversal : \"; avl.preorder(root); cout << endl; break; case 5: cout << \"Inorder Traversal:\" << endl; avl.inorder(root); cout << endl; break; case 6: cout << \"Postorder Traversal:\" << endl; avl.postorder(root); cout << endl; break; case 7: exit(1); break; default: cout << \"Wrong Choice\" << endl; } } getch(); closegraph(); return 0;} // Function to find the height// of the AVL Treeint avlTree::height(avl_node* temp){ int h = 0; if (temp != NULL) { int l_height = height(temp->left); int r_height = height(temp->right); int max_height = max(l_height, r_height); h = max_height + 1; } return h;} // Function to find the difference// between the left and the right// height of any node of the treeint avlTree::diff(avl_node* temp){ int l_height = height(temp->left); int r_height = height(temp->right); int b_factor = l_height - r_height; return b_factor;} // Function to perform the Right// Right Rotationavl_node* avlTree::rr_rotation( avl_node* parent){ avl_node* temp; temp = parent->right; parent->right = temp->left; temp->left = parent; return temp;} // Function to perform the Left// Left Rotationavl_node* avlTree::ll_rotation( avl_node* parent){ avl_node* temp; temp = parent->left; parent->left = temp->right; temp->right = parent; return temp;} // Function to perform the Left// Right Rotationavl_node* avlTree::lr_rotation( avl_node* parent){ avl_node* temp; temp = parent->left; parent->left = rr_rotation(temp); return ll_rotation(parent);} // Function to perform the Right// Left Rotationavl_node* avlTree::rl_rotation( avl_node* parent){ avl_node* temp; temp = parent->right; parent->right = ll_rotation(temp); return rr_rotation(parent);} // Function to balance the treeavl_node* avlTree::balance(avl_node* temp){ int bal_factor = diff(temp); if (bal_factor > 1) { if (diff(temp->left) > 0) { temp = ll_rotation(temp); } else { temp = lr_rotation(temp); } } else if (bal_factor < -1) { if (diff(temp->right) > 0) { temp = rl_rotation(temp); } else { temp = rr_rotation(temp); } } return temp;} // Function to display the AVL Treevoid avlTree::display(avl_node* ptr, int level){ int i; if (ptr != NULL) { display(ptr->right, level + 1); printf(\"\\n\"); if (ptr == root) cout << \"Root -> \"; for (i = 0; i < level && ptr != root; i++) { cout << \" \"; } int j; cout << ptr->data; display(ptr->left, level + 1); }} // Function to balance the treeavl_node* avlTree::balanceTree(avl_node* root){ int choice; if (root == NULL) { return NULL; } root->left = balanceTree(root->left); root->right = balanceTree(root->right); root = balance(root); return root;} // Function to create the node// int the AVL treevoid avlTree::drawNode(avl_node* root, int x, int y, int noderatio){ int bf = diff(root); if (bf > 1 || bf < -1) { setcolor(12); outtextxy(600, 10, \"Imbalanced!\"); circle(x, y, 25); setfillstyle(SOLID_FILL, 12); } else if (bf == 1 || bf == -1) { setcolor(14); circle(x, y, 25); setfillstyle(SOLID_FILL, 14); floodfill(x, y, YELLOW); } else { setcolor(15); circle(x, y, 25); setfillstyle(SOLID_FILL, 15); floodfill(x, y, WHITE); } char arr[5]; itoa(root->data, arr, 10); outtextxy(x, y, arr); if (root->left != NULL) { line(x, y, x - 20 * noderatio, y + 70); drawNode(root->left, x - 20 * noderatio, y + 70, noderatio - 2); } if (root->right != NULL) { line(x, y, x + 20 * noderatio, y + 70); drawNode(root->right, x + 20 * noderatio, y + 70, noderatio - 2); }} // Function to draw the AVL treevoid avlTree::drawTree(avl_node* root, int x, int y){ settextstyle(10, HORIZ_DIR, 3); outtextxy(10, 10, \"Tree\"); outtextxy(20, 600, \"Balanced : \"); circle(190, 605, 10); // Floodfill(190, 605, WHITE); outtextxy(520, 600, \"L/R Heavy : \"); setcolor(14); circle(700, 605, 10); // Floodfill(700, 605, YELLOW); setcolor(15); outtextxy(950, 600, \"Critical : \"); setcolor(12); circle(1115, 605, 10); // Floodfill(1115, 605, RED); settextstyle(10, HORIZ_DIR, 2); drawNode(root, x, y, 8);} // Function to insert element// in the treeavl_node* avlTree::insert( avl_node* root, int value){ if (root == NULL) { root = new avl_node; root->data = value; root->left = NULL; root->right = NULL; return root; } if (value < root->data) { root->left = insert( root->left, value); } else if (value > root->data) { root->right = insert( root->right, value); } else cout << \"\\n\\tValue already\" << \" exists!\" << endl; return root;} // Function to perform the Inorder// Traversal of AVL Treevoid avlTree::inorder(avl_node* root){ if (root == NULL) return; inorder(root->left); cout << root->data << \" \"; inorder(root->right);} // Function to perform the Preorder// Traversal of AVL Treevoid avlTree::preorder(avl_node* root){ if (root == NULL) return; cout << root->data << \" \"; preorder(root->left); preorder(root->right);} // Function to perform the Postorder// Traversal of AVL Treevoid avlTree::postorder(avl_node* root){ if (root == NULL) return; postorder(root->left); postorder(root->right); cout << root->data << \" \";} // Function to check the input// validationbool avlTree::checkInput(string str){ for (int i = 0; i < str.length(); i++) if (isdigit(str[i]) == false) return false; return true;} // Function to validate AVL Treeint avlTree::validate(string str){ if (checkInput(str)) return 100; else return 10;}", "e": 11725, "s": 1883, "text": null }, { "code": null, "e": 11736, "s": 11728, "text": "Output:" }, { "code": null, "e": 11772, "s": 11738, "text": "Imbalanced Tree – Before Rotation" }, { "code": null, "e": 11805, "s": 11774, "text": "Balanced Tree – After Rotation" }, { "code": null, "e": 11818, "s": 11807, "text": "Final Tree" }, { "code": null, "e": 11835, "s": 11820, "text": "reachharshitha" }, { "code": null, "e": 11844, "s": 11835, "text": "AVL-Tree" }, { "code": null, "e": 11848, "s": 11844, "text": "BST" }, { "code": null, "e": 11859, "s": 11848, "text": "c-graphics" }, { "code": null, "e": 11877, "s": 11859, "text": "computer-graphics" }, { "code": null, "e": 11896, "s": 11877, "text": "Self-Balancing-BST" }, { "code": null, "e": 11915, "s": 11896, "text": "Binary Search Tree" }, { "code": null, "e": 11919, "s": 11915, "text": "C++" }, { "code": null, "e": 11932, "s": 11919, "text": "C++ Programs" }, { "code": null, "e": 11937, "s": 11932, "text": "Tree" }, { "code": null, "e": 11956, "s": 11937, "text": "Binary Search Tree" }, { "code": null, "e": 11961, "s": 11956, "text": "Tree" }, { "code": null, "e": 11970, "s": 11961, "text": "AVL-Tree" }, { "code": null, "e": 11974, "s": 11970, "text": "CPP" }, { "code": null, "e": 12072, "s": 11974, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12104, "s": 12072, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 12150, "s": 12104, "text": "Flatten BST to sorted list | Increasing order" }, { "code": null, "e": 12197, "s": 12150, "text": "Find median of BST in O(n) time and O(1) space" }, { "code": null, "e": 12239, "s": 12197, "text": "Count BST nodes that lie in a given range" }, { "code": null, "e": 12276, "s": 12239, "text": "Largest BST in a Binary Tree | Set 2" }, { "code": null, "e": 12294, "s": 12276, "text": "Vector in C++ STL" }, { "code": null, "e": 12337, "s": 12294, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 12383, "s": 12337, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 12406, "s": 12383, "text": "std::sort() in C++ STL" } ]
Unconstrained Multivariate Optimization
17 Jul, 2020 Wikipedia defines optimization as a problem where you maximize or minimize a real function by systematically choosing input values from an allowed set and computing the value of the function. That means when we talk about optimization we are always interested in finding the best solution. So, let say that one has some functional form(e.g in the form of f(x)) and he is trying to find the best solution for this functional form. Now, what does best mean? One could either say he is interested in minimizing this functional form or maximizing this functional form.Generally, an optimization problem has three components. minimize f(x),w.r.t x , subject to a < x < b where, f(x) : Objective function x : Decision variable a < x < b : Constraint What’s a multivariate optimization problem? In a multivariate optimization problem, there are multiple variables that act as decision variables in the optimization problem. So, when you look at these types of problems a general function z could be some non-linear function of decision variables x1,x2,x3 to xn. So, there are n variables that one could manipulate or choose to optimize this function z. Notice that one could explain univariate optimization using pictures in two dimensions that is because in the x-direction we had the decision variable value and in the y-direction, we had the value of the function. However, if it is multivariate optimization then we have to use pictures in three dimensions and if the decision variables are more than 2 then it is difficult to visualize. What’s unconstrained multivariate optimization? As the name suggests multivariate optimization with no constraints is known as unconstrained multivariate optimization.Example: So, when you look at this optimization problem you typically write it in this above form where you say you are going to minimize f(x̄), and this function is called the objective function. And the variable that you can use to minimize this function which is called the decision variable is written below like this w.r.t x̄ here and you also say x̄ is continuous that is it could take any value in the real number line. In case of multivariate optimization the necessary and sufficient conditions for x̄* to be the minimizer of the function f(x̄) are: First-order necessary condition: ∇ f(x̄*) = 0 Second-order sufficiency condition: ∇ 2 f(x̄*) has to be positive definite. where, Let us quickly solve a numerical example on this to understand these conditions better. Problem: min Solution: According to the first-order condition By solving the two equation we got value of and as To check whether this is a maximum point or a minimum point, and to do so we look at the second-order sufficiency condition. So according to the second-order sufficiency condition: And we know that the Hessian matrix is said to be positive definite at a point if all the eigenvalues of the Hessian matrix are positive. So now let's find the eigenvalues of the above Hessian matrix. To find eigenvalue refer here. And to find eigenvalue in python refer here. So the eigenvalue of the above hessian matrix is So the eigenvalues for this found to be both positive; that means, that this is a minimum point. data-science Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jul, 2020" }, { "code": null, "e": 649, "s": 28, "text": "Wikipedia defines optimization as a problem where you maximize or minimize a real function by systematically choosing input values from an allowed set and computing the value of the function. That means when we talk about optimization we are always interested in finding the best solution. So, let say that one has some functional form(e.g in the form of f(x)) and he is trying to find the best solution for this functional form. Now, what does best mean? One could either say he is interested in minimizing this functional form or maximizing this functional form.Generally, an optimization problem has three components." }, { "code": null, "e": 695, "s": 649, "text": "minimize f(x),w.r.t x , subject to a < x < b " }, { "code": null, "e": 775, "s": 695, "text": "where, f(x) : Objective function x : Decision variable a < x < b : Constraint " }, { "code": null, "e": 819, "s": 775, "text": "What’s a multivariate optimization problem?" }, { "code": null, "e": 948, "s": 819, "text": "In a multivariate optimization problem, there are multiple variables that act as decision variables in the optimization problem." }, { "code": null, "e": 1566, "s": 948, "text": "So, when you look at these types of problems a general function z could be some non-linear function of decision variables x1,x2,x3 to xn. So, there are n variables that one could manipulate or choose to optimize this function z. Notice that one could explain univariate optimization using pictures in two dimensions that is because in the x-direction we had the decision variable value and in the y-direction, we had the value of the function. However, if it is multivariate optimization then we have to use pictures in three dimensions and if the decision variables are more than 2 then it is difficult to visualize." }, { "code": null, "e": 1614, "s": 1566, "text": "What’s unconstrained multivariate optimization?" }, { "code": null, "e": 1742, "s": 1614, "text": "As the name suggests multivariate optimization with no constraints is known as unconstrained multivariate optimization.Example:" }, { "code": null, "e": 2160, "s": 1742, "text": "So, when you look at this optimization problem you typically write it in this above form where you say you are going to minimize f(x̄), and this function is called the objective function. And the variable that you can use to minimize this function which is called the decision variable is written below like this w.r.t x̄ here and you also say x̄ is continuous that is it could take any value in the real number line." }, { "code": null, "e": 2292, "s": 2160, "text": "In case of multivariate optimization the necessary and sufficient conditions for x̄* to be the minimizer of the function f(x̄) are:" }, { "code": null, "e": 2338, "s": 2292, "text": "First-order necessary condition: ∇ f(x̄*) = 0" }, { "code": null, "e": 2414, "s": 2338, "text": "Second-order sufficiency condition: ∇ 2 f(x̄*) has to be positive definite." }, { "code": null, "e": 2421, "s": 2414, "text": "where," }, { "code": null, "e": 2509, "s": 2421, "text": "Let us quickly solve a numerical example on this to understand these conditions better." }, { "code": null, "e": 3248, "s": 2509, "text": "Problem:\nmin \n\nSolution:\nAccording to the first-order condition\n\n\n\nBy solving the two equation we got value of and as\n\n\n\nTo check whether this is a maximum point or a minimum point, and\nto do so we look at the second-order sufficiency condition. \nSo according to the second-order sufficiency condition:\n\n\n\nAnd we know that the Hessian matrix is said to be positive definite at a point \nif all the eigenvalues of the Hessian matrix are positive. So now let's find the\neigenvalues of the above Hessian matrix. To find eigenvalue refer here. \nAnd to find eigenvalue in python refer here.\n\nSo the eigenvalue of the above hessian matrix is\n\n\n\nSo the eigenvalues for this found to be both positive; \nthat means, that this is a minimum point.\n" }, { "code": null, "e": 3261, "s": 3248, "text": "data-science" }, { "code": null, "e": 3278, "s": 3261, "text": "Machine Learning" }, { "code": null, "e": 3295, "s": 3278, "text": "Machine Learning" } ]
Least Slack Time (LST) scheduling Algorithm in real-time systems
16 Jan, 2020 Least Slack Time (LST) is a dynamic priority-driven scheduling algorithm used in real-time systems. In LST, all the tasks in the system are assigned some priority according to their slack time. The task which has the least slack time has the highest priority and vice versa. Priorities to the tasks are assigned dynamically. Slack time can be calculated using the equation: slack_time = ( D - t - e' ) Here D : Deadline of the task t : Real time when the cycle starts. e’ : Remaining Execution Time of the task. The task which has the minimal slack time is dispatched to the CPU for its execution as it has the highest priority. Hyper Period (HP) is the time period of the Gantt chart which is equal to the LCM of the periods of all the tasks in the system. At time t, the slack of a task is equivalent to ( d-t ) minus the time required to complete the remaining portion of the task. It is a complex algorithm, and that is why it requires extra information like execution times and deadlines. Least Slack Time scheduling algorithm works optimally only when preemption is allowed. It can produce a feasible schedule if and only if a feasible schedule exists for the set of tasks that are runnable. It is different from the Earliest Deadline First because it requires execution times of the task which are to be scheduled. Hence it is sometimes impractical to implement the Least Slack Time scheduling algorithm because the burst time of the tasks in real-time systems is difficult to predict. Unlike EDF (Earliest Deadline First) scheduling algorithm, LST may under-utilize the CPU, thus decreasing the efficiency and throughput. If two or more tasks which are ready for execution in LST, and the tasks have the same slack time or laxity value, then they are dispatched to the processor according to the FCFS (First Come First Serve) basis. At time t=0: Only task T1, has arrived. T1 is executed till time t=4. At time t=4: T2 has arrived.Slack time of T1: 33-4-6=23Slack time of T2: 28-4-3=21Hence T2 starts to execute till time t=5 when T3 arrives. At time t=5:Slack Time of T1: 33-5-6=22Slack Time of T2: 28-5-2=21Slack Time of T3: 29-5-10=12Hence T3 starts to execute till time t=13 At time t=13:Slack Time of T1: 33-13-6=14Slack Time of T2: 28-13-2=13Slack Time of T3: 29-13-2=14Hence T2 starts to execute till time t=15 At time t=15:Slack Time of T1: 33-15-6=12Slack Time of T3: 29-15-2=12Hence T3 starts to execute till time t=16 At time t=16:Slack Time of T1: 33-16-6=11Slack Time of T3:29-16-=12Hence T1 starts to execute till time t=18 and so on.. Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Disk Scheduling Algorithms Introduction of Deadlock in Operating System Inter Process Communication (IPC) Paging in Operating System File Allocation Methods Introduction of Operating System - Set 1 CPU Scheduling in Operating Systems Semaphores in Process Synchronization Difference between Process and Thread
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Jan, 2020" }, { "code": null, "e": 153, "s": 53, "text": "Least Slack Time (LST) is a dynamic priority-driven scheduling algorithm used in real-time systems." }, { "code": null, "e": 328, "s": 153, "text": "In LST, all the tasks in the system are assigned some priority according to their slack time. The task which has the least slack time has the highest priority and vice versa." }, { "code": null, "e": 378, "s": 328, "text": "Priorities to the tasks are assigned dynamically." }, { "code": null, "e": 427, "s": 378, "text": "Slack time can be calculated using the equation:" }, { "code": null, "e": 455, "s": 427, "text": "slack_time = ( D - t - e' )" }, { "code": null, "e": 579, "s": 455, "text": "Here D : Deadline of the task t : Real time when the cycle starts. e’ : Remaining Execution Time of the task." }, { "code": null, "e": 696, "s": 579, "text": "The task which has the minimal slack time is dispatched to the CPU for its execution as it has the highest priority." }, { "code": null, "e": 825, "s": 696, "text": "Hyper Period (HP) is the time period of the Gantt chart which is equal to the LCM of the periods of all the tasks in the system." }, { "code": null, "e": 952, "s": 825, "text": "At time t, the slack of a task is equivalent to ( d-t ) minus the time required to complete the remaining portion of the task." }, { "code": null, "e": 1265, "s": 952, "text": "It is a complex algorithm, and that is why it requires extra information like execution times and deadlines. Least Slack Time scheduling algorithm works optimally only when preemption is allowed. It can produce a feasible schedule if and only if a feasible schedule exists for the set of tasks that are runnable." }, { "code": null, "e": 1560, "s": 1265, "text": "It is different from the Earliest Deadline First because it requires execution times of the task which are to be scheduled. Hence it is sometimes impractical to implement the Least Slack Time scheduling algorithm because the burst time of the tasks in real-time systems is difficult to predict." }, { "code": null, "e": 1697, "s": 1560, "text": "Unlike EDF (Earliest Deadline First) scheduling algorithm, LST may under-utilize the CPU, thus decreasing the efficiency and throughput." }, { "code": null, "e": 1908, "s": 1697, "text": "If two or more tasks which are ready for execution in LST, and the tasks have the same slack time or laxity value, then they are dispatched to the processor according to the FCFS (First Come First Serve) basis." }, { "code": null, "e": 1978, "s": 1908, "text": "At time t=0: Only task T1, has arrived. T1 is executed till time t=4." }, { "code": null, "e": 2118, "s": 1978, "text": "At time t=4: T2 has arrived.Slack time of T1: 33-4-6=23Slack time of T2: 28-4-3=21Hence T2 starts to execute till time t=5 when T3 arrives." }, { "code": null, "e": 2254, "s": 2118, "text": "At time t=5:Slack Time of T1: 33-5-6=22Slack Time of T2: 28-5-2=21Slack Time of T3: 29-5-10=12Hence T3 starts to execute till time t=13" }, { "code": null, "e": 2393, "s": 2254, "text": "At time t=13:Slack Time of T1: 33-13-6=14Slack Time of T2: 28-13-2=13Slack Time of T3: 29-13-2=14Hence T2 starts to execute till time t=15" }, { "code": null, "e": 2504, "s": 2393, "text": "At time t=15:Slack Time of T1: 33-15-6=12Slack Time of T3: 29-15-2=12Hence T3 starts to execute till time t=16" }, { "code": null, "e": 2625, "s": 2504, "text": "At time t=16:Slack Time of T1: 33-16-6=11Slack Time of T3:29-16-=12Hence T1 starts to execute till time t=18 and so on.." }, { "code": null, "e": 2643, "s": 2625, "text": "Operating Systems" }, { "code": null, "e": 2661, "s": 2643, "text": "Operating Systems" }, { "code": null, "e": 2759, "s": 2661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2808, "s": 2759, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 2835, "s": 2808, "text": "Disk Scheduling Algorithms" }, { "code": null, "e": 2880, "s": 2835, "text": "Introduction of Deadlock in Operating System" }, { "code": null, "e": 2914, "s": 2880, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 2941, "s": 2914, "text": "Paging in Operating System" }, { "code": null, "e": 2965, "s": 2941, "text": "File Allocation Methods" }, { "code": null, "e": 3006, "s": 2965, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 3042, "s": 3006, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 3080, "s": 3042, "text": "Semaphores in Process Synchronization" } ]
Python dictionary, set and counter to check if frequencies can become same
24 Apr, 2020 Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make the frequency of each character same. Input : str = “xyyzz” Output : Yes We can remove character ‘x’ from above string to make the frequency of each character same. Input : str = “xxxxyyzz” Output : No It is not possible to make frequency of each character same just by removing at most one character from above string. This problem has existing solution please refer Check if frequency of all characters can become same by one removal link. We will solve this problem quickly in Python. Approach is very simple, We need to count frequency of each letter in string, for this we will use Counter(input) method, it returns a dictionary having characters as keys and their respective frequencies as values.Now extract list of frequencies of each character and push these values in Set() data structure in python.Since set contains unique values, so if size of set is 1 that means frequencies of all characters were same, if size of set is 2 then check if value of first element is 1 or not ( if 1 then we can make same frequency by removing one character at most otherwise not possible ).# Function to Check if frequency of all characters# can become same by one removalfrom collections import Counter def allSame(input): # calculate frequency of each character # and convert string into dictionary dict=Counter(input) # now get list of all values and push it # in set same = list(set(dict.values())) if len(same)>2: print('No') elif len (same)==2 and same[1]-same[0]>1: print('No') else: print('Yes') # now check if frequency of all characters # can become same # Driver programif __name__ == "__main__": input = 'xxxyyzzt' allSame(input)Output:No My Personal Notes arrow_drop_upSave We need to count frequency of each letter in string, for this we will use Counter(input) method, it returns a dictionary having characters as keys and their respective frequencies as values. Now extract list of frequencies of each character and push these values in Set() data structure in python. Since set contains unique values, so if size of set is 1 that means frequencies of all characters were same, if size of set is 2 then check if value of first element is 1 or not ( if 1 then we can make same frequency by removing one character at most otherwise not possible ). # Function to Check if frequency of all characters# can become same by one removalfrom collections import Counter def allSame(input): # calculate frequency of each character # and convert string into dictionary dict=Counter(input) # now get list of all values and push it # in set same = list(set(dict.values())) if len(same)>2: print('No') elif len (same)==2 and same[1]-same[0]>1: print('No') else: print('Yes') # now check if frequency of all characters # can become same # Driver programif __name__ == "__main__": input = 'xxxyyzzt' allSame(input) Output: No gopalgupta7799 frequency-counting Python dictionary-programs python-dict python-set Python python-dict python-set 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Apr, 2020" }, { "code": null, "e": 228, "s": 28, "text": "Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string." }, { "code": null, "e": 238, "s": 228, "text": "Examples:" }, { "code": null, "e": 659, "s": 238, "text": "Input : str = “xyyz”\nOutput : Yes\nWe can remove character ’y’ from above \nstring to make the frequency of each \ncharacter same. \n\nInput : str = “xyyzz” \nOutput : Yes\nWe can remove character ‘x’ from above \nstring to make the frequency of each \ncharacter same.\n\nInput : str = “xxxxyyzz” \nOutput : No\nIt is not possible to make frequency of \neach character same just by removing at \nmost one character from above string.\n" }, { "code": null, "e": 852, "s": 659, "text": "This problem has existing solution please refer Check if frequency of all characters can become same by one removal link. We will solve this problem quickly in Python. Approach is very simple," }, { "code": null, "e": 2106, "s": 852, "text": "We need to count frequency of each letter in string, for this we will use Counter(input) method, it returns a dictionary having characters as keys and their respective frequencies as values.Now extract list of frequencies of each character and push these values in Set() data structure in python.Since set contains unique values, so if size of set is 1 that means frequencies of all characters were same, if size of set is 2 then check if value of first element is 1 or not ( if 1 then we can make same frequency by removing one character at most otherwise not possible ).# Function to Check if frequency of all characters# can become same by one removalfrom collections import Counter def allSame(input): # calculate frequency of each character # and convert string into dictionary dict=Counter(input) # now get list of all values and push it # in set same = list(set(dict.values())) if len(same)>2: print('No') elif len (same)==2 and same[1]-same[0]>1: print('No') else: print('Yes') # now check if frequency of all characters # can become same # Driver programif __name__ == \"__main__\": input = 'xxxyyzzt' allSame(input)Output:No\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 2297, "s": 2106, "text": "We need to count frequency of each letter in string, for this we will use Counter(input) method, it returns a dictionary having characters as keys and their respective frequencies as values." }, { "code": null, "e": 2404, "s": 2297, "text": "Now extract list of frequencies of each character and push these values in Set() data structure in python." }, { "code": null, "e": 2681, "s": 2404, "text": "Since set contains unique values, so if size of set is 1 that means frequencies of all characters were same, if size of set is 2 then check if value of first element is 1 or not ( if 1 then we can make same frequency by removing one character at most otherwise not possible )." }, { "code": "# Function to Check if frequency of all characters# can become same by one removalfrom collections import Counter def allSame(input): # calculate frequency of each character # and convert string into dictionary dict=Counter(input) # now get list of all values and push it # in set same = list(set(dict.values())) if len(same)>2: print('No') elif len (same)==2 and same[1]-same[0]>1: print('No') else: print('Yes') # now check if frequency of all characters # can become same # Driver programif __name__ == \"__main__\": input = 'xxxyyzzt' allSame(input)", "e": 3318, "s": 2681, "text": null }, { "code": null, "e": 3326, "s": 3318, "text": "Output:" }, { "code": null, "e": 3330, "s": 3326, "text": "No\n" }, { "code": null, "e": 3345, "s": 3330, "text": "gopalgupta7799" }, { "code": null, "e": 3364, "s": 3345, "text": "frequency-counting" }, { "code": null, "e": 3391, "s": 3364, "text": "Python dictionary-programs" }, { "code": null, "e": 3403, "s": 3391, "text": "python-dict" }, { "code": null, "e": 3414, "s": 3403, "text": "python-set" }, { "code": null, "e": 3421, "s": 3414, "text": "Python" }, { "code": null, "e": 3433, "s": 3421, "text": "python-dict" }, { "code": null, "e": 3444, "s": 3433, "text": "python-set" }, { "code": null, "e": 3542, "s": 3444, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3560, "s": 3542, "text": "Python Dictionary" }, { "code": null, "e": 3602, "s": 3560, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3624, "s": 3602, "text": "Enumerate() in Python" }, { "code": null, "e": 3650, "s": 3624, "text": "Python String | replace()" }, { "code": null, "e": 3682, "s": 3650, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3711, "s": 3682, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3738, "s": 3711, "text": "Python Classes and Objects" }, { "code": null, "e": 3768, "s": 3738, "text": "Iterate over a list in Python" }, { "code": null, "e": 3789, "s": 3768, "text": "Python OOPs Concepts" } ]
Tryit Editor v3.7
Tryit: Create input fields with black border color on focus
[]
Optimal Division in C++
Suppose we have a list of positive integers; the adjacent integers will perform the float division. So for example, [2,3,4] -> 2 / 3 / 4. Now, we can add any number of parenthesis at any position to change the priority of these operations. We should find out how to add parenthesis to get the maximum result, we have to find the corresponding expression in string format. Our expression should NOT contain redundant parenthesis. So if the input is like [1000,100,10,2], then the result will be “1000/(100/10/2)”. To solve this, we will follow these steps − n := size of nums array if n is 0 then return a blank string. num := nums[0] as string if n is 1, then return num if n is 2, then return num concatenate /, concatenate nums[1] as string den := an empty string for i in range 1 to n – 1den := den + nums[i] as stringif i is not n – 1, then den := den concatenate ‘/’ den := den + nums[i] as string if i is not n – 1, then den := den concatenate ‘/’ return num concatenate / concatenate ( concatenate den , concatenate ) Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: string optimalDivision(vector<int>& nums) { int n = nums.size(); if(n == 0) return ""; string num = to_string(nums[0]); if(n == 1) return num; if(n == 2) return num + "/" + to_string(nums[1]); string den = ""; for(int i = 1; i < n; i++){ den += to_string(nums[i]); if(i != n - 1) den += "/"; } return num + "/" + "(" + den + ")"; } }; main(){ vector<int> v = {1000,100,10,2}; Solution ob; cout << (ob.optimalDivision(v)); } [1000,100,10,2] 1000/(100/10/2)
[ { "code": null, "e": 1575, "s": 1062, "text": "Suppose we have a list of positive integers; the adjacent integers will perform the float division. So for example, [2,3,4] -> 2 / 3 / 4. Now, we can add any number of parenthesis at any position to change the priority of these operations. We should find out how to add parenthesis to get the maximum result, we have to find the corresponding expression in string format. Our expression should NOT contain redundant parenthesis. So if the input is like [1000,100,10,2], then the result will be “1000/(100/10/2)”." }, { "code": null, "e": 1619, "s": 1575, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1643, "s": 1619, "text": "n := size of nums array" }, { "code": null, "e": 1681, "s": 1643, "text": "if n is 0 then return a blank string." }, { "code": null, "e": 1706, "s": 1681, "text": "num := nums[0] as string" }, { "code": null, "e": 1733, "s": 1706, "text": "if n is 1, then return num" }, { "code": null, "e": 1805, "s": 1733, "text": "if n is 2, then return num concatenate /, concatenate nums[1] as string" }, { "code": null, "e": 1828, "s": 1805, "text": "den := an empty string" }, { "code": null, "e": 1934, "s": 1828, "text": "for i in range 1 to n – 1den := den + nums[i] as stringif i is not n – 1, then den := den concatenate ‘/’" }, { "code": null, "e": 1965, "s": 1934, "text": "den := den + nums[i] as string" }, { "code": null, "e": 2016, "s": 1965, "text": "if i is not n – 1, then den := den concatenate ‘/’" }, { "code": null, "e": 2087, "s": 2016, "text": "return num concatenate / concatenate ( concatenate den , concatenate )" }, { "code": null, "e": 2157, "s": 2087, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2168, "s": 2157, "text": " Live Demo" }, { "code": null, "e": 2753, "s": 2168, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n string optimalDivision(vector<int>& nums) {\n int n = nums.size();\n if(n == 0) return \"\";\n string num = to_string(nums[0]);\n if(n == 1) return num;\n if(n == 2) return num + \"/\" + to_string(nums[1]);\n string den = \"\";\n for(int i = 1; i < n; i++){\n den += to_string(nums[i]);\n if(i != n - 1) den += \"/\";\n }\n return num + \"/\" + \"(\" + den + \")\";\n }\n};\nmain(){\n vector<int> v = {1000,100,10,2};\n Solution ob;\n cout << (ob.optimalDivision(v));\n}" }, { "code": null, "e": 2769, "s": 2753, "text": "[1000,100,10,2]" }, { "code": null, "e": 2785, "s": 2769, "text": "1000/(100/10/2)" } ]
How to align the bar and line in Matplotlib two Y-axes chart?
To align the bar and line in matplotlib two Y-axes chart, we can use twinx() method to create a twin of Axes with a shared X-axis but independent Y-axis. 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. Make a Pandas dataframe with columns 1 and 2. Make a Pandas dataframe with columns 1 and 2. Plot the dataframe using plot() method with kind="bar", i.e., class by name. Plot the dataframe using plot() method with kind="bar", i.e., class by name. Use twinx() method to create a twin of Axes with a shared X-axis but independent Y-axis. Use twinx() method to create a twin of Axes with a shared X-axis but independent Y-axis. Plot the axis (Step 3) ticks and dataframe columns values to plot the lines. Plot the axis (Step 3) ticks and dataframe columns values to plot the lines. To display the figure, use show() method. To display the figure, use show() method. from matplotlib import pyplot as plt import pandas as pd plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame({"col1": [1, 3, 5, 7, 1], "col2": [1, 5, 7, 9, 1]}) ax = df.plot(kind="bar") ax2 = ax.twinx() ax2.plot(ax.get_xticks(), df[['col1', 'col2']].values, linestyle='-', marker='o', linewidth=2.0) plt.show()
[ { "code": null, "e": 1216, "s": 1062, "text": "To align the bar and line in matplotlib two Y-axes chart, we can use twinx() method to create a twin of Axes with a shared X-axis but independent Y-axis." }, { "code": null, "e": 1292, "s": 1216, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1368, "s": 1292, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1414, "s": 1368, "text": "Make a Pandas dataframe with columns 1 and 2." }, { "code": null, "e": 1460, "s": 1414, "text": "Make a Pandas dataframe with columns 1 and 2." }, { "code": null, "e": 1537, "s": 1460, "text": "Plot the dataframe using plot() method with kind=\"bar\", i.e., class by name." }, { "code": null, "e": 1614, "s": 1537, "text": "Plot the dataframe using plot() method with kind=\"bar\", i.e., class by name." }, { "code": null, "e": 1703, "s": 1614, "text": "Use twinx() method to create a twin of Axes with a shared X-axis but independent Y-axis." }, { "code": null, "e": 1792, "s": 1703, "text": "Use twinx() method to create a twin of Axes with a shared X-axis but independent Y-axis." }, { "code": null, "e": 1869, "s": 1792, "text": "Plot the axis (Step 3) ticks and dataframe columns values to plot the lines." }, { "code": null, "e": 1946, "s": 1869, "text": "Plot the axis (Step 3) ticks and dataframe columns values to plot the lines." }, { "code": null, "e": 1988, "s": 1946, "text": "To display the figure, use show() method." }, { "code": null, "e": 2030, "s": 1988, "text": "To display the figure, use show() method." }, { "code": null, "e": 2407, "s": 2030, "text": "from matplotlib import pyplot as plt\nimport pandas as pd\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndf = pd.DataFrame({\"col1\": [1, 3, 5, 7, 1], \"col2\": [1, 5, 7, 9, 1]})\nax = df.plot(kind=\"bar\")\nax2 = ax.twinx()\n\nax2.plot(ax.get_xticks(),\n df[['col1', 'col2']].values,\n linestyle='-',\n marker='o', linewidth=2.0)\n\nplt.show()" } ]
MVC Framework - Advanced Example
In the first chapter, we learnt how Controllers and Views interact in MVC. In this tutorial, we are going to take a step forward and learn how to use Models and create an advanced application to create, edit, delete. and view the list of users in our application. Step 1 − Select File → New → Project → ASP.NET MVC Web Application. Name it as AdvancedMVCApplication. Click Ok. In the next window, select Template as Internet Application and View Engine as Razor. Observe that we are using a template this time instead of an Empty application. This will create a new solution project as shown in the following screenshot. Since we are using the default ASP.NET theme, it comes with sample Views, Controllers, Models and other files. Step 2 − Build the solution and run the application to see its default output as shown in the following screenshot. Step 3 − Add a new model which will define the structure of users data. Right-click on Models folder and click Add → Class. Name this as UserModel and click Add. Step 4 − Copy the following code in the newly created UserModel.cs. using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc.Html; namespace AdvancedMVCApplication.Models { public class UserModels { [Required] public int Id { get; set; } [DisplayName("First Name")] [Required(ErrorMessage = "First name is required")] public string FirstName { get; set; } [Required] public string LastName { get; set; } public string Address { get; set; } [Required] [StringLength(50)] public string Email { get; set; } [DataType(DataType.Date)] public DateTime DOB { get; set; } [Range(100,1000000)] public decimal Salary { get; set; } } } In the above code, we have specified all the parameters that the User model has, their data types and validations such as required fields and length. Now that we have our User Model ready to hold the data, we will create a class file Users.cs, which will contain methods for viewing users, adding, editing, and deleting users. Step 5 − Right-click on Models and click Add → Class. Name it as Users. This will create users.cs class inside Models. Copy the following code in the users.cs class. using System; using System.Collections.Generic; using System.EnterpriseServices; namespace AdvancedMVCApplication.Models { public class Users { public List UserList = new List(); //action to get user details public UserModels GetUser(int id) { UserModels usrMdl = null; foreach (UserModels um in UserList) if (um.Id == id) usrMdl = um; return usrMdl; } //action to create new user public void CreateUser(UserModels userModel) { UserList.Add(userModel); } //action to udpate existing user public void UpdateUser(UserModels userModel) { foreach (UserModels usrlst in UserList) { if (usrlst.Id == userModel.Id) { usrlst.Address = userModel.Address; usrlst.DOB = userModel.DOB; usrlst.Email = userModel.Email; usrlst.FirstName = userModel.FirstName; usrlst.LastName = userModel.LastName; usrlst.Salary = userModel.Salary; break; } } } //action to delete exising user public void DeleteUser(UserModels userModel) { foreach (UserModels usrlst in UserList) { if (usrlst.Id == userModel.Id) { UserList.Remove(usrlst); break; } } } } } Once we have our UserModel.cs and Users.cs, we will add Views to our model for viewing users, adding, editing and deleting users. First let us create a View to create a user. Step 6 − Right-click on the Views folder and click Add → View. Step 7 − In the next window, select the View Name as UserAdd, View Engine as Razor and select the Create a strongly-typed view checkbox. Step 8 − Click Add. This will create the following CSHML code by default as shown below − @model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = "UserAdd"; } <h2>UserAdd</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>UserModels</legend> <div class = "editor-label"> @Html.LabelFor(model => model.FirstName) </div> <div class = "editor-field"> @Html.EditorFor(model => model.FirstName) @Html.ValidationMessageFor(model => model.FirstName) </div> <div class = "editor-label"> @Html.LabelFor(model => model.LastName) </div> <div class = "editor-field"> @Html.EditorFor(model => model.LastName) @Html.ValidationMessageFor(model => model.LastName) </div> <div class = "editor-label"> @Html.LabelFor(model => model.Address) </div> <div class = "editor-field"> @Html.EditorFor(model => model.Address) @Html.ValidationMessageFor(model => model.Address) </div> <div class = "editor-label"> @Html.LabelFor(model => model.Email) </div> <div class = "editor-field"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class = "editor-label"> @Html.LabelFor(model => model.DOB) </div> <div class = "editor-field"> @Html.EditorFor(model => model.DOB) @Html.ValidationMessageFor(model => model.DOB) </div> <div class = "editor-label"> @Html.LabelFor(model => model.Salary) </div> <div class = "editor-field"> @Html.EditorFor(model => model.Salary) @Html.ValidationMessageFor(model => model.Salary) </div> <p> <input type = "submit" value = "Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") } As you can see, this view contains view details of all the attributes of the fields including their validation messages, labels, etc. This View will look like the following in our final application. Similar to UserAdd, now we will add four more Views given below with the given code − This View will display all the users present in our system on the Index page. @model IEnumerable<AdvancedMVCApplication.Models.UserModels> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "UserAdd") </p> <table> <tr> <th> @Html.DisplayNameFor(model => model.FirstName) </th> <th> @Html.DisplayNameFor(model => model.LastName) </th> <th> @Html.DisplayNameFor(model => model.Address) </th> <th> @Html.DisplayNameFor(model => model.Email) </th> <th> @Html.DisplayNameFor(model => model.DOB) </th> <th> @Html.DisplayNameFor(model => model.Salary) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.FirstName) </td> <td> @Html.DisplayFor(modelItem => item.LastName) </td> <td> @Html.DisplayFor(modelItem => item.Address) </td> <td> @Html.DisplayFor(modelItem => item.Email) </td> <td> @Html.DisplayFor(modelItem => item.DOB) </td> <td> @Html.DisplayFor(modelItem => item.Salary) </td> <td> @Html.ActionLink("Edit", "Edit", new { id = item.Id }) | @Html.ActionLink("Details", "Details", new { id = item.Id }) | @Html.ActionLink("Delete", "Delete", new { id = item.Id }) </td> </tr> } </table> This View will look like the following in our final application. This View will display the details of a specific user when we click on the user record. @model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = "Details"; } <h2>Details</h2> <fieldset> <legend>UserModels</legend> <div class = "display-label"> @Html.DisplayNameFor(model => model.FirstName) </div> <div class = "display-field"> @Html.DisplayFor(model => model.FirstName) </div> <div class = "display-label"> @Html.DisplayNameFor(model => model.LastName) </div> <div class = "display-field"> @Html.DisplayFor(model => model.LastName) </div> <div class = "display-label"> @Html.DisplayNameFor(model => model.Address) </div> <div class = "display-field"> @Html.DisplayFor(model => model.Address) </div> <div class = "display-label"> @Html.DisplayNameFor(model => model.Email) </div> <div class = "display-field"> @Html.DisplayFor(model => model.Email) </div> <div class = "display-label"> @Html.DisplayNameFor(model => model.DOB) </div> <div class = "display-field"> @Html.DisplayFor(model => model.DOB) </div> <div class = "display-label"> @Html.DisplayNameFor(model => model.Salary) </div> <div class = "display-field"> @Html.DisplayFor(model => model.Salary) </div> </fieldset> <p> @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) | @Html.ActionLink("Back to List", "Index") </p> This View will look like the following in our final application. This View will display the edit form to edit the details of an existing user. @model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = "Edit"; } <h2>Edit</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>UserModels</legend> @Html.HiddenFor(model => model.Id) <div class = "editor-label"> @Html.LabelFor(model => model.FirstName) </div> <div class = "editor-field"> @Html.EditorFor(model => model.FirstName) @Html.ValidationMessageFor(model => model.FirstName) </div> <div class = "editor-label"> @Html.LabelFor(model => model.LastName) </div> <div class = "editor-field"> @Html.EditorFor(model => model.LastName) @Html.ValidationMessageFor(model => model.LastName) </div> <div class = "editor-label"> @Html.LabelFor(model => model.Address) </div> <div class = "editor-field"> @Html.EditorFor(model => model.Address) @Html.ValidationMessageFor(model => model.Address) </div> <div class = "editor-label"> @Html.LabelFor(model => model.Email) </div> <div class = "editor-field"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class = "editor-label"> @Html.LabelFor(model => model.DOB) </div> <div class = "editor-field"> @Html.EditorFor(model => model.DOB) @Html.ValidationMessageFor(model => model.DOB) </div> <div class = "editor-label"> @Html.LabelFor(model => model.Salary) </div> <div class = "editor-field"> @Html.EditorFor(model => model.Salary) @Html.ValidationMessageFor(model => model.Salary) </div> <p> <input type = "submit" value = "Save" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") } This View will look like the following in our application. This View will display the form to delete the existing user. @model AdvancedMVCApplication.Models.UserModels @{ ViewBag.Title = "Delete"; } <h2>Delete</h2> <h3>Are you sure you want to delete this?</h3> <fieldset> <legend>UserModels</legend> <div class = "display-label"> @Html.DisplayNameFor(model => model.FirstName) </div> <div class = "display-field"> @Html.DisplayFor(model => model.FirstName) </div> <div class = "display-label"> @Html.DisplayNameFor(model => model.LastName) </div> <div class = "display-field"> @Html.DisplayFor(model => model.LastName) </div> <div class = "display-label"> @Html.DisplayNameFor(model => model.Address) </div> <div class = "display-field"> @Html.DisplayFor(model => model.Address) </div> <div class = "display-label"> @Html.DisplayNameFor(model => model.Email) </div> <div class = "display-field"> @Html.DisplayFor(model => model.Email) </div> <div class = "display-label"> @Html.DisplayNameFor(model => model.DOB) </div> <div class = "display-field"> @Html.DisplayFor(model => model.DOB) </div> <div class = "display-label"> @Html.DisplayNameFor(model => model.Salary) </div> <div class = "display-field"> @Html.DisplayFor(model => model.Salary) </div> </fieldset> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <p> <input type = "submit" value = "Delete" /> | @Html.ActionLink("Back to List", "Index") </p> } This View will look like the following in our final application. Step 9 − We have already added the Models and Views in our application. Now finally we will add a controller for our view. Right-click on the Controllers folder and click Add → Controller. Name it as UserController. By default, your Controller class will be created with the following code − using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using AdvancedMVCApplication.Models; namespace AdvancedMVCApplication.Controllers { public class UserController : Controller { private static Users _users = new Users(); public ActionResult Index() { return View(_users.UserList); } } } In the above code, the Index method will be used while rendering the list of users on the Index page. Step 10 − Right-click on the Index method and select Create View to create a View for our Index page (which will list down all the users and provide options to create new users). Step 11 − Now add the following code in the UserController.cs. In this code, we are creating action methods for different user actions and returning corresponding views that we created earlier. We will add two methods for each operation: GET and POST. HttpGet will be used while fetching the data and rendering it. HttpPost will be used for creating/updating data. For example, when we are adding a new user, we will need a form to add a user, which is a GET operation. Once we fill the form and submit those values, we will need the POST method. //Action for Index View public ActionResult Index() { return View(_users.UserList); } //Action for UserAdd View [HttpGet] public ActionResult UserAdd() { return View(); } [HttpPost] public ActionResult UserAdd(UserModels userModel) { _users.CreateUser(userModel); return View("Index", _users.UserList); } //Action for Details View [HttpGet] public ActionResult Details(int id) { return View(_users.UserList.FirstOrDefault(x => x.Id == id)); } [HttpPost] public ActionResult Details() { return View("Index", _users.UserList); } //Action for Edit View [HttpGet] public ActionResult Edit(int id) { return View(_users.UserList.FirstOrDefault(x=>x.Id==id)); } [HttpPost] public ActionResult Edit(UserModels userModel) { _users.UpdateUser(userModel); return View("Index", _users.UserList); } //Action for Delete View [HttpGet] public ActionResult Delete(int id) { return View(_users.UserList.FirstOrDefault(x => x.Id == id)); } [HttpPost] public ActionResult Delete(UserModels userModel) { _users.DeleteUser(userModel); return View("Index", _users.UserList); } sers.UserList); Step 12 − Last thing to do is go to RouteConfig.cs file in App_Start folder and change the default Controller to User. defaults: new { controller = "User", action = "Index", id = UrlParameter.Optional } That's all we need to get our advanced application up and running. Step 13 − Now run the application. You will be able to see an application as shown in the following screenshot. You can perform all the functionalities of adding, viewing, editing, and deleting users as we saw in the earlier screenshots. 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 55 Lectures 4.5 hours University Code 40 Lectures 2.5 hours University Code 140 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2289, "s": 2025, "text": "In the first chapter, we learnt how Controllers and Views interact in MVC. In this tutorial, we are going to take a step forward and learn how to use Models and create an advanced application to create, edit, delete. and view the list of users in our application." }, { "code": null, "e": 2568, "s": 2289, "text": "Step 1 − Select File → New → Project → ASP.NET MVC Web Application. Name it as AdvancedMVCApplication. Click Ok. In the next window, select Template as Internet Application and View Engine as Razor. Observe that we are using a template this time instead of an Empty application." }, { "code": null, "e": 2757, "s": 2568, "text": "This will create a new solution project as shown in the following screenshot. Since we are using the default ASP.NET theme, it comes with sample Views, Controllers, Models and other files." }, { "code": null, "e": 2873, "s": 2757, "text": "Step 2 − Build the solution and run the application to see its default output as shown in the following screenshot." }, { "code": null, "e": 3035, "s": 2873, "text": "Step 3 − Add a new model which will define the structure of users data. Right-click on Models folder and click Add → Class. Name this as UserModel and click Add." }, { "code": null, "e": 3103, "s": 3035, "text": "Step 4 − Copy the following code in the newly created UserModel.cs." }, { "code": null, "e": 3878, "s": 3103, "text": "using System; \nusing System.ComponentModel; \nusing System.ComponentModel.DataAnnotations; \nusing System.Web.Mvc.Html; \n\nnamespace AdvancedMVCApplication.Models { \n public class UserModels { \n \n [Required] \n public int Id { get; set; } \n [DisplayName(\"First Name\")] \n [Required(ErrorMessage = \"First name is required\")] \n public string FirstName { get; set; } \n [Required] \n public string LastName { get; set; } \n \n public string Address { get; set; } \n \n [Required] \n [StringLength(50)] \n public string Email { get; set; } \n \n [DataType(DataType.Date)] \n public DateTime DOB { get; set; } \n \n [Range(100,1000000)] \n public decimal Salary { get; set; } \n } \n} " }, { "code": null, "e": 4028, "s": 3878, "text": "In the above code, we have specified all the parameters that the User model has, their data types and validations such as required fields and length." }, { "code": null, "e": 4205, "s": 4028, "text": "Now that we have our User Model ready to hold the data, we will create a class file Users.cs, which will contain methods for viewing users, adding, editing, and deleting users." }, { "code": null, "e": 4371, "s": 4205, "text": "Step 5 − Right-click on Models and click Add → Class. Name it as Users. This will create users.cs class inside Models. Copy the following code in the users.cs class." }, { "code": null, "e": 5921, "s": 4371, "text": "using System; \nusing System.Collections.Generic; \nusing System.EnterpriseServices; \n\nnamespace AdvancedMVCApplication.Models { \n \n public class Users { \n public List UserList = new List(); \n \n //action to get user details \n public UserModels GetUser(int id) { \n UserModels usrMdl = null; \n \n foreach (UserModels um in UserList) \n \n if (um.Id == id) \n usrMdl = um; \n return usrMdl; \n } \n \n //action to create new user \n public void CreateUser(UserModels userModel) { \n UserList.Add(userModel); \n } \n \n //action to udpate existing user \n public void UpdateUser(UserModels userModel) { \n \n foreach (UserModels usrlst in UserList) { \n \n if (usrlst.Id == userModel.Id) { \n usrlst.Address = userModel.Address; \n usrlst.DOB = userModel.DOB; \n usrlst.Email = userModel.Email; \n usrlst.FirstName = userModel.FirstName; \n usrlst.LastName = userModel.LastName; \n usrlst.Salary = userModel.Salary; \n break; \n } \n } \n } \n \n //action to delete exising user \n public void DeleteUser(UserModels userModel) { \n \n foreach (UserModels usrlst in UserList) { \n \n if (usrlst.Id == userModel.Id) { \n UserList.Remove(usrlst); \n break; \n } \n } \n } \n } \n} " }, { "code": null, "e": 6096, "s": 5921, "text": "Once we have our UserModel.cs and Users.cs, we will add Views to our model for viewing users, adding, editing and deleting users. First let us create a View to create a user." }, { "code": null, "e": 6159, "s": 6096, "text": "Step 6 − Right-click on the Views folder and click Add → View." }, { "code": null, "e": 6296, "s": 6159, "text": "Step 7 − In the next window, select the View Name as UserAdd, View Engine as Razor and select the Create a strongly-typed view checkbox." }, { "code": null, "e": 6386, "s": 6296, "text": "Step 8 − Click Add. This will create the following CSHML code by default as shown below −" }, { "code": null, "e": 8461, "s": 6386, "text": "@model AdvancedMVCApplication.Models.UserModels \n\n@{ \n ViewBag.Title = \"UserAdd\"; \n}\n\n<h2>UserAdd</h2> \n\n@using (Html.BeginForm()) { \n @Html.ValidationSummary(true) \n \n <fieldset> \n <legend>UserModels</legend> \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.FirstName) \n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.FirstName) \n @Html.ValidationMessageFor(model => model.FirstName) \n </div> \n \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.LastName) \n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.LastName) \n @Html.ValidationMessageFor(model => model.LastName) \n </div> \n \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.Address) \n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.Address) \n @Html.ValidationMessageFor(model => model.Address) \n </div> \n \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.Email)\n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.Email) \n @Html.ValidationMessageFor(model => model.Email) \n </div> \n \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.DOB) \n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.DOB) \n @Html.ValidationMessageFor(model => model.DOB) \n </div> \n \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.Salary) \n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.Salary) \n @Html.ValidationMessageFor(model => model.Salary) \n </div> \n \n <p> \n <input type = \"submit\" value = \"Create\" /> \n </p> \n </fieldset> \n} \n<div> \n @Html.ActionLink(\"Back to List\", \"Index\") \n</div> \n\n@section Scripts { \n \n @Scripts.Render(\"~/bundles/jqueryval\") \n}" }, { "code": null, "e": 8660, "s": 8461, "text": "As you can see, this view contains view details of all the attributes of the fields including their validation messages, labels, etc. This View will look like the following in our final application." }, { "code": null, "e": 8746, "s": 8660, "text": "Similar to UserAdd, now we will add four more Views given below with the given code −" }, { "code": null, "e": 8824, "s": 8746, "text": "This View will display all the users present in our system on the Index page." }, { "code": null, "e": 10431, "s": 8824, "text": "@model IEnumerable<AdvancedMVCApplication.Models.UserModels> \n\n@{ \n ViewBag.Title = \"Index\"; \n} \n\n<h2>Index</h2> \n\n<p> \n @Html.ActionLink(\"Create New\", \"UserAdd\") \n</p> \n\n<table> \n <tr> \n <th> \n @Html.DisplayNameFor(model => model.FirstName) \n </th> \n \n <th> \n @Html.DisplayNameFor(model => model.LastName) \n </th> \n \n <th> \n @Html.DisplayNameFor(model => model.Address) \n </th> \n \n <th> \n @Html.DisplayNameFor(model => model.Email) \n </th> \n \n <th> \n @Html.DisplayNameFor(model => model.DOB) \n </th> \n \n <th> \n @Html.DisplayNameFor(model => model.Salary) \n </th> \n \n <th></th> \n </tr> \n \n @foreach (var item in Model) { \n <tr> \n <td>\n @Html.DisplayFor(modelItem => item.FirstName) \n </td> \n \n <td> \n @Html.DisplayFor(modelItem => item.LastName) \n </td> \n \n <td> \n @Html.DisplayFor(modelItem => item.Address) \n </td> \n \n <td> \n @Html.DisplayFor(modelItem => item.Email) \n </td> \n \n <td> \n @Html.DisplayFor(modelItem => item.DOB) \n </td> \n \n <td> \n @Html.DisplayFor(modelItem => item.Salary) \n </td> \n \n <td> \n @Html.ActionLink(\"Edit\", \"Edit\", new { id = item.Id }) | \n @Html.ActionLink(\"Details\", \"Details\", new { id = item.Id }) | \n @Html.ActionLink(\"Delete\", \"Delete\", new { id = item.Id }) \n </td> \n </tr> \n } \n</table>" }, { "code": null, "e": 10496, "s": 10431, "text": "This View will look like the following in our final application." }, { "code": null, "e": 10584, "s": 10496, "text": "This View will display the details of a specific user when we click on the user record." }, { "code": null, "e": 12048, "s": 10584, "text": "@model AdvancedMVCApplication.Models.UserModels \n\n@{ \n ViewBag.Title = \"Details\"; \n} \n\n<h2>Details</h2> \n<fieldset> \n <legend>UserModels</legend> \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.FirstName) \n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.FirstName) \n </div> \n \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.LastName) \n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.LastName)\n </div> \n \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.Address) \n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.Address) \n </div> \n \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.Email) \n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.Email) \n </div> \n \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.DOB) \n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.DOB) \n </div> \n \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.Salary) \n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.Salary) \n </div> \n \n</fieldset> \n<p>\n @Html.ActionLink(\"Edit\", \"Edit\", new { id = Model.Id }) | \n @Html.ActionLink(\"Back to List\", \"Index\") \n</p>" }, { "code": null, "e": 12113, "s": 12048, "text": "This View will look like the following in our final application." }, { "code": null, "e": 12191, "s": 12113, "text": "This View will display the edit form to edit the details of an existing user." }, { "code": null, "e": 14327, "s": 12191, "text": "@model AdvancedMVCApplication.Models.UserModels \n\n@{ \n ViewBag.Title = \"Edit\"; \n} \n\n<h2>Edit</h2> \n@using (Html.BeginForm()) { \n @Html.AntiForgeryToken() \n @Html.ValidationSummary(true) \n \n <fieldset> \n <legend>UserModels</legend> \n @Html.HiddenFor(model => model.Id) \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.FirstName) \n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.FirstName) \n @Html.ValidationMessageFor(model => model.FirstName) \n </div> \n \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.LastName) \n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.LastName) \n @Html.ValidationMessageFor(model => model.LastName) \n </div> \n \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.Address) \n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.Address) \n @Html.ValidationMessageFor(model => model.Address) \n </div> \n \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.Email) \n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.Email) \n @Html.ValidationMessageFor(model => model.Email) \n </div> \n \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.DOB)\n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.DOB) \n @Html.ValidationMessageFor(model => model.DOB) \n </div> \n \n <div class = \"editor-label\"> \n @Html.LabelFor(model => model.Salary) \n </div> \n \n <div class = \"editor-field\"> \n @Html.EditorFor(model => model.Salary) \n @Html.ValidationMessageFor(model => model.Salary) \n </div> \n \n <p> \n <input type = \"submit\" value = \"Save\" /> \n </p> \n </fieldset> \n} \n<div> \n @Html.ActionLink(\"Back to List\", \"Index\") \n</div> \n\n@section Scripts { \n @Scripts.Render(\"~/bundles/jqueryval\") \n}" }, { "code": null, "e": 14386, "s": 14327, "text": "This View will look like the following in our application." }, { "code": null, "e": 14447, "s": 14386, "text": "This View will display the form to delete the existing user." }, { "code": null, "e": 16019, "s": 14447, "text": "@model AdvancedMVCApplication.Models.UserModels \n\n@{ \n ViewBag.Title = \"Delete\"; \n} \n\n<h2>Delete</h2> \n<h3>Are you sure you want to delete this?</h3> \n<fieldset> \n <legend>UserModels</legend> \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.FirstName) \n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.FirstName) \n </div> \n \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.LastName) \n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.LastName) \n </div> \n \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.Address) \n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.Address) \n </div> \n \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.Email) \n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.Email) \n </div> \n \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.DOB) \n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.DOB) \n </div> \n \n <div class = \"display-label\"> \n @Html.DisplayNameFor(model => model.Salary)\n </div> \n \n <div class = \"display-field\"> \n @Html.DisplayFor(model => model.Salary) \n </div> \n</fieldset> \n\n@using (Html.BeginForm()) { \n @Html.AntiForgeryToken() \n \n <p> \n <input type = \"submit\" value = \"Delete\" /> | \n @Html.ActionLink(\"Back to List\", \"Index\") \n </p> \n}" }, { "code": null, "e": 16084, "s": 16019, "text": "This View will look like the following in our final application." }, { "code": null, "e": 16300, "s": 16084, "text": "Step 9 − We have already added the Models and Views in our application. Now finally we will add a controller for our view. Right-click on the Controllers folder and click Add → Controller. Name it as UserController." }, { "code": null, "e": 16376, "s": 16300, "text": "By default, your Controller class will be created with the following code −" }, { "code": null, "e": 16780, "s": 16376, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Web; \nusing System.Web.Mvc; \nusing AdvancedMVCApplication.Models; \n\nnamespace AdvancedMVCApplication.Controllers { \n \n public class UserController : Controller { \n private static Users _users = new Users(); \n \n public ActionResult Index() { \n return View(_users.UserList); \n } \n } \n} " }, { "code": null, "e": 16882, "s": 16780, "text": "In the above code, the Index method will be used while rendering the list of users on the Index page." }, { "code": null, "e": 17061, "s": 16882, "text": "Step 10 − Right-click on the Index method and select Create View to create a View for our Index page (which will list down all the users and provide options to create new users)." }, { "code": null, "e": 17255, "s": 17061, "text": "Step 11 − Now add the following code in the UserController.cs. In this code, we are creating action methods for different user actions and returning corresponding views that we created earlier." }, { "code": null, "e": 17608, "s": 17255, "text": "We will add two methods for each operation: GET and POST. HttpGet will be used while fetching the data and rendering it. HttpPost will be used for creating/updating data. For example, when we are adding a new user, we will need a form to add a user, which is a GET operation. Once we fill the form and submit those values, we will need the POST method." }, { "code": null, "e": 18780, "s": 17608, "text": "//Action for Index View \npublic ActionResult Index() { \n return View(_users.UserList); \n} \n\n//Action for UserAdd View \n[HttpGet] \npublic ActionResult UserAdd() { \n return View(); \n} \n\n[HttpPost] \npublic ActionResult UserAdd(UserModels userModel) { \n _users.CreateUser(userModel); \n return View(\"Index\", _users.UserList); \n} \n\n//Action for Details View \n[HttpGet] \npublic ActionResult Details(int id) { \n return View(_users.UserList.FirstOrDefault(x => x.Id == id)); \n} \n\n[HttpPost] \npublic ActionResult Details() { \n return View(\"Index\", _users.UserList); \n} \n\n//Action for Edit View \n[HttpGet] \npublic ActionResult Edit(int id) { \n return View(_users.UserList.FirstOrDefault(x=>x.Id==id)); \n} \n\n[HttpPost] \npublic ActionResult Edit(UserModels userModel) { \n _users.UpdateUser(userModel); \n return View(\"Index\", _users.UserList); \n} \n \n//Action for Delete View \n[HttpGet] \npublic ActionResult Delete(int id) { \n return View(_users.UserList.FirstOrDefault(x => x.Id == id)); \n} \n\n[HttpPost] \npublic ActionResult Delete(UserModels userModel) { \n _users.DeleteUser(userModel); \n return View(\"Index\", _users.UserList); \n} sers.UserList);" }, { "code": null, "e": 18899, "s": 18780, "text": "Step 12 − Last thing to do is go to RouteConfig.cs file in App_Start folder and change the default Controller to User." }, { "code": null, "e": 18985, "s": 18899, "text": "defaults: new { controller = \"User\", action = \"Index\", id = UrlParameter.Optional } \n" }, { "code": null, "e": 19052, "s": 18985, "text": "That's all we need to get our advanced application up and running." }, { "code": null, "e": 19290, "s": 19052, "text": "Step 13 − Now run the application. You will be able to see an application as shown in the following screenshot. You can perform all the functionalities of adding, viewing, editing, and deleting users as we saw in the earlier screenshots." }, { "code": null, "e": 19325, "s": 19290, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 19348, "s": 19325, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 19382, "s": 19348, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 19402, "s": 19382, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 19437, "s": 19402, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 19454, "s": 19437, "text": " University Code" }, { "code": null, "e": 19489, "s": 19454, "text": "\n 55 Lectures \n 4.5 hours \n" }, { "code": null, "e": 19506, "s": 19489, "text": " University Code" }, { "code": null, "e": 19541, "s": 19506, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 19558, "s": 19541, "text": " University Code" }, { "code": null, "e": 19592, "s": 19558, "text": "\n 140 Lectures \n 9 hours \n" }, { "code": null, "e": 19607, "s": 19592, "text": " Bhrugen Patel" }, { "code": null, "e": 19614, "s": 19607, "text": " Print" }, { "code": null, "e": 19625, "s": 19614, "text": " Add Notes" } ]
Python - Sequence Assignment to Words - GeeksforGeeks
05 Sep, 2020 Given a String of words, assign index to each word. Input : test_str = ‘geekforgeeks is best’Output : {0: ‘geekforgeeks’, 1: ‘is’, 2: ‘best’}Explanation : Index assigned to each word. Input : test_str = ‘geekforgeeks best’Output : {0: ‘geekforgeeks’, 1: ‘best’}Explanation : Index assigned to each word. Method #1 : Using enumerate() + dict() + split() In this, we first perform task of split() and then add index component to map each word with index using enumerate(). Python3 # Python3 code to demonstrate working of # Sequence Assignment to Words# Using split() + enumerate() + dict() # initializing stringtest_str = 'geekforgeeks is best for geeks' # printing original stringprint("The original string is : " + str(test_str)) # using dict() to convert result in idx:word manner res = dict(enumerate(test_str.split())) # printing result print("The Assigned Sequence : " + str(res)) The original string is : geekforgeeks is best for geeks The Assigned Sequence : {0: 'geekforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'} Method #2 : Using zip() + count() + dict() In this, the count() component renders the index logic and pairing of each word to index is done using zip(). Python3 # Python3 code to demonstrate working of # Sequence Assignment to Words# Using zip() + count() + dict()from itertools import count # initializing stringtest_str = 'geekforgeeks is best for geeks' # printing original stringprint("The original string is : " + str(test_str)) # using dict() to convert result in idx:word manner # count() from itertools used for this taskres = dict(zip(count(), test_str.split())) # printing result print("The Assigned Sequence : " + str(res)) The original string is : geekforgeeks is best for geeks The Assigned Sequence : {0: 'geekforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'} Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 23971, "s": 23943, "text": "\n05 Sep, 2020" }, { "code": null, "e": 24023, "s": 23971, "text": "Given a String of words, assign index to each word." }, { "code": null, "e": 24155, "s": 24023, "text": "Input : test_str = ‘geekforgeeks is best’Output : {0: ‘geekforgeeks’, 1: ‘is’, 2: ‘best’}Explanation : Index assigned to each word." }, { "code": null, "e": 24275, "s": 24155, "text": "Input : test_str = ‘geekforgeeks best’Output : {0: ‘geekforgeeks’, 1: ‘best’}Explanation : Index assigned to each word." }, { "code": null, "e": 24324, "s": 24275, "text": "Method #1 : Using enumerate() + dict() + split()" }, { "code": null, "e": 24442, "s": 24324, "text": "In this, we first perform task of split() and then add index component to map each word with index using enumerate()." }, { "code": null, "e": 24450, "s": 24442, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Sequence Assignment to Words# Using split() + enumerate() + dict() # initializing stringtest_str = 'geekforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # using dict() to convert result in idx:word manner res = dict(enumerate(test_str.split())) # printing result print(\"The Assigned Sequence : \" + str(res)) ", "e": 24866, "s": 24450, "text": null }, { "code": null, "e": 25009, "s": 24866, "text": "The original string is : geekforgeeks is best for geeks\nThe Assigned Sequence : {0: 'geekforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'}\n" }, { "code": null, "e": 25052, "s": 25009, "text": "Method #2 : Using zip() + count() + dict()" }, { "code": null, "e": 25162, "s": 25052, "text": "In this, the count() component renders the index logic and pairing of each word to index is done using zip()." }, { "code": null, "e": 25170, "s": 25162, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Sequence Assignment to Words# Using zip() + count() + dict()from itertools import count # initializing stringtest_str = 'geekforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # using dict() to convert result in idx:word manner # count() from itertools used for this taskres = dict(zip(count(), test_str.split())) # printing result print(\"The Assigned Sequence : \" + str(res)) ", "e": 25653, "s": 25170, "text": null }, { "code": null, "e": 25796, "s": 25653, "text": "The original string is : geekforgeeks is best for geeks\nThe Assigned Sequence : {0: 'geekforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'}\n" }, { "code": null, "e": 25819, "s": 25796, "text": "Python string-programs" }, { "code": null, "e": 25826, "s": 25819, "text": "Python" }, { "code": null, "e": 25842, "s": 25826, "text": "Python Programs" }, { "code": null, "e": 25940, "s": 25842, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25949, "s": 25940, "text": "Comments" }, { "code": null, "e": 25962, "s": 25949, "text": "Old Comments" }, { "code": null, "e": 25997, "s": 25962, "text": "Read a file line by line in Python" }, { "code": null, "e": 26019, "s": 25997, "text": "Enumerate() in Python" }, { "code": null, "e": 26051, "s": 26019, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26081, "s": 26051, "text": "Iterate over a list in Python" }, { "code": null, "e": 26123, "s": 26081, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26166, "s": 26123, "text": "Python program to convert a list to string" }, { "code": null, "e": 26188, "s": 26166, "text": "Defaultdict in Python" }, { "code": null, "e": 26227, "s": 26188, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26273, "s": 26227, "text": "Python | Split string into list of characters" } ]
C++: Methods of code shortening in competitive programming - GeeksforGeeks
17 Jun, 2021 Shortcode is ideal in competitive programming because programs should be written as fast as possible. Because of this, competitive programmers often define shorter names for datatypes and other parts of the code. We here discuss the method of code shortening in C++ specifically.Type names Using the command typedef it is possible to give a shorter name to a datatype. For example, the name long long is long, so we can define a shorter name ll: typedef long long ll; After this, the code CPP long long a = 123456789;long long b = 987654321;cout << a * b << "\n"; can be shorted as follows: CPP ll a = 123456789;ll b = 987654321;cout << a * b << "\n"; The command typedef can also be used with more complex types. For example, the following code gives the name vi for a vector of integers and the name pi for a pair that contains two integers, CPP typedef vector<int> vi;typedef pair<int, int> pi; Macros Another way to shorten code is to define macros. A macro means that certain strings in the code will be changed before the compilation. In C++, macros are defined using the #define keyword. For example, we can define the following macros: #define F first #define S second #define PB push_back#define MP make_pairAfter this, the codev.push_back(make_pair(y1, x1)) ;v.push_back(make_pair(y2, x2)); int d = v[i].first+v[i].second;can be shorted as followsv.PB(MP(y1, x1)); v.PB(MP(y2, x2)); int d = v[i].F+v[i].S; A macro can also have parameters which makes it possible to shorten loops and others structures. For example, we can define the following macro: #define REP(i, a, b) for (int i=a; i<=b; i++) After this, the code for (int i=1; i<=n; i++){ search(i); } can be shortened as follows: REP(i, 1, n){ search(i); }A version of template given below This can be use in competitive programming for faster coding. CPP #include <bits/stdc++.h> // Include every standard libraryusing namespace std; typedef long long LL;typedef pair<int, int> pii;typedef pair<LL, LL> pll;typedef pair<string, string> pss;typedef vector<int> vi;typedef vector<vi> vvi;typedef vector<pii> vii;typedef vector<LL> vl;typedef vector<vl> vvl; double EPS = 1e-9;int INF = 1000000005;long long INFF = 1000000000000000005LL;double PI = acos(-1);int dirx[8] = { -1, 0, 0, 1, -1, -1, 1, 1 };int diry[8] = { 0, 1, -1, 0, -1, 1, -1, 1 }; #ifdef TESTING#define DEBUG fprintf(stderr, "====TESTING====\n")#define VALUE(x) cerr << "The value of " << #x << " is " << x << endl#define debug(...) fprintf(stderr, __VA_ARGS__)#else#define DEBUG#define VALUE(x)#define debug(...)#endif #define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a))#define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a))#define FORD(a, b, c) for (int(a) = (b); (a) >= (c); --(a))#define FORSQ(a, b, c) for (int(a) = (b); (a) * (a) <= (c); ++(a))#define FORC(a, b, c) for (char(a) = (b); (a) <= (c); ++(a))#define FOREACH(a, b) for (auto&(a) : (b))#define REP(i, n) FOR(i, 0, n)#define REPN(i, n) FORN(i, 1, n)#define MAX(a, b) a = max(a, b)#define MIN(a, b) a = min(a, b)#define SQR(x) ((LL)(x) * (x))#define RESET(a, b) memset(a, b, sizeof(a))#define fi first#define se second#define mp make_pair#define pb push_back#define ALL(v) v.begin(), v.end()#define ALLA(arr, sz) arr, arr + sz#define SIZE(v) (int)v.size()#define SORT(v) sort(ALL(v))#define REVERSE(v) reverse(ALL(v))#define SORTA(arr, sz) sort(ALLA(arr, sz))#define REVERSEA(arr, sz) reverse(ALLA(arr, sz))#define PERMUTE next_permutation#define TC(t) while (t--) inline string IntToString(LL a){ char x[100]; sprintf(x, "%lld", a); string s = x; return s;} inline LL StringToInt(string a){ char x[100]; LL res; strcpy(x, a.c_str()); sscanf(x, "%lld", &res); return res;} inline string GetString(void){ char x[1000005]; scanf("%s", x); string s = x; return s;} inline string uppercase(string s){ int n = SIZE(s); REP(i, n) if (s[i] >= 'a' && s[i] <= 'z') s[i] = s[i] - 'a' + 'A'; return s;} inline string lowercase(string s){ int n = SIZE(s); REP(i, n) if (s[i] >= 'A' && s[i] <= 'Z') s[i] = s[i] - 'A' + 'a'; return s;} inline void OPEN(string s){#ifndef TESTING freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout);#endif} // end of Sektor_jr template v2.0.3 (BETA) int main(){ freopen("A.in", "r", stdin); freopen("output.txt", "w", stdout); int a, b; fin >> a >> b; fout << a + b << endl; return 0;} sachiniyermalkapur amtheshubham abhishek0719kadiyan cpp-macros C Language C++ Competitive Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Substring in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ C++ Classes and Objects Constructors in C++
[ { "code": null, "e": 24275, "s": 24247, "text": "\n17 Jun, 2021" }, { "code": null, "e": 24766, "s": 24275, "text": "Shortcode is ideal in competitive programming because programs should be written as fast as possible. Because of this, competitive programmers often define shorter names for datatypes and other parts of the code. We here discuss the method of code shortening in C++ specifically.Type names Using the command typedef it is possible to give a shorter name to a datatype. For example, the name long long is long, so we can define a shorter name ll: typedef long long ll; After this, the code " }, { "code": null, "e": 24770, "s": 24766, "text": "CPP" }, { "code": "long long a = 123456789;long long b = 987654321;cout << a * b << \"\\n\";", "e": 24841, "s": 24770, "text": null }, { "code": null, "e": 24870, "s": 24841, "text": "can be shorted as follows: " }, { "code": null, "e": 24874, "s": 24870, "text": "CPP" }, { "code": "ll a = 123456789;ll b = 987654321;cout << a * b << \"\\n\";", "e": 24931, "s": 24874, "text": null }, { "code": null, "e": 25125, "s": 24931, "text": "The command typedef can also be used with more complex types. For example, the following code gives the name vi for a vector of integers and the name pi for a pair that contains two integers, " }, { "code": null, "e": 25129, "s": 25125, "text": "CPP" }, { "code": "typedef vector<int> vi;typedef pair<int, int> pi;", "e": 25179, "s": 25129, "text": null }, { "code": null, "e": 26101, "s": 25179, "text": "Macros Another way to shorten code is to define macros. A macro means that certain strings in the code will be changed before the compilation. In C++, macros are defined using the #define keyword. For example, we can define the following macros: #define F first #define S second #define PB push_back#define MP make_pairAfter this, the codev.push_back(make_pair(y1, x1)) ;v.push_back(make_pair(y2, x2)); int d = v[i].first+v[i].second;can be shorted as followsv.PB(MP(y1, x1)); v.PB(MP(y2, x2)); int d = v[i].F+v[i].S; A macro can also have parameters which makes it possible to shorten loops and others structures. For example, we can define the following macro: #define REP(i, a, b) for (int i=a; i<=b; i++) After this, the code for (int i=1; i<=n; i++){ search(i); } can be shortened as follows: REP(i, 1, n){ search(i); }A version of template given below This can be use in competitive programming for faster coding. " }, { "code": null, "e": 26105, "s": 26101, "text": "CPP" }, { "code": "#include <bits/stdc++.h> // Include every standard libraryusing namespace std; typedef long long LL;typedef pair<int, int> pii;typedef pair<LL, LL> pll;typedef pair<string, string> pss;typedef vector<int> vi;typedef vector<vi> vvi;typedef vector<pii> vii;typedef vector<LL> vl;typedef vector<vl> vvl; double EPS = 1e-9;int INF = 1000000005;long long INFF = 1000000000000000005LL;double PI = acos(-1);int dirx[8] = { -1, 0, 0, 1, -1, -1, 1, 1 };int diry[8] = { 0, 1, -1, 0, -1, 1, -1, 1 }; #ifdef TESTING#define DEBUG fprintf(stderr, \"====TESTING====\\n\")#define VALUE(x) cerr << \"The value of \" << #x << \" is \" << x << endl#define debug(...) fprintf(stderr, __VA_ARGS__)#else#define DEBUG#define VALUE(x)#define debug(...)#endif #define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a))#define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a))#define FORD(a, b, c) for (int(a) = (b); (a) >= (c); --(a))#define FORSQ(a, b, c) for (int(a) = (b); (a) * (a) <= (c); ++(a))#define FORC(a, b, c) for (char(a) = (b); (a) <= (c); ++(a))#define FOREACH(a, b) for (auto&(a) : (b))#define REP(i, n) FOR(i, 0, n)#define REPN(i, n) FORN(i, 1, n)#define MAX(a, b) a = max(a, b)#define MIN(a, b) a = min(a, b)#define SQR(x) ((LL)(x) * (x))#define RESET(a, b) memset(a, b, sizeof(a))#define fi first#define se second#define mp make_pair#define pb push_back#define ALL(v) v.begin(), v.end()#define ALLA(arr, sz) arr, arr + sz#define SIZE(v) (int)v.size()#define SORT(v) sort(ALL(v))#define REVERSE(v) reverse(ALL(v))#define SORTA(arr, sz) sort(ALLA(arr, sz))#define REVERSEA(arr, sz) reverse(ALLA(arr, sz))#define PERMUTE next_permutation#define TC(t) while (t--) inline string IntToString(LL a){ char x[100]; sprintf(x, \"%lld\", a); string s = x; return s;} inline LL StringToInt(string a){ char x[100]; LL res; strcpy(x, a.c_str()); sscanf(x, \"%lld\", &res); return res;} inline string GetString(void){ char x[1000005]; scanf(\"%s\", x); string s = x; return s;} inline string uppercase(string s){ int n = SIZE(s); REP(i, n) if (s[i] >= 'a' && s[i] <= 'z') s[i] = s[i] - 'a' + 'A'; return s;} inline string lowercase(string s){ int n = SIZE(s); REP(i, n) if (s[i] >= 'A' && s[i] <= 'Z') s[i] = s[i] - 'A' + 'a'; return s;} inline void OPEN(string s){#ifndef TESTING freopen((s + \".in\").c_str(), \"r\", stdin); freopen((s + \".out\").c_str(), \"w\", stdout);#endif} // end of Sektor_jr template v2.0.3 (BETA) int main(){ freopen(\"A.in\", \"r\", stdin); freopen(\"output.txt\", \"w\", stdout); int a, b; fin >> a >> b; fout << a + b << endl; return 0;}", "e": 28727, "s": 26105, "text": null }, { "code": null, "e": 28746, "s": 28727, "text": "sachiniyermalkapur" }, { "code": null, "e": 28759, "s": 28746, "text": "amtheshubham" }, { "code": null, "e": 28779, "s": 28759, "text": "abhishek0719kadiyan" }, { "code": null, "e": 28790, "s": 28779, "text": "cpp-macros" }, { "code": null, "e": 28801, "s": 28790, "text": "C Language" }, { "code": null, "e": 28805, "s": 28801, "text": "C++" }, { "code": null, "e": 28829, "s": 28805, "text": "Competitive Programming" }, { "code": null, "e": 28833, "s": 28829, "text": "CPP" }, { "code": null, "e": 28931, "s": 28833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28940, "s": 28931, "text": "Comments" }, { "code": null, "e": 28953, "s": 28940, "text": "Old Comments" }, { "code": null, "e": 28981, "s": 28953, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 29027, "s": 28981, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 29039, "s": 29027, "text": "fork() in C" }, { "code": null, "e": 29071, "s": 29039, "text": "Command line arguments in C/C++" }, { "code": null, "e": 29088, "s": 29071, "text": "Substring in C++" }, { "code": null, "e": 29134, "s": 29088, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 29177, "s": 29134, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 29196, "s": 29177, "text": "Inheritance in C++" }, { "code": null, "e": 29220, "s": 29196, "text": "C++ Classes and Objects" } ]
API calls on Blockchain; best practices for data collection | by Patrick Collins | Towards Data Science
Most software engineers, when looking to get data from outside their programs, look to get data from API calls or HTTP GET/POST requests. Similarly, on a blockchain, people look to get data from an external API as well. This article will teach you how to do that! Let’s get going, here is step one: Got you. You actually can’t get data from an API call the same way you get data from normal software applications. However, in order for our smart contracts to do anything worthwhile, we would want them to interact with the outside world. So what gives? The Ethereum blockchain was designed to be entirely deterministic. This means, that if I took the whole history of the network, then replayed it on my computer, I should always end up with the correct state. Since the internet is non-deterministic and changes over time, then every time I replayed all of the transactions on the network, I would receive a different answer. — Tjaden Hess on StackOverflow Instead of the contract calling the API directly, we need to have it call an application that can interact with the outside world, and have it record its findings on-chain. These are called Oracles. Oracles are any application that interacts with data from the outside world and reports it back on-chain. If we replayed the chain without oracles and used regular API calls, the API calls might have changed, and we’d get different results. Thanks for the technicality definition update, but how do I get my data into my solidity application? Ok ok, let’s get into what you actually came here for. In our example, we will be just trying to get the price of ETH in USD. Now if you’re a TOTAL NOOB here with this Remix, solidity, Chainlink, and want a step by step guide, feel free to check out my more in-depth guide: Write your first solidity contract or Chainlink’s documentation. We all were imposters once :D If you want to follow along and just press the buttons without having to choose your own oracles, you can follow along with all the code and deploy it with me in Remix here (code included in the hyperlink). HOWEVER, THAT CODE IS FOR DEMO ONLY AND YOU SHOULD NOT USE IT FOR PRODUCTION. You should put JobIDs and addresses as parameters. You can follow that along with us in Remix here for the more productized version. You’ll notice two of the steps are missing. This is intentional ;) Go to the gists section. Be sure to send ROPSTEN LINK to your contracts after deploying them, otherwise, you’ll get a gas estimation error. You can get ropsten LINK here. DO NOT SEND YOUR ACTUAL LINK WHEN YOU ARE TESTING. Please. Please. Please. You can use the withdrawLink function if you accidentally send it LINK. One other note: I tend to use oracle and node interchangeably, while technically not correct, the distinction between the two for this article is negligible. The first approach most blockchain engineers start with is just finding an oracle technology, giving it the URL of our API call, and then having it do its thing of reporting the data on-chain for us to interact with. There are a number of oracles we can use to do this. We will be using Chainlink for reasons you’ll see soon. To use Chainlink, we first have to pick a Chainlink oracle/node. These are independently operated smart contracts on the blockchain that allow you to interact with the world. To find one, we can go to node listing services like Linkpool’s Market.Link, and just choose a node. We then have to make sure that the node has a “http Get > uint256” job. Not every node can make URL calls and return a Uint256 (basically an Int), but most do! The node we choose was a Linkpool node at the address in the ORACLE variable. All the magic happens in the requestEthereumPrice function. If you’ve followed Chainlink’s tutorials before, you know that this is the most simple way to get data using Chainlink. This is great! We can get data. This is fine if you’re just testing and want to quickly develop your code, but please do not use this for a production smart contract. Why? It comes with one major issue: You are pulling from one oracle and one data provider. This is not decentralized data! You need decentralized data in your solidity smart contracts otherwise you lose a major benefit of the application. Now Linkpool is one of the most trusted Chainlink node services out there, but your application needs to be trustless. Not only that, but you’re also getting your data from one source as well, now you have TWO points of failure in your application. CryptoCompare and LinkPool are both massive liabilities that can be easily remedied. This is a rant worthy point that I will spare you from here, but let me drill it once more. Your smart contract needs to never have a single point of failure, as that point can be bribed, hacked, be out-of-service at execution time, or many other reasons that leave your smart contract worthless. So how do we fix this issue? We’ve gone a step forward now and chosen 3 nodes that we will route our API calls to, greatly mitigating the issue from the naive approach. Now to get the price, we have added a median function, that takes the median of all the answers provided. This way if one or two give wildly different answers, we are more likely to still get the true value of ETH. You can see how added even more nodes would increase how little trust you have to put into each node. Ideally, we’d also choose different data providers, but for simplicity, I’ve kept the same ones in the examples. Ideally continued, you’d like even more than 3 nodes, but at least now there are no single points of failure. At the moment, 7 or 21 nodes seems to be considered “decent”. Why 7 and 21? No idea. So this is much better though! We now have decentralized data in solidity! Although, there is a lot of code that goes into this, is there a simpler way to route my API calls to multiple nodes? I’m glad you asked. If this part gets confusing for you, feel free to skip to 3.5 This one requires an extra step. You’ll notice in the remix link, there was one file that was just two lines of code. pragma solidity ^0.5.0;import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.5/PreCoordinator.sol"; That’s it. What this does, it that it creates what’s called a service agreement. This takes a list of oracle address and job IDs that you give it, and will fan out your API call to all those oracles, take the median, and everything for you, using the syntax of the naive approach! Deploy theprecoordinator.sol, and in the GUI, add your oracle addresses, jobIDpayments (100000000000000000 = 0.1 LINK), and _minResponses. This is the minimum number of responses needed from each oracle. Let’s say you have 5 oracles, and only 2 respond. If you set the minimum responses to 3, this would negate the rest of your smart contract. Which is ideal, since if we don’t have enough oracles respond, it will be less decentralized. Once you launch a service agreement, you can use the address of the service agreement as your Oracle address, and the ID of the service agreement as the jobID. You’ll notice the syntax of this step is nearly identical to the naive approach. This is so that once you do all your testing with one oracle and are ready to move to production, you can just launch a service agreement and change the oracle and jobID, but keep all of the rest of your code the same. It’s easy then to create new service agreements using different oracles if you decide some of the oracles you are using are giving you poor responses. You can do this without having to rewrite any of your existing code, just swap the IDs out for the new service agreement. I don’t know about you, but I like it when I have to do less work to get more done. This step is the most control you can have over a Chainlinked network. You can choose your nodes, data providers, and integrate and change them easily. Note on data providers: Right now, the precoordinator can only send the same data package to every provider, meaning if the JSON output of different data APIs is different, you’d have to send different copyPaths. The way to send the same information while using different data providers is to wrap them all in an external adapter that formats their outputs to be the same. Stay tuned for updates on how to do this! Sometimes you have to learn the hard way before you get the easier ways right?address PreCoordinator= 0x11db7845a757041F5Dad3fAf81d70ebAd394e9A2; bytes32 constant patrick_service_agreement = 0xcb08d1dbcc1b0621b4e8d4aea6bafc79f456e12332c782b4258c7e83bcedb74c; The PreCoordinator address above you can use on Ropsten to deploy arbitrary Service agreements. The patrick_service_agreement address you can use to send your httpget request to a few nodes I picked. Ideally, you don’t store the PreCoordinator patrick_service_agreement , or payment in your code, but accept them as parameters of your functions. I hope to get questions at the bottom if this confuses you. A lot of oracles technologies have an out-the-box solution as well. Chainlink is no different. They have taken time to vet multiple nodes and data providers to give data feeds on a number of high use price feeds for anyone to use. I’ve written about them before in Building Smart Contracts, Smartly, and they are the pinnacle of simplicity and decentralization. You can find a list of the reference contracts they have on their feeds page. The ONLY part that makes it more centralized, is that Chainlink has chosen the list of nodes, this means that you have to trust a little in the node choosing ability of the Chainlink team. However, if you want a pre-boxed answer where maintenance of decentralization is outsourced to the Chainlink team, this is a huge advantage. Otherwise, you can always build your own Chainlink network of nodes to get your decentralized data in solidity! The other best part of this is that it’s currently free, and is sponsored by awesome companies like Synthetix. I’m sure in the future this will change as it’s not a sustainable model. Whew. There is a lot to cover here. I hope I have drilled the decentralization point. One of the main advantages of the blockchain is that we can have trustless applications. Building a blockchain application with centralized data sources and oracles is like buying a bike so you don’t have to walk to work anymore, then proceeding to continue to walk to work with your bike strapped to your back. You have invested the time in a solution and then proceed to still not solve the original problem, even though you have the solution right there. Now that you have the tools and understand the importance here, let’s see you build something! For all new and experienced blockchain engineers, there are a ton of ways to join. AlphaVHack is a hackathon coming up for new engineers. You can join the Chainlink discord, build your first end-to-end blockchain solution with this awesome class from Udemy. Or just leave me a comment below asking how to find out more about anything above, talk soon! Think I missed something? Were you able to follow the remix code? Don’t understand anything? Leave a question, comment, or insight below! All opinions here are my own. Follow me on twitter, medium, github, linkedin, discord, for more content and insights. Check out my latest article on Medium here! #financerevolution #blockchain #ETH #chainlink #smartcontracts
[ { "code": null, "e": 471, "s": 172, "text": "Most software engineers, when looking to get data from outside their programs, look to get data from API calls or HTTP GET/POST requests. Similarly, on a blockchain, people look to get data from an external API as well. This article will teach you how to do that! Let’s get going, here is step one:" }, { "code": null, "e": 480, "s": 471, "text": "Got you." }, { "code": null, "e": 725, "s": 480, "text": "You actually can’t get data from an API call the same way you get data from normal software applications. However, in order for our smart contracts to do anything worthwhile, we would want them to interact with the outside world. So what gives?" }, { "code": null, "e": 933, "s": 725, "text": "The Ethereum blockchain was designed to be entirely deterministic. This means, that if I took the whole history of the network, then replayed it on my computer, I should always end up with the correct state." }, { "code": null, "e": 1099, "s": 933, "text": "Since the internet is non-deterministic and changes over time, then every time I replayed all of the transactions on the network, I would receive a different answer." }, { "code": null, "e": 1130, "s": 1099, "text": "— Tjaden Hess on StackOverflow" }, { "code": null, "e": 1435, "s": 1130, "text": "Instead of the contract calling the API directly, we need to have it call an application that can interact with the outside world, and have it record its findings on-chain. These are called Oracles. Oracles are any application that interacts with data from the outside world and reports it back on-chain." }, { "code": null, "e": 1570, "s": 1435, "text": "If we replayed the chain without oracles and used regular API calls, the API calls might have changed, and we’d get different results." }, { "code": null, "e": 1672, "s": 1570, "text": "Thanks for the technicality definition update, but how do I get my data into my solidity application?" }, { "code": null, "e": 1798, "s": 1672, "text": "Ok ok, let’s get into what you actually came here for. In our example, we will be just trying to get the price of ETH in USD." }, { "code": null, "e": 2041, "s": 1798, "text": "Now if you’re a TOTAL NOOB here with this Remix, solidity, Chainlink, and want a step by step guide, feel free to check out my more in-depth guide: Write your first solidity contract or Chainlink’s documentation. We all were imposters once :D" }, { "code": null, "e": 2526, "s": 2041, "text": "If you want to follow along and just press the buttons without having to choose your own oracles, you can follow along with all the code and deploy it with me in Remix here (code included in the hyperlink). HOWEVER, THAT CODE IS FOR DEMO ONLY AND YOU SHOULD NOT USE IT FOR PRODUCTION. You should put JobIDs and addresses as parameters. You can follow that along with us in Remix here for the more productized version. You’ll notice two of the steps are missing. This is intentional ;)" }, { "code": null, "e": 2844, "s": 2526, "text": "Go to the gists section. Be sure to send ROPSTEN LINK to your contracts after deploying them, otherwise, you’ll get a gas estimation error. You can get ropsten LINK here. DO NOT SEND YOUR ACTUAL LINK WHEN YOU ARE TESTING. Please. Please. Please. You can use the withdrawLink function if you accidentally send it LINK." }, { "code": null, "e": 3002, "s": 2844, "text": "One other note: I tend to use oracle and node interchangeably, while technically not correct, the distinction between the two for this article is negligible." }, { "code": null, "e": 3328, "s": 3002, "text": "The first approach most blockchain engineers start with is just finding an oracle technology, giving it the URL of our API call, and then having it do its thing of reporting the data on-chain for us to interact with. There are a number of oracles we can use to do this. We will be using Chainlink for reasons you’ll see soon." }, { "code": null, "e": 3764, "s": 3328, "text": "To use Chainlink, we first have to pick a Chainlink oracle/node. These are independently operated smart contracts on the blockchain that allow you to interact with the world. To find one, we can go to node listing services like Linkpool’s Market.Link, and just choose a node. We then have to make sure that the node has a “http Get > uint256” job. Not every node can make URL calls and return a Uint256 (basically an Int), but most do!" }, { "code": null, "e": 4022, "s": 3764, "text": "The node we choose was a Linkpool node at the address in the ORACLE variable. All the magic happens in the requestEthereumPrice function. If you’ve followed Chainlink’s tutorials before, you know that this is the most simple way to get data using Chainlink." }, { "code": null, "e": 4225, "s": 4022, "text": "This is great! We can get data. This is fine if you’re just testing and want to quickly develop your code, but please do not use this for a production smart contract. Why? It comes with one major issue:" }, { "code": null, "e": 4428, "s": 4225, "text": "You are pulling from one oracle and one data provider. This is not decentralized data! You need decentralized data in your solidity smart contracts otherwise you lose a major benefit of the application." }, { "code": null, "e": 4854, "s": 4428, "text": "Now Linkpool is one of the most trusted Chainlink node services out there, but your application needs to be trustless. Not only that, but you’re also getting your data from one source as well, now you have TWO points of failure in your application. CryptoCompare and LinkPool are both massive liabilities that can be easily remedied. This is a rant worthy point that I will spare you from here, but let me drill it once more." }, { "code": null, "e": 5059, "s": 4854, "text": "Your smart contract needs to never have a single point of failure, as that point can be bribed, hacked, be out-of-service at execution time, or many other reasons that leave your smart contract worthless." }, { "code": null, "e": 5088, "s": 5059, "text": "So how do we fix this issue?" }, { "code": null, "e": 5545, "s": 5088, "text": "We’ve gone a step forward now and chosen 3 nodes that we will route our API calls to, greatly mitigating the issue from the naive approach. Now to get the price, we have added a median function, that takes the median of all the answers provided. This way if one or two give wildly different answers, we are more likely to still get the true value of ETH. You can see how added even more nodes would increase how little trust you have to put into each node." }, { "code": null, "e": 5853, "s": 5545, "text": "Ideally, we’d also choose different data providers, but for simplicity, I’ve kept the same ones in the examples. Ideally continued, you’d like even more than 3 nodes, but at least now there are no single points of failure. At the moment, 7 or 21 nodes seems to be considered “decent”. Why 7 and 21? No idea." }, { "code": null, "e": 6046, "s": 5853, "text": "So this is much better though! We now have decentralized data in solidity! Although, there is a lot of code that goes into this, is there a simpler way to route my API calls to multiple nodes?" }, { "code": null, "e": 6066, "s": 6046, "text": "I’m glad you asked." }, { "code": null, "e": 6128, "s": 6066, "text": "If this part gets confusing for you, feel free to skip to 3.5" }, { "code": null, "e": 6246, "s": 6128, "text": "This one requires an extra step. You’ll notice in the remix link, there was one file that was just two lines of code." }, { "code": null, "e": 6359, "s": 6246, "text": "pragma solidity ^0.5.0;import \"github.com/smartcontractkit/chainlink/evm-contracts/src/v0.5/PreCoordinator.sol\";" }, { "code": null, "e": 6370, "s": 6359, "text": "That’s it." }, { "code": null, "e": 6640, "s": 6370, "text": "What this does, it that it creates what’s called a service agreement. This takes a list of oracle address and job IDs that you give it, and will fan out your API call to all those oracles, take the median, and everything for you, using the syntax of the naive approach!" }, { "code": null, "e": 6844, "s": 6640, "text": "Deploy theprecoordinator.sol, and in the GUI, add your oracle addresses, jobIDpayments (100000000000000000 = 0.1 LINK), and _minResponses. This is the minimum number of responses needed from each oracle." }, { "code": null, "e": 7078, "s": 6844, "text": "Let’s say you have 5 oracles, and only 2 respond. If you set the minimum responses to 3, this would negate the rest of your smart contract. Which is ideal, since if we don’t have enough oracles respond, it will be less decentralized." }, { "code": null, "e": 7538, "s": 7078, "text": "Once you launch a service agreement, you can use the address of the service agreement as your Oracle address, and the ID of the service agreement as the jobID. You’ll notice the syntax of this step is nearly identical to the naive approach. This is so that once you do all your testing with one oracle and are ready to move to production, you can just launch a service agreement and change the oracle and jobID, but keep all of the rest of your code the same." }, { "code": null, "e": 7811, "s": 7538, "text": "It’s easy then to create new service agreements using different oracles if you decide some of the oracles you are using are giving you poor responses. You can do this without having to rewrite any of your existing code, just swap the IDs out for the new service agreement." }, { "code": null, "e": 7895, "s": 7811, "text": "I don’t know about you, but I like it when I have to do less work to get more done." }, { "code": null, "e": 8047, "s": 7895, "text": "This step is the most control you can have over a Chainlinked network. You can choose your nodes, data providers, and integrate and change them easily." }, { "code": null, "e": 8462, "s": 8047, "text": "Note on data providers: Right now, the precoordinator can only send the same data package to every provider, meaning if the JSON output of different data APIs is different, you’d have to send different copyPaths. The way to send the same information while using different data providers is to wrap them all in an external adapter that formats their outputs to be the same. Stay tuned for updates on how to do this!" }, { "code": null, "e": 8608, "s": 8462, "text": "Sometimes you have to learn the hard way before you get the easier ways right?address PreCoordinator= 0x11db7845a757041F5Dad3fAf81d70ebAd394e9A2;" }, { "code": null, "e": 8721, "s": 8608, "text": "bytes32 constant patrick_service_agreement = 0xcb08d1dbcc1b0621b4e8d4aea6bafc79f456e12332c782b4258c7e83bcedb74c;" }, { "code": null, "e": 8921, "s": 8721, "text": "The PreCoordinator address above you can use on Ropsten to deploy arbitrary Service agreements. The patrick_service_agreement address you can use to send your httpget request to a few nodes I picked." }, { "code": null, "e": 9067, "s": 8921, "text": "Ideally, you don’t store the PreCoordinator patrick_service_agreement , or payment in your code, but accept them as parameters of your functions." }, { "code": null, "e": 9127, "s": 9067, "text": "I hope to get questions at the bottom if this confuses you." }, { "code": null, "e": 9358, "s": 9127, "text": "A lot of oracles technologies have an out-the-box solution as well. Chainlink is no different. They have taken time to vet multiple nodes and data providers to give data feeds on a number of high use price feeds for anyone to use." }, { "code": null, "e": 9489, "s": 9358, "text": "I’ve written about them before in Building Smart Contracts, Smartly, and they are the pinnacle of simplicity and decentralization." }, { "code": null, "e": 10009, "s": 9489, "text": "You can find a list of the reference contracts they have on their feeds page. The ONLY part that makes it more centralized, is that Chainlink has chosen the list of nodes, this means that you have to trust a little in the node choosing ability of the Chainlink team. However, if you want a pre-boxed answer where maintenance of decentralization is outsourced to the Chainlink team, this is a huge advantage. Otherwise, you can always build your own Chainlink network of nodes to get your decentralized data in solidity!" }, { "code": null, "e": 10193, "s": 10009, "text": "The other best part of this is that it’s currently free, and is sponsored by awesome companies like Synthetix. I’m sure in the future this will change as it’s not a sustainable model." }, { "code": null, "e": 10368, "s": 10193, "text": "Whew. There is a lot to cover here. I hope I have drilled the decentralization point. One of the main advantages of the blockchain is that we can have trustless applications." }, { "code": null, "e": 10591, "s": 10368, "text": "Building a blockchain application with centralized data sources and oracles is like buying a bike so you don’t have to walk to work anymore, then proceeding to continue to walk to work with your bike strapped to your back." }, { "code": null, "e": 10737, "s": 10591, "text": "You have invested the time in a solution and then proceed to still not solve the original problem, even though you have the solution right there." }, { "code": null, "e": 11184, "s": 10737, "text": "Now that you have the tools and understand the importance here, let’s see you build something! For all new and experienced blockchain engineers, there are a ton of ways to join. AlphaVHack is a hackathon coming up for new engineers. You can join the Chainlink discord, build your first end-to-end blockchain solution with this awesome class from Udemy. Or just leave me a comment below asking how to find out more about anything above, talk soon!" }, { "code": null, "e": 11322, "s": 11184, "text": "Think I missed something? Were you able to follow the remix code? Don’t understand anything? Leave a question, comment, or insight below!" }, { "code": null, "e": 11352, "s": 11322, "text": "All opinions here are my own." }, { "code": null, "e": 11484, "s": 11352, "text": "Follow me on twitter, medium, github, linkedin, discord, for more content and insights. Check out my latest article on Medium here!" } ]
How to Query Your Pandas Dataframe | Towards Data Science
IntroductionMultiple ConditionsMerging On Multiple, Specific ColumnsSummaryReferences Introduction Multiple Conditions Merging On Multiple, Specific Columns Summary References Whether you are transitioning from a data engineer/data analyst or wanting to become a more efficient data scientist, querying your dataframe can prove to be quite a useful method of returning specific rows that you want. It is important to note that there is a specific query function for pandas, appropriately named, query. However, I will instead be discussing the other ways that you can mimic querying, filtering, and merging your data. We will present common scenarios or questions that you would ask to your data, and rather than SQL, we will do it with Python. In the paragraphs below, I will outline some simple ways of querying rows for your pandas dataframe with the Python programming language. As data scientists or data analysts, we want to return specific rows of data. One of these scenarios is where you want to apply multiple conditions, all in the same line of code. In order to display my example, I have created some fake sample data of a first and last name, as well as their respective gender and birthdate. This data is displayed above in the screenshot. The example multiple conditions will essentially answer a specific question, just like when you use SQL. The question is, what percent of our data is Male gender OR a person who was born between 2010 and 2021. Here is the code that will solve that question (there are a few ways to answer this question, but here is my specific way of doing it): print(“Percent of data who are Males OR were born between 2010 and 2021:”, 100*round(df[(df[‘Gender’] == ‘M’) | (df[‘Birthdate’] >= ‘2010–01–01’) & (df[‘Birthdate’] <= ‘2021–01–01’)][‘Gender’].count()/df.shape [0],4), “%”) To better visualize this code, I have also included this screenshot of that same code from above, along with the output/result. You can also apply these conditions to return the actual rows instead of getting the fraction or percent of rows out of the total rows. Here is the order of commands we performed: Return rows with Male Gender Include the OR function | Return the rows of Birthdate > 2010 and 2021 Combine those all, and then divide by the total amount of rows As you can see, this code is similar to something you would see in SQL. I personally think it is easier in pandas because it can be less code, while also being able to visually see all the code in one easy spot, without having to scroll up and down (but this format is just my preference). We have probably seen how to merge dataframes together in other tutorials, so I wanted to add a unique approach that I have not really seen out there, which is merging on multiple, specific columns. In this scenario, we want to join two dataframes where two fields are shared between them. You could tell that if there are even more columns, this method could be even more useful. We have our first dataframe, which is df, then we are merging our columns on a second dataframe, df2. Here is that code to achieve our expected result: merged_df = df.merge(df2, how=’inner’, left_on=cols, right_on=cols ) To better visualize this merging and code, I have presented the screenshot below. You see what the second dataframe looks like below, with the First and Last names, just like they are in the first dataframe, but with a new column, Numeric. Then, we have out specific columns that we wanted to merge on, while returning columns Gender, Birthdate, and the new Numeric column as well. The columns are a list of columns, which is named cols. As you can see, this way of merging dataframes is a simple way to achieve the same results that you would get from a SQL query. In this tutorial, we saw two common questions or queries that you would perform in SQL, but instead, have performed them with pandas dataframes in Python. To summarize, here are the two scenarios we worked with: * Returning the percent of rows out of the total dataset from multiple conditions* Merging on multiple, specific columns to return a final datafarme with a new column I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with these methods. Why or why not? These can certainly be clarified even further, but I hope I was able to shed some light on some of the ways you can use pandas and Python instead of SQL. Thank you for reading! Please feel free to check out my profile, Matt Przybyla, and other articles, as well as reach out to me on LinkedIn. I am not affiliated with these companies. [1] Photo by Bruce Hong on Unsplash, (2018) [2] M. Przybyla, sample data screenshot, (2021) [3] M. Przybyla, conditions code screenshot, (2021) [4] M. Przybyla, merged dataframe result screenshot, (2021) [5] M. Przybyla, merging dataframe screenshot, (2021)
[ { "code": null, "e": 258, "s": 172, "text": "IntroductionMultiple ConditionsMerging On Multiple, Specific ColumnsSummaryReferences" }, { "code": null, "e": 271, "s": 258, "text": "Introduction" }, { "code": null, "e": 291, "s": 271, "text": "Multiple Conditions" }, { "code": null, "e": 329, "s": 291, "text": "Merging On Multiple, Specific Columns" }, { "code": null, "e": 337, "s": 329, "text": "Summary" }, { "code": null, "e": 348, "s": 337, "text": "References" }, { "code": null, "e": 1055, "s": 348, "text": "Whether you are transitioning from a data engineer/data analyst or wanting to become a more efficient data scientist, querying your dataframe can prove to be quite a useful method of returning specific rows that you want. It is important to note that there is a specific query function for pandas, appropriately named, query. However, I will instead be discussing the other ways that you can mimic querying, filtering, and merging your data. We will present common scenarios or questions that you would ask to your data, and rather than SQL, we will do it with Python. In the paragraphs below, I will outline some simple ways of querying rows for your pandas dataframe with the Python programming language." }, { "code": null, "e": 1427, "s": 1055, "text": "As data scientists or data analysts, we want to return specific rows of data. One of these scenarios is where you want to apply multiple conditions, all in the same line of code. In order to display my example, I have created some fake sample data of a first and last name, as well as their respective gender and birthdate. This data is displayed above in the screenshot." }, { "code": null, "e": 1637, "s": 1427, "text": "The example multiple conditions will essentially answer a specific question, just like when you use SQL. The question is, what percent of our data is Male gender OR a person who was born between 2010 and 2021." }, { "code": null, "e": 1773, "s": 1637, "text": "Here is the code that will solve that question (there are a few ways to answer this question, but here is my specific way of doing it):" }, { "code": null, "e": 1997, "s": 1773, "text": "print(“Percent of data who are Males OR were born between 2010 and 2021:”, 100*round(df[(df[‘Gender’] == ‘M’) | (df[‘Birthdate’] >= ‘2010–01–01’) & (df[‘Birthdate’] <= ‘2021–01–01’)][‘Gender’].count()/df.shape [0],4), “%”)" }, { "code": null, "e": 2261, "s": 1997, "text": "To better visualize this code, I have also included this screenshot of that same code from above, along with the output/result. You can also apply these conditions to return the actual rows instead of getting the fraction or percent of rows out of the total rows." }, { "code": null, "e": 2305, "s": 2261, "text": "Here is the order of commands we performed:" }, { "code": null, "e": 2334, "s": 2305, "text": "Return rows with Male Gender" }, { "code": null, "e": 2360, "s": 2334, "text": "Include the OR function |" }, { "code": null, "e": 2405, "s": 2360, "text": "Return the rows of Birthdate > 2010 and 2021" }, { "code": null, "e": 2468, "s": 2405, "text": "Combine those all, and then divide by the total amount of rows" }, { "code": null, "e": 2758, "s": 2468, "text": "As you can see, this code is similar to something you would see in SQL. I personally think it is easier in pandas because it can be less code, while also being able to visually see all the code in one easy spot, without having to scroll up and down (but this format is just my preference)." }, { "code": null, "e": 3139, "s": 2758, "text": "We have probably seen how to merge dataframes together in other tutorials, so I wanted to add a unique approach that I have not really seen out there, which is merging on multiple, specific columns. In this scenario, we want to join two dataframes where two fields are shared between them. You could tell that if there are even more columns, this method could be even more useful." }, { "code": null, "e": 3291, "s": 3139, "text": "We have our first dataframe, which is df, then we are merging our columns on a second dataframe, df2. Here is that code to achieve our expected result:" }, { "code": null, "e": 3362, "s": 3291, "text": "merged_df = df.merge(df2, how=’inner’, left_on=cols, right_on=cols )" }, { "code": null, "e": 3800, "s": 3362, "text": "To better visualize this merging and code, I have presented the screenshot below. You see what the second dataframe looks like below, with the First and Last names, just like they are in the first dataframe, but with a new column, Numeric. Then, we have out specific columns that we wanted to merge on, while returning columns Gender, Birthdate, and the new Numeric column as well. The columns are a list of columns, which is named cols." }, { "code": null, "e": 3928, "s": 3800, "text": "As you can see, this way of merging dataframes is a simple way to achieve the same results that you would get from a SQL query." }, { "code": null, "e": 4083, "s": 3928, "text": "In this tutorial, we saw two common questions or queries that you would perform in SQL, but instead, have performed them with pandas dataframes in Python." }, { "code": null, "e": 4140, "s": 4083, "text": "To summarize, here are the two scenarios we worked with:" }, { "code": null, "e": 4307, "s": 4140, "text": "* Returning the percent of rows out of the total dataset from multiple conditions* Merging on multiple, specific columns to return a final datafarme with a new column" }, { "code": null, "e": 4641, "s": 4307, "text": "I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with these methods. Why or why not? These can certainly be clarified even further, but I hope I was able to shed some light on some of the ways you can use pandas and Python instead of SQL. Thank you for reading!" }, { "code": null, "e": 4758, "s": 4641, "text": "Please feel free to check out my profile, Matt Przybyla, and other articles, as well as reach out to me on LinkedIn." }, { "code": null, "e": 4800, "s": 4758, "text": "I am not affiliated with these companies." }, { "code": null, "e": 4844, "s": 4800, "text": "[1] Photo by Bruce Hong on Unsplash, (2018)" }, { "code": null, "e": 4892, "s": 4844, "text": "[2] M. Przybyla, sample data screenshot, (2021)" }, { "code": null, "e": 4944, "s": 4892, "text": "[3] M. Przybyla, conditions code screenshot, (2021)" }, { "code": null, "e": 5004, "s": 4944, "text": "[4] M. Przybyla, merged dataframe result screenshot, (2021)" } ]
Find minimum cost to buy all books - GeeksforGeeks
22 Jun, 2021 Given an array of ratings for n books. Find the minimum cost to buy all books with below conditions : Cost of every book would be at-least 1 dollar.A book has higher cost than an adjacent (left or right) if rating is more than the adjacent. Cost of every book would be at-least 1 dollar. A book has higher cost than an adjacent (left or right) if rating is more than the adjacent. Examples : Input : Ratings[] = {1, 3, 4, 3, 7, 1} Output : 10 Exp :- 1 + 2 + 3 + 1 + 2 + 1 = 10 Input : ratings[] = {1, 6, 8, 3, 4, 1, 5, 7} Output : 15 Exp :- 1 + 2 + 3 + 1 + 2 + 1 + 2 + 3 = 15 Make two arrays left2right and right2left and fill 1 in both of them.Traverse left to right and fill left2right array and update it by seeing previous rating of given array. Do not care about next rating of given array.Traverse right to left and fill right2left array and update it by seeing next rating of given array. Do not care about previous rating of given array.Find maximum value of ith position in both array (left2right and right2left) and add it to result Make two arrays left2right and right2left and fill 1 in both of them. Traverse left to right and fill left2right array and update it by seeing previous rating of given array. Do not care about next rating of given array. Traverse right to left and fill right2left array and update it by seeing next rating of given array. Do not care about previous rating of given array. Find maximum value of ith position in both array (left2right and right2left) and add it to result C++ Java Python C# Javascript // C++ program to find minimum cost to buy// n books.#include <bits/stdc++.h>using namespace std; int minCost(int ratings[], int n){ int res = 0; int left2right[n]; int right2left[n]; // fill 1 in both array fill_n(left2right, n, 1); fill_n(right2left, n, 1); // Traverse from left to right and assign // minimum possible rating considering only // left adjacent for (int i = 1; i < n; i++) if (ratings[i] > ratings[i - 1]) left2right[i] = left2right[i - 1] + 1; // Traverse from right to left and assign // minimum possible rating considering only // right adjacent for (int i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i + 1]) right2left[i] = right2left[i + 1] + 1; // Since we need to follow rating rule for // both adjacent, we pick maximum of two for (int i = 0; i < n; i++) res += max(left2right[i], right2left[i]); return res;} // Driver functionint main(){ int ratings[] = { 1, 6, 8, 3, 4, 1, 5, 7 }; int n = sizeof(ratings) / sizeof(ratings[0]); cout << minCost(ratings, n); return 0;} // JAVA Code For Find minimum cost to// buy all booksimport java.util.*; class GFG { public static int minCost(int ratings[], int n) { int res = 0; int left2right[] = new int[n]; int right2left[] = new int[n];; // fill 1 in both array Arrays.fill(left2right, 1); Arrays.fill(right2left, 1); // Traverse from left to right and assign // minimum possible rating considering // only left adjacent for (int i = 1; i < n; i++) if (ratings[i] > ratings[i - 1]) left2right[i] = left2right[i - 1] + 1; // Traverse from right to left and assign // minimum possible rating considering only // right adjacent for (int i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i + 1]) right2left[i] = right2left[i + 1] + 1; // Since we need to follow rating rule for // both adjacent, we pick maximum of two for (int i = 0; i < n; i++) res += Math.max(left2right[i], right2left[i]); return res; } /* Driver program to test above function */ public static void main(String[] args) { int ratings[] = { 1, 6, 8, 3, 4, 1, 5, 7 }; int n = ratings.length; System.out.print(minCost(ratings, n)); }} // This code is contributed by Arnav Kr. Mandal. # Python program to find minimum cost to buy# n books. def minCost(ratings, n): res = 0 # fill 1 in both array left2right = [1 for i in range(n)] right2left = [1 for i in range(n)] # Traverse from left to right and assign # minimum possible rating considering only # left adjacent for i in range(1, n): if (ratings[i] > ratings[i - 1]): left2right[i] = left2right[i - 1] + 1 # Traverse from right to left and assign # minimum possible rating considering only # right adjacent i = n - 2 while(i >= 0): if (ratings[i] > ratings[i + 1]): right2left[i] = right2left[i + 1] + 1 i -= 1 # Since we need to follow rating rule for # both adjacent, we pick maximum of two for i in range(n): res += max(left2right[i], right2left[i]) return res # Driver functionratings = [ 1, 6, 8, 3, 4, 1, 5, 7 ]n = len(ratings)print minCost(ratings, n) # This code is contributed by Sachin Bisht // C# code For Finding minimum// cost to buy all booksusing System; class GFG { public static int minCost(int []ratings, int n) { int res = 0; int []left2right = new int[n]; int []right2left = new int[n]; // fill 1 in both array for(int i = 0; i < n; i++) left2right[i] = 1; for(int i = 0; i < n; i++) right2left[i] = 1; // Traverse from left to right and assign // minimum possible rating considering // only left adjacent for (int i = 1; i < n; i++) if (ratings[i] > ratings[i - 1]) left2right[i] = left2right[i - 1] + 1; // Traverse from right to left and assign // minimum possible rating considering only // right adjacent for (int i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i + 1]) right2left[i] = right2left[i + 1] + 1; // Since we need to follow rating rule for // both adjacent, we pick maximum of two for (int i = 0; i < n; i++) res += Math.Max(left2right[i], right2left[i]); return res; } /* Driver program to test above function */ public static void Main() { int []ratings = {1, 6, 8, 3, 4, 1, 5, 7}; int n = ratings.Length; Console.Write(minCost(ratings, n)); }} // This code is contributed by nitin mittal. <script> // JavaScript program to find minimum cost to buy// n books. function minCost(ratings, n) { let res = 0; let left2right = new Array(n).fill(1); let right2left = new Array(n).fill(1); // Traverse from left to right and assign // minimum possible rating considering only // left adjacent for (let i = 1; i < n; i++) if (ratings[i] > ratings[i - 1]) left2right[i] = left2right[i - 1] + 1; // Traverse from right to left and assign // minimum possible rating considering only // right adjacent for (let i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i + 1]) right2left[i] = right2left[i + 1] + 1; // Since we need to follow rating rule for // both adjacent, we pick maximum of two for (let i = 0; i < n; i++) res += Math.max(left2right[i], right2left[i]); return res;} // Driver function let ratings = [1, 6, 8, 3, 4, 1, 5, 7];let n = ratings.length;document.write(minCost(ratings, n)); </script> Output: 15 Time complexity – O(n) Auxiliary Space – O(n)This article is contributed by Harshit Agrawal. 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. nitin mittal _saurabh_jaiswal Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Maximum and minimum of an array using minimum number of comparisons Python | Using 2D arrays/lists the right way Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 25052, "s": 25024, "text": "\n22 Jun, 2021" }, { "code": null, "e": 25156, "s": 25052, "text": "Given an array of ratings for n books. Find the minimum cost to buy all books with below conditions : " }, { "code": null, "e": 25295, "s": 25156, "text": "Cost of every book would be at-least 1 dollar.A book has higher cost than an adjacent (left or right) if rating is more than the adjacent." }, { "code": null, "e": 25342, "s": 25295, "text": "Cost of every book would be at-least 1 dollar." }, { "code": null, "e": 25435, "s": 25342, "text": "A book has higher cost than an adjacent (left or right) if rating is more than the adjacent." }, { "code": null, "e": 25448, "s": 25435, "text": "Examples : " }, { "code": null, "e": 25634, "s": 25448, "text": "Input : Ratings[] = {1, 3, 4, 3, 7, 1}\nOutput : 10\nExp :- 1 + 2 + 3 + 1 + 2 + 1 = 10\n\nInput : ratings[] = {1, 6, 8, 3, 4, 1, 5, 7}\nOutput : 15\nExp :- 1 + 2 + 3 + 1 + 2 + 1 + 2 + 3 = 15 " }, { "code": null, "e": 26105, "s": 25638, "text": "Make two arrays left2right and right2left and fill 1 in both of them.Traverse left to right and fill left2right array and update it by seeing previous rating of given array. Do not care about next rating of given array.Traverse right to left and fill right2left array and update it by seeing next rating of given array. Do not care about previous rating of given array.Find maximum value of ith position in both array (left2right and right2left) and add it to result" }, { "code": null, "e": 26175, "s": 26105, "text": "Make two arrays left2right and right2left and fill 1 in both of them." }, { "code": null, "e": 26326, "s": 26175, "text": "Traverse left to right and fill left2right array and update it by seeing previous rating of given array. Do not care about next rating of given array." }, { "code": null, "e": 26477, "s": 26326, "text": "Traverse right to left and fill right2left array and update it by seeing next rating of given array. Do not care about previous rating of given array." }, { "code": null, "e": 26575, "s": 26477, "text": "Find maximum value of ith position in both array (left2right and right2left) and add it to result" }, { "code": null, "e": 26583, "s": 26579, "text": "C++" }, { "code": null, "e": 26588, "s": 26583, "text": "Java" }, { "code": null, "e": 26595, "s": 26588, "text": "Python" }, { "code": null, "e": 26598, "s": 26595, "text": "C#" }, { "code": null, "e": 26609, "s": 26598, "text": "Javascript" }, { "code": "// C++ program to find minimum cost to buy// n books.#include <bits/stdc++.h>using namespace std; int minCost(int ratings[], int n){ int res = 0; int left2right[n]; int right2left[n]; // fill 1 in both array fill_n(left2right, n, 1); fill_n(right2left, n, 1); // Traverse from left to right and assign // minimum possible rating considering only // left adjacent for (int i = 1; i < n; i++) if (ratings[i] > ratings[i - 1]) left2right[i] = left2right[i - 1] + 1; // Traverse from right to left and assign // minimum possible rating considering only // right adjacent for (int i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i + 1]) right2left[i] = right2left[i + 1] + 1; // Since we need to follow rating rule for // both adjacent, we pick maximum of two for (int i = 0; i < n; i++) res += max(left2right[i], right2left[i]); return res;} // Driver functionint main(){ int ratings[] = { 1, 6, 8, 3, 4, 1, 5, 7 }; int n = sizeof(ratings) / sizeof(ratings[0]); cout << minCost(ratings, n); return 0;}", "e": 27740, "s": 26609, "text": null }, { "code": "// JAVA Code For Find minimum cost to// buy all booksimport java.util.*; class GFG { public static int minCost(int ratings[], int n) { int res = 0; int left2right[] = new int[n]; int right2left[] = new int[n];; // fill 1 in both array Arrays.fill(left2right, 1); Arrays.fill(right2left, 1); // Traverse from left to right and assign // minimum possible rating considering // only left adjacent for (int i = 1; i < n; i++) if (ratings[i] > ratings[i - 1]) left2right[i] = left2right[i - 1] + 1; // Traverse from right to left and assign // minimum possible rating considering only // right adjacent for (int i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i + 1]) right2left[i] = right2left[i + 1] + 1; // Since we need to follow rating rule for // both adjacent, we pick maximum of two for (int i = 0; i < n; i++) res += Math.max(left2right[i], right2left[i]); return res; } /* Driver program to test above function */ public static void main(String[] args) { int ratings[] = { 1, 6, 8, 3, 4, 1, 5, 7 }; int n = ratings.length; System.out.print(minCost(ratings, n)); }} // This code is contributed by Arnav Kr. Mandal.", "e": 29188, "s": 27740, "text": null }, { "code": "# Python program to find minimum cost to buy# n books. def minCost(ratings, n): res = 0 # fill 1 in both array left2right = [1 for i in range(n)] right2left = [1 for i in range(n)] # Traverse from left to right and assign # minimum possible rating considering only # left adjacent for i in range(1, n): if (ratings[i] > ratings[i - 1]): left2right[i] = left2right[i - 1] + 1 # Traverse from right to left and assign # minimum possible rating considering only # right adjacent i = n - 2 while(i >= 0): if (ratings[i] > ratings[i + 1]): right2left[i] = right2left[i + 1] + 1 i -= 1 # Since we need to follow rating rule for # both adjacent, we pick maximum of two for i in range(n): res += max(left2right[i], right2left[i]) return res # Driver functionratings = [ 1, 6, 8, 3, 4, 1, 5, 7 ]n = len(ratings)print minCost(ratings, n) # This code is contributed by Sachin Bisht", "e": 30190, "s": 29188, "text": null }, { "code": "// C# code For Finding minimum// cost to buy all booksusing System; class GFG { public static int minCost(int []ratings, int n) { int res = 0; int []left2right = new int[n]; int []right2left = new int[n]; // fill 1 in both array for(int i = 0; i < n; i++) left2right[i] = 1; for(int i = 0; i < n; i++) right2left[i] = 1; // Traverse from left to right and assign // minimum possible rating considering // only left adjacent for (int i = 1; i < n; i++) if (ratings[i] > ratings[i - 1]) left2right[i] = left2right[i - 1] + 1; // Traverse from right to left and assign // minimum possible rating considering only // right adjacent for (int i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i + 1]) right2left[i] = right2left[i + 1] + 1; // Since we need to follow rating rule for // both adjacent, we pick maximum of two for (int i = 0; i < n; i++) res += Math.Max(left2right[i], right2left[i]); return res; } /* Driver program to test above function */ public static void Main() { int []ratings = {1, 6, 8, 3, 4, 1, 5, 7}; int n = ratings.Length; Console.Write(minCost(ratings, n)); }} // This code is contributed by nitin mittal.", "e": 31654, "s": 30190, "text": null }, { "code": "<script> // JavaScript program to find minimum cost to buy// n books. function minCost(ratings, n) { let res = 0; let left2right = new Array(n).fill(1); let right2left = new Array(n).fill(1); // Traverse from left to right and assign // minimum possible rating considering only // left adjacent for (let i = 1; i < n; i++) if (ratings[i] > ratings[i - 1]) left2right[i] = left2right[i - 1] + 1; // Traverse from right to left and assign // minimum possible rating considering only // right adjacent for (let i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i + 1]) right2left[i] = right2left[i + 1] + 1; // Since we need to follow rating rule for // both adjacent, we pick maximum of two for (let i = 0; i < n; i++) res += Math.max(left2right[i], right2left[i]); return res;} // Driver function let ratings = [1, 6, 8, 3, 4, 1, 5, 7];let n = ratings.length;document.write(minCost(ratings, n)); </script>", "e": 32651, "s": 31654, "text": null }, { "code": null, "e": 32661, "s": 32651, "text": "Output: " }, { "code": null, "e": 32664, "s": 32661, "text": "15" }, { "code": null, "e": 33133, "s": 32664, "text": "Time complexity – O(n) Auxiliary Space – O(n)This article is contributed by Harshit Agrawal. 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": 33146, "s": 33133, "text": "nitin mittal" }, { "code": null, "e": 33163, "s": 33146, "text": "_saurabh_jaiswal" }, { "code": null, "e": 33170, "s": 33163, "text": "Arrays" }, { "code": null, "e": 33177, "s": 33170, "text": "Arrays" }, { "code": null, "e": 33275, "s": 33177, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33323, "s": 33275, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33367, "s": 33323, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33399, "s": 33367, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33422, "s": 33399, "text": "Introduction to Arrays" }, { "code": null, "e": 33436, "s": 33422, "text": "Linear Search" }, { "code": null, "e": 33504, "s": 33436, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33549, "s": 33504, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 33570, "s": 33549, "text": "Linked List vs Array" }, { "code": null, "e": 33655, "s": 33570, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" } ]
Apache Commons DBUtils - Environment Setup
To start developing with DBUtils, you should setup your DBUtils environment by following the steps shown below. We assume that you are working on a Windows platform. Install J2SE Development Kit 5.0 (JDK 5.0) from Java Official Site. Make sure following environment variables are set as described below − JAVA_HOME − This environment variable should point to the directory where you installed the JDK, e.g. C:\Program Files\Java\jdk1.5.0. JAVA_HOME − This environment variable should point to the directory where you installed the JDK, e.g. C:\Program Files\Java\jdk1.5.0. CLASSPATH − This environment variable should have appropriate paths set, e.g. C:\Program Files\Java\jdk1.5.0_20\jre\lib. CLASSPATH − This environment variable should have appropriate paths set, e.g. C:\Program Files\Java\jdk1.5.0_20\jre\lib. PATH − This environment variable should point to appropriate JRE bin, e.g. C:\Program Files\Java\jre1.5.0_20\bin. PATH − This environment variable should point to appropriate JRE bin, e.g. C:\Program Files\Java\jre1.5.0_20\bin. It is possible you have these variable set already, but just to make sure here's how to check. Go to the control panel and double-click on System. If you are a Windows XP user, it is possible you have to open Performance and Maintenance before you will see the System icon. Go to the control panel and double-click on System. If you are a Windows XP user, it is possible you have to open Performance and Maintenance before you will see the System icon. Go to the Advanced tab and click on the Environment Variables. Go to the Advanced tab and click on the Environment Variables. Now check if all the above mentioned variables are set properly. Now check if all the above mentioned variables are set properly. The most important thing you will need, of course is an actual running database with a table that you can query and modify. Install a database that is most suitable for you. You can have plenty of choices and most common are − MySQL DB: MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation. In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier. Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\Program Files\MySQL\mysql-connector-java-5.1.8. Accordingly, set CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation. MySQL DB: MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation. In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier. Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\Program Files\MySQL\mysql-connector-java-5.1.8. Accordingly, set CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation. PostgreSQL DB: PostgreSQL is an open source database. You can download it from PostgreSQL Official Site. The Postgres installation contains a GUI based administrative tool called pgAdmin III. JDBC drivers are also included as part of the installation. PostgreSQL DB: PostgreSQL is an open source database. You can download it from PostgreSQL Official Site. The Postgres installation contains a GUI based administrative tool called pgAdmin III. JDBC drivers are also included as part of the installation. Oracle DB − Oracle DB is a commercial database sold by Oracle . We assume that you have the necessary distribution media to install it. Oracle installation includes a GUI based administrative tool called Enterprise Manager. JDBC drivers are also included as a part of the installation. Oracle DB − Oracle DB is a commercial database sold by Oracle . We assume that you have the necessary distribution media to install it. Oracle installation includes a GUI based administrative tool called Enterprise Manager. JDBC drivers are also included as a part of the installation. The latest JDK includes a JDBC-ODBC Bridge driver that makes most Open Database Connectivity (ODBC) drivers available to programmers using the JDBC API. Now a days, most of the Database vendors are supplying appropriate JDBC drivers along with Database installation. So, you should not worry about this part. For this tutorial we are going to use MySQL database. When you install any of the above database, its administrator ID is set to root and gives provision to set a password of your choice. Using root ID and password you can either create another user ID and password, or you can use root ID and password for your JDBC application. There are various database operations like database creation and deletion, which would need administrator ID and password. For rest of the JDBC tutorial, we would use MySQL Database with username as ID and password as password. If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to create a user ID and password for you. To create the emp database, use the following steps − Open a Command Prompt and change to the installation directory as follows − C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Note: The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server. Start the database server by executing the following command, if it is already not running. C:\Program Files\MySQL\bin>mysqld C:\Program Files\MySQL\bin> Create the emp database by executing the following command − C:\Program Files\MySQL\bin> mysqladmin create emp -u root -p Enter password: ******** C:\Program Files\MySQL\bin> To create the Employees table in emp database, use the following steps − Open a Command Prompt and change to the installation directory as follows − C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Login to the database as follows − C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql> Create the table Employee as follows − mysql> use emp; mysql> create table Employees -> ( -> id int not null, -> age int not null, -> first varchar (255), -> last varchar (255) -> ); Query OK, 0 rows affected (0.08 sec) mysql> Finally you create few records in Employee table as follows − mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal'); Query OK, 1 row affected (0.00 sec) mysql> For a complete understanding on MySQL database, study the MySQL Tutorial. Download the latest version of Apache Common DBUtils jar file from commons-dbutils-1.7-bin.zip, MySql connector mysql-connector-java-5.1.28-bin.jar , Apache Commons DBCP commons-dbcp2-2.1.1-bin.zip, Apache Commons Pool commons-pool2-2.4.3-bin.zip and , Apache Commons Logging commons-logging-1.2-bin.zip . At the time of writing this tutorial, we have downloaded commons-dbutils-1.7-bin.zip, mysql-connector-java-5.1.28-bin.jar, commons-dbcp2-2.1.1-bin.zip, commons-pool2-2.4.3-bin.zip, commons-logging-1.2-bin.zip and copied it into C:\>Apache folder. Set the APACHE_HOME environment variable to point to the base directory location where Apache jar is stored on your machine. Assuming, we've extracted commons-dbutils-1.7-bin.zip in Apache folder on various Operating Systems as follows. Set the CLASSPATH environment variable to point to the Common IO jar location. Assuming, you have stored commons-dbutils-1.7-bin.zip in Apache folder on various Operating Systems as follows. Now you are ready to start experimenting with DBUtils. Next chapter gives you a sample example on DBUtils Programming. Print Add Notes Bookmark this page
[ { "code": null, "e": 2318, "s": 2152, "text": "To start developing with DBUtils, you should setup your DBUtils environment by following the steps shown below. We assume that you are working on a Windows platform." }, { "code": null, "e": 2386, "s": 2318, "text": "Install J2SE Development Kit 5.0 (JDK 5.0) from Java Official Site." }, { "code": null, "e": 2457, "s": 2386, "text": "Make sure following environment variables are set as described below −" }, { "code": null, "e": 2591, "s": 2457, "text": "JAVA_HOME − This environment variable should point to the directory where you installed the JDK, e.g. C:\\Program Files\\Java\\jdk1.5.0." }, { "code": null, "e": 2725, "s": 2591, "text": "JAVA_HOME − This environment variable should point to the directory where you installed the JDK, e.g. C:\\Program Files\\Java\\jdk1.5.0." }, { "code": null, "e": 2846, "s": 2725, "text": "CLASSPATH − This environment variable should have appropriate paths set, e.g. C:\\Program Files\\Java\\jdk1.5.0_20\\jre\\lib." }, { "code": null, "e": 2967, "s": 2846, "text": "CLASSPATH − This environment variable should have appropriate paths set, e.g. C:\\Program Files\\Java\\jdk1.5.0_20\\jre\\lib." }, { "code": null, "e": 3081, "s": 2967, "text": "PATH − This environment variable should point to appropriate JRE bin, e.g. C:\\Program Files\\Java\\jre1.5.0_20\\bin." }, { "code": null, "e": 3195, "s": 3081, "text": "PATH − This environment variable should point to appropriate JRE bin, e.g. C:\\Program Files\\Java\\jre1.5.0_20\\bin." }, { "code": null, "e": 3290, "s": 3195, "text": "It is possible you have these variable set already, but just to make sure here's how to check." }, { "code": null, "e": 3469, "s": 3290, "text": "Go to the control panel and double-click on System. If you are a Windows XP user, it is possible you have to open Performance and Maintenance before you will see the System icon." }, { "code": null, "e": 3648, "s": 3469, "text": "Go to the control panel and double-click on System. If you are a Windows XP user, it is possible you have to open Performance and Maintenance before you will see the System icon." }, { "code": null, "e": 3711, "s": 3648, "text": "Go to the Advanced tab and click on the Environment Variables." }, { "code": null, "e": 3774, "s": 3711, "text": "Go to the Advanced tab and click on the Environment Variables." }, { "code": null, "e": 3839, "s": 3774, "text": "Now check if all the above mentioned variables are set properly." }, { "code": null, "e": 3904, "s": 3839, "text": "Now check if all the above mentioned variables are set properly." }, { "code": null, "e": 4028, "s": 3904, "text": "The most important thing you will need, of course is an actual running database with a table that you can query and modify." }, { "code": null, "e": 4131, "s": 4028, "text": "Install a database that is most suitable for you. You can have plenty of choices and most common are −" }, { "code": null, "e": 4850, "s": 4131, "text": "MySQL DB: MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation.\nIn addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier.\nFinally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8.\nAccordingly, set CLASSPATH variable to C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8\\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation." }, { "code": null, "e": 4996, "s": 4850, "text": "MySQL DB: MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation." }, { "code": null, "e": 5153, "s": 4996, "text": "In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier." }, { "code": null, "e": 5387, "s": 5153, "text": "Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8." }, { "code": null, "e": 5569, "s": 5387, "text": "Accordingly, set CLASSPATH variable to C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8\\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation." }, { "code": null, "e": 5821, "s": 5569, "text": "PostgreSQL DB: PostgreSQL is an open source database. You can download it from PostgreSQL Official Site.\nThe Postgres installation contains a GUI based administrative tool called pgAdmin III. JDBC drivers are also included as part of the installation." }, { "code": null, "e": 5926, "s": 5821, "text": "PostgreSQL DB: PostgreSQL is an open source database. You can download it from PostgreSQL Official Site." }, { "code": null, "e": 6073, "s": 5926, "text": "The Postgres installation contains a GUI based administrative tool called pgAdmin III. JDBC drivers are also included as part of the installation." }, { "code": null, "e": 6359, "s": 6073, "text": "Oracle DB − Oracle DB is a commercial database sold by Oracle . We assume that you have the necessary distribution media to install it.\nOracle installation includes a GUI based administrative tool called Enterprise Manager. JDBC drivers are also included as a part of the installation." }, { "code": null, "e": 6495, "s": 6359, "text": "Oracle DB − Oracle DB is a commercial database sold by Oracle . We assume that you have the necessary distribution media to install it." }, { "code": null, "e": 6645, "s": 6495, "text": "Oracle installation includes a GUI based administrative tool called Enterprise Manager. JDBC drivers are also included as a part of the installation." }, { "code": null, "e": 6798, "s": 6645, "text": "The latest JDK includes a JDBC-ODBC Bridge driver that makes most Open Database Connectivity (ODBC) drivers available to programmers using the JDBC API." }, { "code": null, "e": 6954, "s": 6798, "text": "Now a days, most of the Database vendors are supplying appropriate JDBC drivers along with Database installation. So, you should not worry about this part." }, { "code": null, "e": 7142, "s": 6954, "text": "For this tutorial we are going to use MySQL database. When you install any of the above database, its administrator ID is set to root and gives provision to set a password of your choice." }, { "code": null, "e": 7284, "s": 7142, "text": "Using root ID and password you can either create another user ID and password, or you can use root ID and password for your JDBC application." }, { "code": null, "e": 7407, "s": 7284, "text": "There are various database operations like database creation and deletion, which would need administrator ID and password." }, { "code": null, "e": 7512, "s": 7407, "text": "For rest of the JDBC tutorial, we would use MySQL Database with username as ID and password as password." }, { "code": null, "e": 7667, "s": 7512, "text": "If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to create a user ID and password for you." }, { "code": null, "e": 7721, "s": 7667, "text": "To create the emp database, use the following steps −" }, { "code": null, "e": 7797, "s": 7721, "text": "Open a Command Prompt and change to the installation directory as follows −" }, { "code": null, "e": 7862, "s": 7797, "text": "C:\\>\nC:\\>cd Program Files\\MySQL\\bin\nC:\\Program Files\\MySQL\\bin>\n" }, { "code": null, "e": 8039, "s": 7862, "text": "Note: The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server." }, { "code": null, "e": 8131, "s": 8039, "text": "Start the database server by executing the following command, if it is already not running." }, { "code": null, "e": 8194, "s": 8131, "text": "C:\\Program Files\\MySQL\\bin>mysqld\nC:\\Program Files\\MySQL\\bin>\n" }, { "code": null, "e": 8255, "s": 8194, "text": "Create the emp database by executing the following command −" }, { "code": null, "e": 8370, "s": 8255, "text": "C:\\Program Files\\MySQL\\bin> mysqladmin create emp -u root -p\nEnter password: ********\nC:\\Program Files\\MySQL\\bin>\n" }, { "code": null, "e": 8443, "s": 8370, "text": "To create the Employees table in emp database, use the following steps −" }, { "code": null, "e": 8519, "s": 8443, "text": "Open a Command Prompt and change to the installation directory as follows −" }, { "code": null, "e": 8584, "s": 8519, "text": "C:\\>\nC:\\>cd Program Files\\MySQL\\bin\nC:\\Program Files\\MySQL\\bin>\n" }, { "code": null, "e": 8619, "s": 8584, "text": "Login to the database as follows −" }, { "code": null, "e": 8696, "s": 8619, "text": "C:\\Program Files\\MySQL\\bin>mysql -u root -p\nEnter password: ********\nmysql>\n" }, { "code": null, "e": 8735, "s": 8696, "text": "Create the table Employee as follows −" }, { "code": null, "e": 8947, "s": 8735, "text": "mysql> use emp;\nmysql> create table Employees\n -> (\n -> id int not null,\n -> age int not null,\n -> first varchar (255),\n -> last varchar (255)\n -> );\nQuery OK, 0 rows affected (0.08 sec)\nmysql>" }, { "code": null, "e": 9009, "s": 8947, "text": "Finally you create few records in Employee table as follows −" }, { "code": null, "e": 9421, "s": 9009, "text": "mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');\nQuery OK, 1 row affected (0.05 sec)\n\nmysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql>" }, { "code": null, "e": 9495, "s": 9421, "text": "For a complete understanding on MySQL database, study the MySQL Tutorial." }, { "code": null, "e": 10049, "s": 9495, "text": "Download the latest version of Apache Common DBUtils jar file from commons-dbutils-1.7-bin.zip, MySql connector mysql-connector-java-5.1.28-bin.jar , Apache Commons DBCP commons-dbcp2-2.1.1-bin.zip, Apache Commons Pool commons-pool2-2.4.3-bin.zip and , Apache Commons Logging commons-logging-1.2-bin.zip . At the time of writing this tutorial, we have downloaded commons-dbutils-1.7-bin.zip, mysql-connector-java-5.1.28-bin.jar, commons-dbcp2-2.1.1-bin.zip, commons-pool2-2.4.3-bin.zip, commons-logging-1.2-bin.zip and copied it into C:\\>Apache folder." }, { "code": null, "e": 10286, "s": 10049, "text": "Set the APACHE_HOME environment variable to point to the base directory location where Apache jar is stored on your machine. Assuming, we've extracted commons-dbutils-1.7-bin.zip in Apache folder on various Operating Systems as follows." }, { "code": null, "e": 10477, "s": 10286, "text": "Set the CLASSPATH environment variable to point to the Common IO jar location. Assuming, you have stored commons-dbutils-1.7-bin.zip in Apache folder on various Operating Systems as follows." }, { "code": null, "e": 10596, "s": 10477, "text": "Now you are ready to start experimenting with DBUtils. Next chapter gives you a sample example on DBUtils Programming." }, { "code": null, "e": 10603, "s": 10596, "text": " Print" }, { "code": null, "e": 10614, "s": 10603, "text": " Add Notes" } ]
Extract all integers from string in C++ - GeeksforGeeks
19 Apr, 2022 Given a string, extract all integers words from it. Examples : Input : str = "geeksforgeeks 12 13 practice" Output : 12 13 Input : str = "1: Prakhar Agrawal, 2: Manish Kumar Rai, 3: Rishabh Gupta" Output : 1 2 3 Input : str = "Ankit sleeps at 4 am." Output : 4 The idea is to use stringstream:, objects of this class use a string buffer that contains a sequence of characters. Algorithm 1. Enter the whole string into stringstream. 2. Extract the all words from string using loop. 2. Check whether a word is integer or not. /* Extract all integers from string */#include <iostream>#include <sstream>using namespace std; void extractIntegerWords(string str){ stringstream ss; /* Storing the whole string into string stream */ ss << str; /* Running loop till the end of the stream */ string temp; int found; while (!ss.eof()) { /* extracting word by word from stream */ ss >> temp; /* Checking the given word is integer or not */ if (stringstream(temp) >> found) cout << found << " "; /* To save from space at the end of string */ temp = ""; }} // Driver codeint main(){ string str = "1: 2 3 4 prakhar"; extractIntegerWords(str); return 0;} Output: 1 2 3 4 Related Articles : Converting string to number and vice-versa in C++ Program to extract words from a given String Removing spaces from a string using Stringstream This article is contributed by Prakhar Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-string C++ Strings Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ List in C++ Standard Template Library (STL) Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string Python program to check if a string is palindrome or not
[ { "code": null, "e": 23733, "s": 23705, "text": "\n19 Apr, 2022" }, { "code": null, "e": 23785, "s": 23733, "text": "Given a string, extract all integers words from it." }, { "code": null, "e": 23796, "s": 23785, "text": "Examples :" }, { "code": null, "e": 23997, "s": 23796, "text": "Input : str = \"geeksforgeeks 12 13 practice\"\nOutput : 12 13\n\nInput : str = \"1: Prakhar Agrawal, 2: Manish Kumar Rai, 3: Rishabh Gupta\"\nOutput : 1 2 3\n\nInput : str = \"Ankit sleeps at 4 am.\"\nOutput : 4\n" }, { "code": null, "e": 24113, "s": 23997, "text": "The idea is to use stringstream:, objects of this class use a string buffer that contains a sequence of characters." }, { "code": null, "e": 24123, "s": 24113, "text": "Algorithm" }, { "code": null, "e": 24264, "s": 24123, "text": " 1. Enter the whole string into stringstream.\n 2. Extract the all words from string using loop.\n 2. Check whether a word is integer or not.\n" }, { "code": "/* Extract all integers from string */#include <iostream>#include <sstream>using namespace std; void extractIntegerWords(string str){ stringstream ss; /* Storing the whole string into string stream */ ss << str; /* Running loop till the end of the stream */ string temp; int found; while (!ss.eof()) { /* extracting word by word from stream */ ss >> temp; /* Checking the given word is integer or not */ if (stringstream(temp) >> found) cout << found << \" \"; /* To save from space at the end of string */ temp = \"\"; }} // Driver codeint main(){ string str = \"1: 2 3 4 prakhar\"; extractIntegerWords(str); return 0;}", "e": 24981, "s": 24264, "text": null }, { "code": null, "e": 24989, "s": 24981, "text": "Output:" }, { "code": null, "e": 25000, "s": 24989, "text": "\n1 2 3 4 \n" }, { "code": null, "e": 25019, "s": 25000, "text": "Related Articles :" }, { "code": null, "e": 25069, "s": 25019, "text": "Converting string to number and vice-versa in C++" }, { "code": null, "e": 25114, "s": 25069, "text": "Program to extract words from a given String" }, { "code": null, "e": 25163, "s": 25114, "text": "Removing spaces from a string using Stringstream" }, { "code": null, "e": 25466, "s": 25163, "text": "This article is contributed by Prakhar Agrawal. 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": 25591, "s": 25466, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25602, "s": 25591, "text": "cpp-string" }, { "code": null, "e": 25606, "s": 25602, "text": "C++" }, { "code": null, "e": 25614, "s": 25606, "text": "Strings" }, { "code": null, "e": 25622, "s": 25614, "text": "Strings" }, { "code": null, "e": 25626, "s": 25622, "text": "CPP" }, { "code": null, "e": 25724, "s": 25626, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25733, "s": 25724, "text": "Comments" }, { "code": null, "e": 25746, "s": 25733, "text": "Old Comments" }, { "code": null, "e": 25774, "s": 25746, "text": "Operator Overloading in C++" }, { "code": null, "e": 25798, "s": 25774, "text": "Sorting a vector in C++" }, { "code": null, "e": 25818, "s": 25798, "text": "Polymorphism in C++" }, { "code": null, "e": 25851, "s": 25818, "text": "Friend class and function in C++" }, { "code": null, "e": 25895, "s": 25851, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 25920, "s": 25895, "text": "Reverse a string in Java" }, { "code": null, "e": 25966, "s": 25920, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 26000, "s": 25966, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 26060, "s": 26000, "text": "Write a program to print all permutations of a given string" } ]
Find the highest moving (hidden) stocks of the day with Python | by Dorien Herremans | Towards Data Science
We will make use of a library called yfinance, that will provide us with historic stock data and import pandas. # imports!pip install yfinanceimport yfinance as yffrom pandas_datareader import data as pdrimport pandas as pd As we don’t just want to explore the most well known stock, we will load a complete list of all Nasdaq stocks: # list all stocksurl = “ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqlisted.txt"df=pd.read_csv(url, sep=”|”)print(df.head())print(df['Symbol'].head())print(len(df['Symbol'])) This has provided us with a variable (df) which contains 3,549 stock symbols! So how do we get the high movers of today? Let’s start by retrieving recent history for each stock in our list and storing it in movementlist I first define a helper function that will allow us to quickly lookup values from our dataframe with error checking. def lookup_fn(df, key_row, key_col): try: return df.iloc[key_row][key_col] except IndexError: return 0 I look back 5 days. You can change the time period in the command hist = thestock.history(period=”5d”) We populate the list of movement (stock symbol, low over the time period, high over the time period). movementlist = []for stock in df['Symbol']: # get history thestock = yf.Ticker(stock) hist = thestock.history(period="5d") # print(stock) low = float(10000) high = float(0) # print(thestock.info) for day in hist.itertuples(index=True, name='Pandas'): if day.Low < low: low = day.Low if high < day.High: high = day.High deltapercent = 100 * (high - low)/low Open = lookup_fn(hist, 0, "Open") # some error handling: if len(hist >=5): Close = lookup_fn(hist, 4, "Close") else : Close = Open if(Open == 0): deltaprice = 0 else: deltaprice = 100 * (Close - Open) / Open print(stock+" "+str(deltapercent)+ " "+ str(deltaprice)) pair = [stock, deltapercent, deltaprice] movementlist.append(pair) Now that we have populated our list of stock movement, we can move on to filtering out the highest movers. If you just want to get a quick list of those who moved more then 100%: for entry in movementlist: if entry[1]>float(100): print(entry) If we are interested in exploring some of these stocks a bit more in detail we’ll want some more info, like the sector they belong too. Here is how we properly clean up the list: # High risers:def lookup_stockinfo(thestock): try return thestock.info except IndexError: return 0cutoff=float(80)for entry in movementlist: if entry[2]>cutoff: print("\n"+ str(entry)) thestock = yf.Ticker(str(entry[0])) if entry[0]=='HJLIW': print("no info") else: a = lookup_stockinfo(thestock)if a == 0: print("no info") else: if a is None: print("no info") else: if a == "": print("no") else: print(a) print('Up '+ str(entry[2]) + "%") print(str(a['sector'])) print(str(a['longBusinessSummary'])) print("year high "+ str(a['fiftyTwoWeekHigh'])) The result is a detailied overview with some information on the highest movers of the last 5 days. Very interesting to detect some fast moving stocks for speculators or just for anyone wanting to find a hidden gem stock!
[ { "code": null, "e": 284, "s": 172, "text": "We will make use of a library called yfinance, that will provide us with historic stock data and import pandas." }, { "code": null, "e": 396, "s": 284, "text": "# imports!pip install yfinanceimport yfinance as yffrom pandas_datareader import data as pdrimport pandas as pd" }, { "code": null, "e": 507, "s": 396, "text": "As we don’t just want to explore the most well known stock, we will load a complete list of all Nasdaq stocks:" }, { "code": null, "e": 686, "s": 507, "text": "# list all stocksurl = “ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqlisted.txt\"df=pd.read_csv(url, sep=”|”)print(df.head())print(df['Symbol'].head())print(len(df['Symbol']))" }, { "code": null, "e": 764, "s": 686, "text": "This has provided us with a variable (df) which contains 3,549 stock symbols!" }, { "code": null, "e": 906, "s": 764, "text": "So how do we get the high movers of today? Let’s start by retrieving recent history for each stock in our list and storing it in movementlist" }, { "code": null, "e": 1023, "s": 906, "text": "I first define a helper function that will allow us to quickly lookup values from our dataframe with error checking." }, { "code": null, "e": 1126, "s": 1023, "text": "def lookup_fn(df, key_row, key_col): try: return df.iloc[key_row][key_col] except IndexError: return 0" }, { "code": null, "e": 1229, "s": 1126, "text": "I look back 5 days. You can change the time period in the command hist = thestock.history(period=”5d”)" }, { "code": null, "e": 1331, "s": 1229, "text": "We populate the list of movement (stock symbol, low over the time period, high over the time period)." }, { "code": null, "e": 2069, "s": 1331, "text": "movementlist = []for stock in df['Symbol']: # get history thestock = yf.Ticker(stock) hist = thestock.history(period=\"5d\") # print(stock) low = float(10000) high = float(0) # print(thestock.info) for day in hist.itertuples(index=True, name='Pandas'): if day.Low < low: low = day.Low if high < day.High: high = day.High deltapercent = 100 * (high - low)/low Open = lookup_fn(hist, 0, \"Open\") # some error handling: if len(hist >=5): Close = lookup_fn(hist, 4, \"Close\") else : Close = Open if(Open == 0): deltaprice = 0 else: deltaprice = 100 * (Close - Open) / Open print(stock+\" \"+str(deltapercent)+ \" \"+ str(deltaprice)) pair = [stock, deltapercent, deltaprice] movementlist.append(pair)" }, { "code": null, "e": 2248, "s": 2069, "text": "Now that we have populated our list of stock movement, we can move on to filtering out the highest movers. If you just want to get a quick list of those who moved more then 100%:" }, { "code": null, "e": 2316, "s": 2248, "text": "for entry in movementlist: if entry[1]>float(100): print(entry)" }, { "code": null, "e": 2495, "s": 2316, "text": "If we are interested in exploring some of these stocks a bit more in detail we’ll want some more info, like the sector they belong too. Here is how we properly clean up the list:" }, { "code": null, "e": 3194, "s": 2495, "text": "# High risers:def lookup_stockinfo(thestock): try return thestock.info except IndexError: return 0cutoff=float(80)for entry in movementlist: if entry[2]>cutoff: print(\"\\n\"+ str(entry)) thestock = yf.Ticker(str(entry[0])) if entry[0]=='HJLIW': print(\"no info\") else: a = lookup_stockinfo(thestock)if a == 0: print(\"no info\") else: if a is None: print(\"no info\") else: if a == \"\": print(\"no\") else: print(a) print('Up '+ str(entry[2]) + \"%\") print(str(a['sector'])) print(str(a['longBusinessSummary'])) print(\"year high \"+ str(a['fiftyTwoWeekHigh']))" } ]
Rename Root @ localhost username in MySQL?
The syntax is as follows to rename Root @localhost UPDATE MySQL.user SET user = ‘yourNewRootName’ WHERE user = 'root'; To understand the above concept, let us check all the user names and host. The query is as follows mysql> select user,host from MySQL.user; The following is the output +------------------+-----------+ | user | host | +------------------+-----------+ | Bob | % | | Manish | % | | User2 | % | | mysql.infoschema | % | | mysql.session | % | | mysql.sys | % | | root | % | | @UserName@ | localhost | | Adam Smith | localhost | | John | localhost | | John Doe | localhost | | User1 | localhost | | am | localhost | | hbstudent | localhost | | mysql.infoschema | localhost | | mysql.session | localhost | +------------------+-----------+ 16 rows in set (0.00 sec) The following is the query to rename the user ‘root’ to some other name mysql> UPDATE mysql.user set user = 'MyRoot' where user = 'root'; Query OK, 1 row affected (0.13 sec) Rows matched: 1 Changed: 1 Warnings: 0 Let us check the user ‘root’ has been updated with new name ‘MyRoot’ or not. The query is as follows mysql> select user,host from MySQL.user; The following is the output +------------------+-----------+ | user | host | +------------------+-----------+ | Bob | % | | Manish | % | | MyRoot | % | | User2 | % | | mysql.infoschema | % | | mysql.session | % | | mysql.sys | % | | @UserName@ | localhost | | Adam Smith | localhost | | John | localhost | | John Doe | localhost | | User1 | localhost | | am | localhost | | hbstudent | localhost | | mysql.infoschema | localhost | | mysql.session | localhost | +------------------+-----------+ 16 rows in set (0.00 sec) Look at the sample output, the root has been updated with new name “MyRoot” successfully.
[ { "code": null, "e": 1113, "s": 1062, "text": "The syntax is as follows to rename Root @localhost" }, { "code": null, "e": 1181, "s": 1113, "text": "UPDATE MySQL.user SET user = ‘yourNewRootName’ WHERE user = 'root';" }, { "code": null, "e": 1280, "s": 1181, "text": "To understand the above concept, let us check all the user names and host. The query is as follows" }, { "code": null, "e": 1321, "s": 1280, "text": "mysql> select user,host from MySQL.user;" }, { "code": null, "e": 1349, "s": 1321, "text": "The following is the output" }, { "code": null, "e": 2036, "s": 1349, "text": "+------------------+-----------+\n| user | host |\n+------------------+-----------+\n| Bob | % |\n| Manish | % |\n| User2 | % | \n| mysql.infoschema | % |\n| mysql.session | % |\n| mysql.sys | % |\n| root | % |\n| @UserName@ | localhost |\n| Adam Smith | localhost |\n| John | localhost |\n| John Doe | localhost |\n| User1 | localhost |\n| am | localhost |\n| hbstudent | localhost |\n| mysql.infoschema | localhost |\n| mysql.session | localhost |\n+------------------+-----------+\n16 rows in set (0.00 sec)" }, { "code": null, "e": 2108, "s": 2036, "text": "The following is the query to rename the user ‘root’ to some other name" }, { "code": null, "e": 2249, "s": 2108, "text": "mysql> UPDATE mysql.user set user = 'MyRoot' where user = 'root';\nQuery OK, 1 row affected (0.13 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 2350, "s": 2249, "text": "Let us check the user ‘root’ has been updated with new name ‘MyRoot’ or not. The query is as follows" }, { "code": null, "e": 2391, "s": 2350, "text": "mysql> select user,host from MySQL.user;" }, { "code": null, "e": 2419, "s": 2391, "text": "The following is the output" }, { "code": null, "e": 3108, "s": 2419, "text": "+------------------+-----------+\n| user | host |\n+------------------+-----------+\n| Bob | % |\n| Manish | % |\n| MyRoot | % | \n| User2 | % |\n| mysql.infoschema | % |\n| mysql.session | % |\n| mysql.sys | % |\n| @UserName@ | localhost |\n| Adam Smith | localhost |\n| John | localhost |\n| John Doe | localhost |\n| User1 | localhost |\n| am | localhost |\n| hbstudent | localhost |\n| mysql.infoschema | localhost |\n| mysql.session | localhost |\n+------------------+-----------+\n16 rows in set (0.00 sec)" }, { "code": null, "e": 3198, "s": 3108, "text": "Look at the sample output, the root has been updated with new name “MyRoot” successfully." } ]
How to clear console in C?
There are several methods to clear the console or output screen and one of them is clrscr() function. It clears the screen as function invokes. It is declared in “conio.h” header file. There are some other methods too like system(“cls”) and system(“clear”) and these are declared in “stdlib.h” header file. Here is the syntax to clear the console in C language, clrscr(); OR system(“cls”); OR system(“clear”); Here is an example to clear the console in C language, Let’s say we have “new.txt” file with the following content − 0,hell!o 1,hello! 2,gfdtrhtrhrt 3,demo Now, let us see the example. #include<stdio.h> #include<conio.h> void main() { FILE *f; char s; clrscr(); f=fopen("new.txt","r"); while((s=fgetc(f))!=EOF) { printf("%c",s); } fclose(f); getch(); } 0,hell!o 1,hello! 2,gfdtrhtrhrt 3,demo In the above program, we have a text file “new.txt”. A file pointer is used to open and read the file. It is displaying the content of file. To clear the console, clrscr() is used. clrscr(); f=fopen("new.txt","r"); while((s=fgetc(f))!=EOF) { printf("%c",s); }
[ { "code": null, "e": 1369, "s": 1062, "text": "There are several methods to clear the console or output screen and one of them is clrscr() function. It clears the screen as function invokes. It is declared in “conio.h” header file. There are some other methods too like system(“cls”) and system(“clear”) and these are declared in “stdlib.h” header file." }, { "code": null, "e": 1424, "s": 1369, "text": "Here is the syntax to clear the console in C language," }, { "code": null, "e": 1472, "s": 1424, "text": "clrscr();\nOR\nsystem(“cls”);\nOR\nsystem(“clear”);" }, { "code": null, "e": 1527, "s": 1472, "text": "Here is an example to clear the console in C language," }, { "code": null, "e": 1589, "s": 1527, "text": "Let’s say we have “new.txt” file with the following content −" }, { "code": null, "e": 1628, "s": 1589, "text": "0,hell!o\n1,hello!\n2,gfdtrhtrhrt\n3,demo" }, { "code": null, "e": 1657, "s": 1628, "text": "Now, let us see the example." }, { "code": null, "e": 1855, "s": 1657, "text": "#include<stdio.h>\n#include<conio.h>\nvoid main() {\n FILE *f;\n char s;\n clrscr();\n f=fopen(\"new.txt\",\"r\");\n while((s=fgetc(f))!=EOF) {\n printf(\"%c\",s);\n }\n fclose(f);\n getch();\n}" }, { "code": null, "e": 1894, "s": 1855, "text": "0,hell!o\n1,hello!\n2,gfdtrhtrhrt\n3,demo" }, { "code": null, "e": 2075, "s": 1894, "text": "In the above program, we have a text file “new.txt”. A file pointer is used to open and read the file. It is displaying the content of file. To clear the console, clrscr() is used." }, { "code": null, "e": 2157, "s": 2075, "text": "clrscr();\nf=fopen(\"new.txt\",\"r\");\nwhile((s=fgetc(f))!=EOF) {\n printf(\"%c\",s);\n}" } ]
10 Interesting Python Cool Tricks
With increase in popularity of python, more and more features are becoming available for python coding. Using this features makes writing the code in fewer lines and cleaner. In this article we will see 10 such python tricks which are very frequently used and most useful. We can simply reverse a given list by using a reverse() function. It handles both numeric and string data types present in the list. List = ["Shriya", "Lavina","Sampreeti" ] List.reverse() print(List) Running the above code gives us the following result − ['Sampreeti', 'Lavina', 'Shriya'] If you need to print the values of a list in different orders, you can assign the list to a series of variables and programmatically decide the order in which you want to print the list. List = [1,2,3] w, v, t = List print(v, w, t ) print(t, v, w ) Running the above code gives us the following result − (2, 1, 3) (3, 2, 1) We can use generators directly inside a function to writer shorter and cleaner code. In the below example we find the sum using a generator directly as an argument to the sum function. sum(i for i in range(10) ) Running the above code gives us the following result − 45 When we need to join many iterator objects like lists to get a single list we can use the zip function. The result shows each item to be grouped with their respective items from the other lists. Year = (1999, 2003, 2011, 2017) Month = ("Mar", "Jun", "Jan", "Dec") Day = (11,21,13,5) print zip(Year,Month,Day) Running the above code gives us the following result − [(1999, 'Mar', 11), (2003, 'Jun', 21), (2011, 'Jan', 13), (2017, 'Dec', 5)] Swapping of numbers usually requires storing of values in temporary variables. But with this python trick we can do that using one line of code and without using any temporary variables. x,y = 11, 34 print x print y x,y = y,x print x print y Running the above code gives us the following result − 11 34 34 11 Transposing a matrix involves converting columns into rows. In python we can achieve it by designing some loop structure to iterate through the elements in the matrix and change their places or we can use the following script involving zip function in conjunction with the * operator to unzip a list which becomes a transpose of the given matrix. x = [[31,17], [40 ,51], [13 ,12]] print (zip(*x)) Running the above code gives us the following result − [(31, 40, 13), (17, 51, 12)] The usual approach in any programming language to print a string multiple times is to design a loop. But python has a simple trick involving a string and a number inside the print function. str ="Point"; print(str * 3); Running the above code gives us the following result − PointPointPoint List slicing is a very powerful technique in python which can also be used to reverse the order of elements in a list. #Reversing Strings list1 = ["a","b","c","d"] print list1[::-1] # Reversing Numbers list2 = [1,3,6,4,2] print list2[::-1] Running the above code gives us the following result − ['d', 'c', 'b', 'a'] [2, 4, 6, 3, 1] When we are need of the factors of a number, required for some calculation or analysis, we can design a small loop which will check the divisibility of that number with the iteration index. f = 32 print "The factors of",x,"are:" for i in range(1, f + 1): if f % i == 0: print(i) Running the above code gives us the following result − The factors of 32 are: 1 2 4 8 16 32 We can check the amount of memory consumed by each variable that we declare by using the getsizeof() function. As you can see below, different string lengths will consume different amount of memory. import sys a, b, c,d = "abcde" ,"xy", 2, 15.06 print(sys.getsizeof(a)) print(sys.getsizeof(b)) print(sys.getsizeof(c)) print(sys.getsizeof(d)) Running the above code gives us the following result − 38 35 24 24
[ { "code": null, "e": 1335, "s": 1062, "text": "With increase in popularity of python, more and more features are becoming available for python coding. Using this features makes writing the code in fewer lines and cleaner. In this article we will see 10 such python tricks which are very frequently used and most useful." }, { "code": null, "e": 1468, "s": 1335, "text": "We can simply reverse a given list by using a reverse() function. It handles both numeric and string data types present in the list." }, { "code": null, "e": 1536, "s": 1468, "text": "List = [\"Shriya\", \"Lavina\",\"Sampreeti\" ]\nList.reverse()\nprint(List)" }, { "code": null, "e": 1591, "s": 1536, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1625, "s": 1591, "text": "['Sampreeti', 'Lavina', 'Shriya']" }, { "code": null, "e": 1812, "s": 1625, "text": "If you need to print the values of a list in different orders, you can assign the list to a series of variables and programmatically decide the order in which you want to print the list." }, { "code": null, "e": 1874, "s": 1812, "text": "List = [1,2,3]\nw, v, t = List\nprint(v, w, t )\nprint(t, v, w )" }, { "code": null, "e": 1929, "s": 1874, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1949, "s": 1929, "text": "(2, 1, 3)\n(3, 2, 1)" }, { "code": null, "e": 2134, "s": 1949, "text": "We can use generators directly inside a function to writer shorter and cleaner code. In the below example we find the sum using a generator directly as an argument to the sum function." }, { "code": null, "e": 2161, "s": 2134, "text": "sum(i for i in range(10) )" }, { "code": null, "e": 2216, "s": 2161, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2219, "s": 2216, "text": "45" }, { "code": null, "e": 2414, "s": 2219, "text": "When we need to join many iterator objects like lists to get a single list we can use the zip function. The result shows each item to be grouped with their respective items from the other lists." }, { "code": null, "e": 2528, "s": 2414, "text": "Year = (1999, 2003, 2011, 2017)\nMonth = (\"Mar\", \"Jun\", \"Jan\", \"Dec\")\nDay = (11,21,13,5)\nprint zip(Year,Month,Day)" }, { "code": null, "e": 2583, "s": 2528, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2659, "s": 2583, "text": "[(1999, 'Mar', 11), (2003, 'Jun', 21), (2011, 'Jan', 13), (2017, 'Dec', 5)]" }, { "code": null, "e": 2846, "s": 2659, "text": "Swapping of numbers usually requires storing of values in temporary variables. But with this python trick we can do that using one line of code and without using any temporary variables." }, { "code": null, "e": 2901, "s": 2846, "text": "x,y = 11, 34\nprint x\nprint y\nx,y = y,x\nprint x\nprint y" }, { "code": null, "e": 2956, "s": 2901, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2968, "s": 2956, "text": "11\n34\n34\n11" }, { "code": null, "e": 3315, "s": 2968, "text": "Transposing a matrix involves converting columns into rows. In python we can achieve it by designing some loop structure to iterate through the elements in the matrix and change their places or we can use the following script involving zip function in conjunction with the * operator to unzip a list which becomes a transpose of the given matrix." }, { "code": null, "e": 3365, "s": 3315, "text": "x = [[31,17],\n[40 ,51],\n[13 ,12]]\nprint (zip(*x))" }, { "code": null, "e": 3420, "s": 3365, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3449, "s": 3420, "text": "[(31, 40, 13), (17, 51, 12)]" }, { "code": null, "e": 3639, "s": 3449, "text": "The usual approach in any programming language to print a string multiple times is to design a loop. But python has a simple trick involving a string and a number inside the print function." }, { "code": null, "e": 3669, "s": 3639, "text": "str =\"Point\";\nprint(str * 3);" }, { "code": null, "e": 3724, "s": 3669, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3740, "s": 3724, "text": "PointPointPoint" }, { "code": null, "e": 3859, "s": 3740, "text": "List slicing is a very powerful technique in python which can also be used to reverse the order of elements in a list." }, { "code": null, "e": 3981, "s": 3859, "text": "#Reversing Strings\nlist1 = [\"a\",\"b\",\"c\",\"d\"]\nprint list1[::-1]\n\n# Reversing Numbers\nlist2 = [1,3,6,4,2]\nprint list2[::-1]" }, { "code": null, "e": 4036, "s": 3981, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 4073, "s": 4036, "text": "['d', 'c', 'b', 'a']\n[2, 4, 6, 3, 1]" }, { "code": null, "e": 4263, "s": 4073, "text": "When we are need of the factors of a number, required for some calculation or analysis, we can design a small loop which will check the divisibility of that number with the iteration index." }, { "code": null, "e": 4355, "s": 4263, "text": "f = 32\nprint \"The factors of\",x,\"are:\"\nfor i in range(1, f + 1):\n if f % i == 0:\nprint(i)" }, { "code": null, "e": 4410, "s": 4355, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 4447, "s": 4410, "text": "The factors of 32 are:\n1\n2\n4\n8\n16\n32" }, { "code": null, "e": 4646, "s": 4447, "text": "We can check the amount of memory consumed by each variable that we declare by using the getsizeof() function. As you can see below, different string lengths will consume different amount of memory." }, { "code": null, "e": 4789, "s": 4646, "text": "import sys\na, b, c,d = \"abcde\" ,\"xy\", 2, 15.06\nprint(sys.getsizeof(a))\nprint(sys.getsizeof(b))\nprint(sys.getsizeof(c))\nprint(sys.getsizeof(d))" }, { "code": null, "e": 4844, "s": 4789, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 4856, "s": 4844, "text": "38\n35\n24\n24" } ]
Node.js fs.closeSync() Method - GeeksforGeeks
08 Oct, 2021 The fs.closeSync() method is used to synchronously close the given file descriptor thereby clearing the file that is associated with it. It allows the file descriptor to be reused for other files. Calling fs.closeSync() on a file descriptor while some other operation is being performed on it may lead to undefined behavior. Syntax: fs.closeSync( fd ) Parameters: This method accepts single parameter as mentioned above and described below: fd: It is an integer which denotes the file descriptor of the file of which to be closed. Below examples illustrate the fs.closeSync() method in Node.js: Example 1: This example shows the closing of a file descriptor. // Node.js program to demonstrate the// fs.closeSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the file descriptor of the given pathfile_descriptor = fs.openSync("example.txt");console.log("The file descriptor is:", file_descriptor); // Close the file descriptortry { fs.closeSync(file_descriptor); console.log("\n> File Closed successfully");} catch (err) { console.error('Failed to close file');} Output: The file descriptor is: 3 > File Closed successfully Example 2: This example shows the closing of a file descriptor and trying to access the closed file descriptor again. // Node.js program to demonstrate the// fs.closeSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the file descriptor of the given pathfile_descriptor = fs.openSync("example.txt");console.log("The file descriptor is:", file_descriptor); // Attempting to get stats before closingconsole.log("\n> Finding the stats of the file");try { statsObj = fs.fstatSync(file_descriptor); console.log("Stats of the file generated");} catch (err) { console.error('Cannot find stats of file', err);} // Close the file descriptortry { fs.closeSync(file_descriptor); console.log("\n> File Closed successfully");} catch (err) { console.error('Failed to close file', err);} // Attempting to find stats after closingconsole.log("\n> Finding the stats of the file again");try { statsObj = fs.fstatSync(file_descriptor); console.log("Stats of the file generated");} catch (err) { console.error('Cannot find stats of file', err);} Output: The file descriptor is: 3 > Finding the stats of the file Stats of the file generated > File Closed successfully > Finding the stats of the file again Cannot find stats of file Error: EBADF: bad file descriptor, fstat at Object.fstatSync (fs.js:897:3) at Object. (G:\tutorials\nodejs-fs-closeSync\index.js:46:17) at Module._compile (internal/modules/cjs/loader.js:956:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10) at Module.load (internal/modules/cjs/loader.js:812:32) at Function.Module._load (internal/modules/cjs/loader.js:724:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10) at internal/main/run_main_module.js:17:11 { fd: 3, errno: -4083, syscall: 'fstat', code: 'EBADF' } Reference: https://nodejs.org/api/fs.html#fs_fs_closesync_fd Node.js-fs-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Express.js express.Router() Function JWT Authentication with Node.js Express.js req.params Property Mongoose Populate() Method How to build a basic CRUD app with Node.js and ReactJS ? Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 25002, "s": 24974, "text": "\n08 Oct, 2021" }, { "code": null, "e": 25327, "s": 25002, "text": "The fs.closeSync() method is used to synchronously close the given file descriptor thereby clearing the file that is associated with it. It allows the file descriptor to be reused for other files. Calling fs.closeSync() on a file descriptor while some other operation is being performed on it may lead to undefined behavior." }, { "code": null, "e": 25335, "s": 25327, "text": "Syntax:" }, { "code": null, "e": 25354, "s": 25335, "text": "fs.closeSync( fd )" }, { "code": null, "e": 25443, "s": 25354, "text": "Parameters: This method accepts single parameter as mentioned above and described below:" }, { "code": null, "e": 25533, "s": 25443, "text": "fd: It is an integer which denotes the file descriptor of the file of which to be closed." }, { "code": null, "e": 25597, "s": 25533, "text": "Below examples illustrate the fs.closeSync() method in Node.js:" }, { "code": null, "e": 25661, "s": 25597, "text": "Example 1: This example shows the closing of a file descriptor." }, { "code": "// Node.js program to demonstrate the// fs.closeSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the file descriptor of the given pathfile_descriptor = fs.openSync(\"example.txt\");console.log(\"The file descriptor is:\", file_descriptor); // Close the file descriptortry { fs.closeSync(file_descriptor); console.log(\"\\n> File Closed successfully\");} catch (err) { console.error('Failed to close file');}", "e": 26097, "s": 25661, "text": null }, { "code": null, "e": 26105, "s": 26097, "text": "Output:" }, { "code": null, "e": 26159, "s": 26105, "text": "The file descriptor is: 3\n\n> File Closed successfully" }, { "code": null, "e": 26277, "s": 26159, "text": "Example 2: This example shows the closing of a file descriptor and trying to access the closed file descriptor again." }, { "code": "// Node.js program to demonstrate the// fs.closeSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the file descriptor of the given pathfile_descriptor = fs.openSync(\"example.txt\");console.log(\"The file descriptor is:\", file_descriptor); // Attempting to get stats before closingconsole.log(\"\\n> Finding the stats of the file\");try { statsObj = fs.fstatSync(file_descriptor); console.log(\"Stats of the file generated\");} catch (err) { console.error('Cannot find stats of file', err);} // Close the file descriptortry { fs.closeSync(file_descriptor); console.log(\"\\n> File Closed successfully\");} catch (err) { console.error('Failed to close file', err);} // Attempting to find stats after closingconsole.log(\"\\n> Finding the stats of the file again\");try { statsObj = fs.fstatSync(file_descriptor); console.log(\"Stats of the file generated\");} catch (err) { console.error('Cannot find stats of file', err);}", "e": 27226, "s": 26277, "text": null }, { "code": null, "e": 27234, "s": 27226, "text": "Output:" }, { "code": null, "e": 28009, "s": 27234, "text": "The file descriptor is: 3\n\n> Finding the stats of the file\nStats of the file generated\n\n> File Closed successfully\n\n> Finding the stats of the file again\nCannot find stats of file Error: EBADF: bad file descriptor, fstat\n at Object.fstatSync (fs.js:897:3)\n at Object. (G:\\tutorials\\nodejs-fs-closeSync\\index.js:46:17)\n at Module._compile (internal/modules/cjs/loader.js:956:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)\n at Module.load (internal/modules/cjs/loader.js:812:32)\n at Function.Module._load (internal/modules/cjs/loader.js:724:14)\n at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)\n at internal/main/run_main_module.js:17:11 {\n fd: 3,\n errno: -4083,\n syscall: 'fstat',\n code: 'EBADF'\n}" }, { "code": null, "e": 28070, "s": 28009, "text": "Reference: https://nodejs.org/api/fs.html#fs_fs_closesync_fd" }, { "code": null, "e": 28088, "s": 28070, "text": "Node.js-fs-module" }, { "code": null, "e": 28096, "s": 28088, "text": "Node.js" }, { "code": null, "e": 28113, "s": 28096, "text": "Web Technologies" }, { "code": null, "e": 28211, "s": 28113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28248, "s": 28211, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28280, "s": 28248, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 28311, "s": 28280, "text": "Express.js req.params Property" }, { "code": null, "e": 28338, "s": 28311, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28395, "s": 28338, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 28437, "s": 28395, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28480, "s": 28437, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28542, "s": 28480, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28592, "s": 28542, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
What are the inserting elements in queue in C language?
Data structure is collection of data organized in a structured way. It is divided into two types as explained below − Linear data structure − Data is organized in a linear fashion. For example, arrays, structures, stacks, queues, linked lists. Linear data structure − Data is organized in a linear fashion. For example, arrays, structures, stacks, queues, linked lists. Nonlinear data structure − Data is organized in a hierarchical way. For example, Trees, graphs, sets, tables. Nonlinear data structure − Data is organized in a hierarchical way. For example, Trees, graphs, sets, tables. It is a linear data structure, where the insertion is done at rear end and the deletion is done at the front end. The order of queue is FIFO – First In First Out Insert – Inserting an element into a queue. Delete – Deleting an element from the queue. Queue over flow − Trying to insert an element into a full queue. Queue over flow − Trying to insert an element into a full queue. Queue under flow − Trying to delete an element from an empty queue. Queue under flow − Trying to delete an element from an empty queue. Given below is an algorithm for insertion ( ) − Check for queue overflow. if (r==n) printf ("Queue overflow") Otherwise, insert an element in to the queue. q[r] = item r++ Following is the C program for inserting the elements in queue − #include <stdio.h> #define MAX 50 void insert(); int array[MAX]; int rear = - 1; int front = - 1; main(){ int add_item; int choice; while (1){ printf("1.Insert element to queue \n"); printf("2.Display elements of queue \n"); printf("3.Quit \n"); printf("Enter your choice : "); scanf("%d", &choice); switch (choice){ case 1: insert(); break; case 2: display(); break; case 3: exit(1); default: printf("Wrong choice \n"); } } } void insert(){ int add_item; if (rear == MAX - 1) printf("Queue Overflow \n"); else{ if (front == - 1) /*If queue is initially empty */ front = 0; printf("Inset the element in queue : "); scanf("%d", &add_item); rear = rear + 1; array[rear] = add_item; } } void display(){ int i; if (front == - 1) printf("Queue is empty \n"); else{ printf("Queue is : \n"); for (i = front; i <= rear; i++) printf("%d ", array[i]); printf("\n"); } } When the above program is executed, it produces the following result − 1.Insert element to queue 2.Display elements of queue 3.Quit Enter your choice: 1 Inset the element in queue: 34 1.Insert element to queue 2.Display elements of queue 3.Quit Enter your choice: 1 Inset the element in queue: 24 1.Insert element to queue 2.Display elements of queue 3.Quit Enter your choice: 2 Queue is: 34 24 1.Insert element to queue 2.Display elements of queue 3.Quit Enter your choice: 3
[ { "code": null, "e": 1180, "s": 1062, "text": "Data structure is collection of data organized in a structured way. It is divided into two types as explained below −" }, { "code": null, "e": 1306, "s": 1180, "text": "Linear data structure − Data is organized in a linear fashion. For example, arrays, structures, stacks, queues, linked lists." }, { "code": null, "e": 1432, "s": 1306, "text": "Linear data structure − Data is organized in a linear fashion. For example, arrays, structures, stacks, queues, linked lists." }, { "code": null, "e": 1542, "s": 1432, "text": "Nonlinear data structure − Data is organized in a hierarchical way. For example, Trees, graphs, sets, tables." }, { "code": null, "e": 1652, "s": 1542, "text": "Nonlinear data structure − Data is organized in a hierarchical way. For example, Trees, graphs, sets, tables." }, { "code": null, "e": 1766, "s": 1652, "text": "It is a linear data structure, where the insertion is done at rear end and the deletion is done at the front end." }, { "code": null, "e": 1814, "s": 1766, "text": "The order of queue is FIFO – First In First Out" }, { "code": null, "e": 1858, "s": 1814, "text": "Insert – Inserting an element into a queue." }, { "code": null, "e": 1903, "s": 1858, "text": "Delete – Deleting an element from the queue." }, { "code": null, "e": 1968, "s": 1903, "text": "Queue over flow − Trying to insert an element into a full queue." }, { "code": null, "e": 2033, "s": 1968, "text": "Queue over flow − Trying to insert an element into a full queue." }, { "code": null, "e": 2101, "s": 2033, "text": "Queue under flow − Trying to delete an element from an empty queue." }, { "code": null, "e": 2169, "s": 2101, "text": "Queue under flow − Trying to delete an element from an empty queue." }, { "code": null, "e": 2217, "s": 2169, "text": "Given below is an algorithm for insertion ( ) −" }, { "code": null, "e": 2243, "s": 2217, "text": "Check for queue overflow." }, { "code": null, "e": 2279, "s": 2243, "text": "if (r==n)\nprintf (\"Queue overflow\")" }, { "code": null, "e": 2325, "s": 2279, "text": "Otherwise, insert an element in to the queue." }, { "code": null, "e": 2341, "s": 2325, "text": "q[r] = item\nr++" }, { "code": null, "e": 2406, "s": 2341, "text": "Following is the C program for inserting the elements in queue −" }, { "code": null, "e": 3545, "s": 2406, "text": "#include <stdio.h>\n#define MAX 50\nvoid insert();\nint array[MAX];\nint rear = - 1;\nint front = - 1;\nmain(){\n int add_item;\n int choice;\n while (1){\n printf(\"1.Insert element to queue \\n\");\n printf(\"2.Display elements of queue \\n\");\n printf(\"3.Quit \\n\");\n printf(\"Enter your choice : \");\n scanf(\"%d\", &choice);\n switch (choice){\n case 1:\n insert();\n break;\n case 2:\n display();\n break;\n case 3:\n exit(1);\n default:\n printf(\"Wrong choice \\n\");\n }\n }\n}\nvoid insert(){\n int add_item;\n if (rear == MAX - 1)\n printf(\"Queue Overflow \\n\");\n else{\n if (front == - 1)\n /*If queue is initially empty */\n front = 0;\n printf(\"Inset the element in queue : \");\n scanf(\"%d\", &add_item);\n rear = rear + 1;\n array[rear] = add_item;\n }\n}\nvoid display(){\n int i;\n if (front == - 1)\n printf(\"Queue is empty \\n\");\n else{\n printf(\"Queue is : \\n\");\n for (i = front; i <= rear; i++)\n printf(\"%d \", array[i]);\n printf(\"\\n\");\n }\n}" }, { "code": null, "e": 3616, "s": 3545, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 4022, "s": 3616, "text": "1.Insert element to queue\n2.Display elements of queue\n3.Quit\nEnter your choice: 1\nInset the element in queue: 34\n1.Insert element to queue\n2.Display elements of queue\n3.Quit\nEnter your choice: 1\nInset the element in queue: 24\n1.Insert element to queue\n2.Display elements of queue\n3.Quit\nEnter your choice: 2\nQueue is:\n34 24\n1.Insert element to queue\n2.Display elements of queue\n3.Quit\nEnter your choice: 3" } ]
Counting Bits in Python
Suppose we have a non-negative integer number num. For each number i in the range 0 ≤ i ≤ num we have to calculate the number of 1's in their binary counterpart and return them as a list. So if the number is 5, then the numbers are [0, 1, 2, 3, 4, 5], and number of 1s in these numbers are [0, 1, 1, 2, 1, 2] To solve this, we will follow these steps − res := an array which holds num + 1 number of 0s offset := 0 for i in range 1 to num + 1if i and i – 1 = 0, then res[i] := 1 and offset := 0else increase offset by 1 and res[i] := 1 + res[offset] if i and i – 1 = 0, then res[i] := 1 and offset := 0 else increase offset by 1 and res[i] := 1 + res[offset] return res Let us see the following implementation to get a better understanding − Live Demo class Solution: def countBits(self, num): result = [0] * (num+1) offset = 0 for i in range(1,num+1): if i & i-1 == 0: result[i] = 1 offset = 0 else: offset+=1 result[i] = 1 + result[offset] return result ob1 = Solution() print(ob1.countBits(6)) 6 [0, 1, 1, 2, 1, 2, 2]
[ { "code": null, "e": 1371, "s": 1062, "text": "Suppose we have a non-negative integer number num. For each number i in the range 0 ≤ i ≤ num we have to calculate the number of 1's in their binary counterpart and return them as a list. So if the number is 5, then the numbers are [0, 1, 2, 3, 4, 5], and number of 1s in these numbers are [0, 1, 1, 2, 1, 2]" }, { "code": null, "e": 1415, "s": 1371, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1464, "s": 1415, "text": "res := an array which holds num + 1 number of 0s" }, { "code": null, "e": 1476, "s": 1464, "text": "offset := 0" }, { "code": null, "e": 1611, "s": 1476, "text": "for i in range 1 to num + 1if i and i – 1 = 0, then res[i] := 1 and offset := 0else increase offset by 1 and res[i] := 1 + res[offset]" }, { "code": null, "e": 1664, "s": 1611, "text": "if i and i – 1 = 0, then res[i] := 1 and offset := 0" }, { "code": null, "e": 1720, "s": 1664, "text": "else increase offset by 1 and res[i] := 1 + res[offset]" }, { "code": null, "e": 1731, "s": 1720, "text": "return res" }, { "code": null, "e": 1803, "s": 1731, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 1814, "s": 1803, "text": " Live Demo" }, { "code": null, "e": 2152, "s": 1814, "text": "class Solution:\n def countBits(self, num):\n result = [0] * (num+1)\n offset = 0\n for i in range(1,num+1):\n if i & i-1 == 0:\n result[i] = 1\n offset = 0\n else:\n offset+=1\n result[i] = 1 + result[offset]\n return result\nob1 = Solution()\nprint(ob1.countBits(6))" }, { "code": null, "e": 2154, "s": 2152, "text": "6" }, { "code": null, "e": 2176, "s": 2154, "text": "[0, 1, 1, 2, 1, 2, 2]" } ]
Get Synchronized List from ArrayList in java
In order to get a synchronized list from an ArrayList, we use the synchronizedList(List <T>) method in Java. The Collections.synchronizedList(List <T>) method accepts the ArrayList as an argument and returns a thread safe list. Declaration −The Collections.synchronizedList(List <T>) method is declared as follows − public static List <T> synchronizedList(List <T> list) Let us see a program to get a synchronized List from ArrayList − Live Demo import java.util.*; public class Example { public static void main (String[] args) { List<String> list = new ArrayList<String>(); list.add("Hello"); list.add("Hi"); list.add("World"); list = Collections.synchronizedList(list); synchronized(list) { Iterator itr = list.iterator(); while (itr.hasNext()) System.out.print(itr.next()+" "); } } } Hello Hi World
[ { "code": null, "e": 1290, "s": 1062, "text": "In order to get a synchronized list from an ArrayList, we use the synchronizedList(List <T>) method in Java. The Collections.synchronizedList(List <T>) method accepts the ArrayList as an argument and returns a thread safe list." }, { "code": null, "e": 1378, "s": 1290, "text": "Declaration −The Collections.synchronizedList(List <T>) method is declared as follows −" }, { "code": null, "e": 1433, "s": 1378, "text": "public static List <T> synchronizedList(List <T> list)" }, { "code": null, "e": 1498, "s": 1433, "text": "Let us see a program to get a synchronized List from ArrayList −" }, { "code": null, "e": 1509, "s": 1498, "text": " Live Demo" }, { "code": null, "e": 1926, "s": 1509, "text": "import java.util.*;\npublic class Example {\n public static void main (String[] args) {\n List<String> list = new ArrayList<String>();\n list.add(\"Hello\");\n list.add(\"Hi\");\n list.add(\"World\");\n list = Collections.synchronizedList(list);\n synchronized(list) {\n Iterator itr = list.iterator();\n while (itr.hasNext())\n System.out.print(itr.next()+\" \");\n }\n }\n}" }, { "code": null, "e": 1941, "s": 1926, "text": "Hello Hi World" } ]
Segregate 0’s and 1’s in an array list using Python?
List Comprehension is a popular technique in Python. Here we use this technique. We create a user input array and array element should be 0’s and 1’s in random order. Then segregate 0’s on left side and 1’s on right side. We traverse the array and separate two different list, one contains 0’s and another contains 1’s, then concatenate two list. Input:: a=[0,1,1,0,0,1] Output::[0,0,0,1,1,1] seg0s1s(A) /* A is the user input Array and the element of A should be the combination of 0’s and 1’s */ Step 1: First traverse the array. Step 2: Then check every element of the Array. If the element is 0, then its position is left side and if 1 then it is on the right side of the array. Step 3: Then concatenate two list. # Segregate 0's and 1's in an array list def seg0s1s(A): n = ([i for i in A if i==0] + [i for i in A if i==1]) print(n) # Driver program if __name__ == "__main__": A=list() n=int(input("Enter the size of the array ::")) print("Enter the number ::") for i in range(int(n)): k=int(input("")) A.append(int(k)) print("The New ArrayList ::") seg0s1s(A) Enter the size of the array ::6 Enter the number :: 1 0 0 1 1 0 The New ArrayList :: [0, 0, 0, 1, 1, 1]
[ { "code": null, "e": 1409, "s": 1062, "text": "List Comprehension is a popular technique in Python. Here we use this technique. We create a user input array and array element should be 0’s and 1’s in random order. Then segregate 0’s on left side and 1’s on right side. We traverse the array and separate two different list, one contains 0’s and another contains 1’s, then concatenate two list." }, { "code": null, "e": 1456, "s": 1409, "text": "Input:: a=[0,1,1,0,0,1]\nOutput::[0,0,0,1,1,1]\n" }, { "code": null, "e": 1782, "s": 1456, "text": "seg0s1s(A)\n/* A is the user input Array and the element of A should be the combination of 0’s and 1’s */\nStep 1: First traverse the array.\nStep 2: Then check every element of the Array. If the element is 0, then its position is left side and if 1 then it is on the right side of the array.\nStep 3: Then concatenate two list.\n" }, { "code": null, "e": 2172, "s": 1782, "text": "# Segregate 0's and 1's in an array list\ndef seg0s1s(A):\n n = ([i for i in A if i==0] + [i for i in A if i==1])\n print(n)\n\n# Driver program\nif __name__ == \"__main__\":\n A=list()\n n=int(input(\"Enter the size of the array ::\"))\n print(\"Enter the number ::\")\n for i in range(int(n)):\n k=int(input(\"\"))\n A.append(int(k))\n print(\"The New ArrayList ::\") \n seg0s1s(A)" }, { "code": null, "e": 2277, "s": 2172, "text": "Enter the size of the array ::6\nEnter the number ::\n1\n0\n0\n1\n1\n0\nThe New ArrayList ::\n[0, 0, 0, 1, 1, 1]\n" } ]
FreeGames module in Python - GeeksforGeeks
26 Jul, 2021 Python provides you free games and it’s is very easy and simple to get them and you can run it on you computer. So, are you curious about how you can get them? Just follow these simple steps: Step #1: Go to command prompt and type the following commandpython -m pip install freegames python -m pip install freegames Wait until the installation process gets finished After the process gets finished, you are ready to go. Step #2: Let’s check how many and which games are provided by python freely. To check type the below commandpython -m freegames list python -m freegames list After you click Enter, a list of available games will be shownFree Games in Python Free Games in Python Step #3: Free Python Games supports a command-line interface(A command line interface (CLI) is a text-based user interface (UI) used to view and manage computer files. Command line interfaces are also called command-line user interfaces, console user interfaces and character user interfaces). To get the help for the CLI type the below commandpython -m freegames --helpCommand-Line Interface python -m freegames --help Command-Line Interface Step #4: To run any game available in the list type, type the below command.python -m freegames.gamename" python -m freegames.gamename" After that just click Enter to run the game And you can see Python Turtle Graphics will be displayed.Tic Tac Toe Tic Tac Toe anikaseth98 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n26 Jul, 2021" }, { "code": null, "e": 24484, "s": 24292, "text": "Python provides you free games and it’s is very easy and simple to get them and you can run it on you computer. So, are you curious about how you can get them? Just follow these simple steps:" }, { "code": null, "e": 24493, "s": 24484, "text": "Step #1:" }, { "code": null, "e": 24576, "s": 24493, "text": "Go to command prompt and type the following commandpython -m pip install freegames" }, { "code": null, "e": 24608, "s": 24576, "text": "python -m pip install freegames" }, { "code": null, "e": 24658, "s": 24608, "text": "Wait until the installation process gets finished" }, { "code": null, "e": 24712, "s": 24658, "text": "After the process gets finished, you are ready to go." }, { "code": null, "e": 24721, "s": 24712, "text": "Step #2:" }, { "code": null, "e": 24845, "s": 24721, "text": "Let’s check how many and which games are provided by python freely. To check type the below commandpython -m freegames list" }, { "code": null, "e": 24870, "s": 24845, "text": "python -m freegames list" }, { "code": null, "e": 24953, "s": 24870, "text": "After you click Enter, a list of available games will be shownFree Games in Python" }, { "code": null, "e": 24974, "s": 24953, "text": "Free Games in Python" }, { "code": null, "e": 24983, "s": 24974, "text": "Step #3:" }, { "code": null, "e": 25268, "s": 24983, "text": "Free Python Games supports a command-line interface(A command line interface (CLI) is a text-based user interface (UI) used to view and manage computer files. Command line interfaces are also called command-line user interfaces, console user interfaces and character user interfaces)." }, { "code": null, "e": 25367, "s": 25268, "text": "To get the help for the CLI type the below commandpython -m freegames --helpCommand-Line Interface" }, { "code": null, "e": 25394, "s": 25367, "text": "python -m freegames --help" }, { "code": null, "e": 25417, "s": 25394, "text": "Command-Line Interface" }, { "code": null, "e": 25426, "s": 25417, "text": "Step #4:" }, { "code": null, "e": 25523, "s": 25426, "text": "To run any game available in the list type, type the below command.python -m freegames.gamename\"" }, { "code": null, "e": 25553, "s": 25523, "text": "python -m freegames.gamename\"" }, { "code": null, "e": 25597, "s": 25553, "text": "After that just click Enter to run the game" }, { "code": null, "e": 25666, "s": 25597, "text": "And you can see Python Turtle Graphics will be displayed.Tic Tac Toe" }, { "code": null, "e": 25678, "s": 25666, "text": "Tic Tac Toe" }, { "code": null, "e": 25690, "s": 25678, "text": "anikaseth98" }, { "code": null, "e": 25705, "s": 25690, "text": "python-modules" }, { "code": null, "e": 25712, "s": 25705, "text": "Python" }, { "code": null, "e": 25810, "s": 25712, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25819, "s": 25810, "text": "Comments" }, { "code": null, "e": 25832, "s": 25819, "text": "Old Comments" }, { "code": null, "e": 25864, "s": 25832, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25920, "s": 25864, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25975, "s": 25920, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26017, "s": 25975, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26059, "s": 26017, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26090, "s": 26059, "text": "Python | os.path.join() method" }, { "code": null, "e": 26129, "s": 26090, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26151, "s": 26129, "text": "Defaultdict in Python" }, { "code": null, "e": 26180, "s": 26151, "text": "Create a directory in Python" } ]
LINQ | Concatenation Operator | Concat - GeeksforGeeks
22 May, 2019 The concatenation is a process in which one sequence is appended into another sequence. In LINQ, the concatenation operation contains only one operator that is known as Concat. It is used to append two same types of sequences or collections and return a new sequence or collection. It does not support query syntax in C# and VB.NET languages. It support method syntax in both C# and VB.NET languages. It present in both the Queryable and Enumerable class. It is implemented by using deferred execution. It allow duplicate elements. As shown in the below image, here two sequences of the same types are concatenated into one sequence. Example 1: // C# program to concatenate the// given sequencesusing System;using System.Linq; class GFG { static public void Main() { // Data source char[] sequence1 = {'p', 'q', 'r', 's', 'y', 'z'}; char[] sequence2 = {'p', 'm', 'o', 'e', 'c', 'z'}; // Display the sequences Console.WriteLine("Sequence 1 is: "); foreach(var s1 in sequence1) { Console.WriteLine(s1); } Console.WriteLine("Sequence 2 is: "); foreach(var s2 in sequence2) { Console.WriteLine(s2); } // Concatenate the given array // Using Concat function var result = sequence1.Concat(sequence2); Console.WriteLine("New Sequence:"); foreach(var val in result) { Console.WriteLine(val); } }} Sequence 1 is: p q r s y z Sequence 2 is: p m o e c z New Sequence: p q r s y z p m o e c z Example 2: // C# program to print the major // language of the employeesusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee1 { public int emp_id1 { get; set; } public string emp_name1 { get; set; } public string emp_lang1 { get; set; }} // Employee detailspublic class Employee2 { public int emp_id2 { get; set; } public string emp_name2 { get; set; } public string emp_lang2 { get; set; }} class GFG { // Main method static public void Main() { List<Employee1> emp1 = new List<Employee1>() { new Employee1() {emp_id1 = 209, emp_name1 = "Anjita", emp_lang1 = "C#"}, new Employee1() {emp_id1 = 210, emp_name1 = "Soniya", emp_lang1 = "C"}, new Employee1() {emp_id1 = 211, emp_name1 = "Rohit", emp_lang1 = "Java"}, }; List<Employee2> emp2 = new List<Employee2>() { new Employee2() {emp_id2 = 219, emp_name2 = "Anita", emp_lang2 = "Scala"}, new Employee2() {emp_id2 = 223, emp_name2 = "Manya", emp_lang2 = "Python"}, new Employee2() {emp_id2 = 266, emp_name2 = "Rohan", emp_lang2 = "Ruby"}, }; // Query to concatenate the major // languages of the employees of // two different departments // Using Concat method var res = emp1.Select(e => e.emp_lang1).Concat(emp2.Select(e => e.emp_lang2)); Console.WriteLine("Major Languages Used are: "); foreach(var val in res) { Console.WriteLine(val); } }} Major Languages Used are: C# C Java Scala Python Ruby CSharp LINQ C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Method Overriding C# Dictionary with examples C# | Delegates Difference between Ref and Out keywords in C# Destructors in C# Extension Method in C# Introduction to .NET Framework C# | String.IndexOf( ) Method | Set - 1 C# | Abstract Classes C# | Encapsulation
[ { "code": null, "e": 23872, "s": 23844, "text": "\n22 May, 2019" }, { "code": null, "e": 24154, "s": 23872, "text": "The concatenation is a process in which one sequence is appended into another sequence. In LINQ, the concatenation operation contains only one operator that is known as Concat. It is used to append two same types of sequences or collections and return a new sequence or collection." }, { "code": null, "e": 24215, "s": 24154, "text": "It does not support query syntax in C# and VB.NET languages." }, { "code": null, "e": 24273, "s": 24215, "text": "It support method syntax in both C# and VB.NET languages." }, { "code": null, "e": 24328, "s": 24273, "text": "It present in both the Queryable and Enumerable class." }, { "code": null, "e": 24375, "s": 24328, "text": "It is implemented by using deferred execution." }, { "code": null, "e": 24404, "s": 24375, "text": "It allow duplicate elements." }, { "code": null, "e": 24506, "s": 24404, "text": "As shown in the below image, here two sequences of the same types are concatenated into one sequence." }, { "code": null, "e": 24517, "s": 24506, "text": "Example 1:" }, { "code": "// C# program to concatenate the// given sequencesusing System;using System.Linq; class GFG { static public void Main() { // Data source char[] sequence1 = {'p', 'q', 'r', 's', 'y', 'z'}; char[] sequence2 = {'p', 'm', 'o', 'e', 'c', 'z'}; // Display the sequences Console.WriteLine(\"Sequence 1 is: \"); foreach(var s1 in sequence1) { Console.WriteLine(s1); } Console.WriteLine(\"Sequence 2 is: \"); foreach(var s2 in sequence2) { Console.WriteLine(s2); } // Concatenate the given array // Using Concat function var result = sequence1.Concat(sequence2); Console.WriteLine(\"New Sequence:\"); foreach(var val in result) { Console.WriteLine(val); } }}", "e": 25353, "s": 24517, "text": null }, { "code": null, "e": 25448, "s": 25353, "text": "Sequence 1 is: \np\nq\nr\ns\ny\nz\nSequence 2 is: \np\nm\no\ne\nc\nz\nNew Sequence:\np\nq\nr\ns\ny\nz\np\nm\no\ne\nc\nz\n" }, { "code": null, "e": 25459, "s": 25448, "text": "Example 2:" }, { "code": "// C# program to print the major // language of the employeesusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee1 { public int emp_id1 { get; set; } public string emp_name1 { get; set; } public string emp_lang1 { get; set; }} // Employee detailspublic class Employee2 { public int emp_id2 { get; set; } public string emp_name2 { get; set; } public string emp_lang2 { get; set; }} class GFG { // Main method static public void Main() { List<Employee1> emp1 = new List<Employee1>() { new Employee1() {emp_id1 = 209, emp_name1 = \"Anjita\", emp_lang1 = \"C#\"}, new Employee1() {emp_id1 = 210, emp_name1 = \"Soniya\", emp_lang1 = \"C\"}, new Employee1() {emp_id1 = 211, emp_name1 = \"Rohit\", emp_lang1 = \"Java\"}, }; List<Employee2> emp2 = new List<Employee2>() { new Employee2() {emp_id2 = 219, emp_name2 = \"Anita\", emp_lang2 = \"Scala\"}, new Employee2() {emp_id2 = 223, emp_name2 = \"Manya\", emp_lang2 = \"Python\"}, new Employee2() {emp_id2 = 266, emp_name2 = \"Rohan\", emp_lang2 = \"Ruby\"}, }; // Query to concatenate the major // languages of the employees of // two different departments // Using Concat method var res = emp1.Select(e => e.emp_lang1).Concat(emp2.Select(e => e.emp_lang2)); Console.WriteLine(\"Major Languages Used are: \"); foreach(var val in res) { Console.WriteLine(val); } }}", "e": 27420, "s": 25459, "text": null }, { "code": null, "e": 27476, "s": 27420, "text": "Major Languages Used are: \nC#\nC\nJava\nScala\nPython\nRuby\n" }, { "code": null, "e": 27488, "s": 27476, "text": "CSharp LINQ" }, { "code": null, "e": 27491, "s": 27488, "text": "C#" }, { "code": null, "e": 27589, "s": 27491, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27612, "s": 27589, "text": "C# | Method Overriding" }, { "code": null, "e": 27640, "s": 27612, "text": "C# Dictionary with examples" }, { "code": null, "e": 27655, "s": 27640, "text": "C# | Delegates" }, { "code": null, "e": 27701, "s": 27655, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27719, "s": 27701, "text": "Destructors in C#" }, { "code": null, "e": 27742, "s": 27719, "text": "Extension Method in C#" }, { "code": null, "e": 27773, "s": 27742, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27813, "s": 27773, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27835, "s": 27813, "text": "C# | Abstract Classes" } ]
Java Program to check whether the character is ASCII 7 bit printable
To check whether the entered value is ASCII 7-bit printable, check whether the characters ASCII value is greater than equal to 32 and less than 127 or not. These are the control characters. Here, we have a character. char one = '^'; Now, we have checked a condition with if-else for printable characters. if (c >= 32 && c < 127) { System.out.println("Given value is printable!"); } else { System.out.println("Given value is not printable!"); } Live Demo public class Demo { public static void main(String []args) { char c = '^'; System.out.println("Given value = "+c); if (c >= 32 && c < 127) { System.out.println("Given value is printable!"); } else { System.out.println("Given value is not printable!"); } } } Given value = ^ Given value is printable! Let us see another example wherein the given value is a character. Live Demo public class Demo { public static void main(String []args) { char c = 'y'; System.out.println("Given value = "+c); if ( c >= 32 && c < 127) { System.out.println("Given value is printable!"); } else { System.out.println("Given value is not printable!"); } } } Given value = y Given value is printable!
[ { "code": null, "e": 1252, "s": 1062, "text": "To check whether the entered value is ASCII 7-bit printable, check whether the characters ASCII value is greater than equal to 32 and less than 127 or not. These are the control characters." }, { "code": null, "e": 1279, "s": 1252, "text": "Here, we have a character." }, { "code": null, "e": 1295, "s": 1279, "text": "char one = '^';" }, { "code": null, "e": 1367, "s": 1295, "text": "Now, we have checked a condition with if-else for printable characters." }, { "code": null, "e": 1512, "s": 1367, "text": "if (c >= 32 && c < 127) {\n System.out.println(\"Given value is printable!\");\n} else {\n System.out.println(\"Given value is not printable!\");\n}" }, { "code": null, "e": 1523, "s": 1512, "text": " Live Demo" }, { "code": null, "e": 1835, "s": 1523, "text": "public class Demo {\n public static void main(String []args) {\n char c = '^';\n System.out.println(\"Given value = \"+c);\n if (c >= 32 && c < 127) {\n System.out.println(\"Given value is printable!\");\n } else {\n System.out.println(\"Given value is not printable!\");\n }\n }\n}" }, { "code": null, "e": 1877, "s": 1835, "text": "Given value = ^\nGiven value is printable!" }, { "code": null, "e": 1944, "s": 1877, "text": "Let us see another example wherein the given value is a character." }, { "code": null, "e": 1955, "s": 1944, "text": " Live Demo" }, { "code": null, "e": 2268, "s": 1955, "text": "public class Demo {\n public static void main(String []args) {\n char c = 'y';\n System.out.println(\"Given value = \"+c);\n if ( c >= 32 && c < 127) {\n System.out.println(\"Given value is printable!\");\n } else {\n System.out.println(\"Given value is not printable!\");\n }\n }\n}" }, { "code": null, "e": 2310, "s": 2268, "text": "Given value = y\nGiven value is printable!" } ]
How data normalization affects your Random Forest algorithm | by Javier Fernandez | Towards Data Science
Recently, I was implementing a Random Forest regressor when I faced the classical question of: Should I implement data normalization?. As far as I knew, decision tree-based algorithms do not need, in general, normalization. But, I realized that every time I heard this statement it was related to classifiers so, what about regressors? Do they need data normalization? If you search on the internet Random Forest normalization, the first links indicate that: Stack Overflow: (1) No, scaling is not necessary for random forests, (2) Random Forest is a tree-based model and hence does not require feature scaling. Stack Exchange: Thanks for the clarification by commenting. Tree-based models do not care about the absolute value that a feature takes. They only care about the order of the values. Hence, normalization is used mainly in linear models/KNN/neural networks because they’re affected by absolute values taken by features. However, after deepening my research, I discovered that data normalization may affect the output. So, here I leave my takeaway and a short demonstration in Python. For classification tasks, the output of the random forest is the class selected by most trees. For regression tasks, the mean or average prediction of the individual trees is returned. Therefore, data normalization won’t affect the output for Random Forest classifiers while it will affect the output for Random Forest regressors. Regarding the regressor, the algorithm will be more affected by the high-end values if the data is not transformed. This means that they will probably be more accurate in predicting high values than low values. Consequently, transformations such as log-transform will reduce the relative importance of these high values, hence generalizing better. Here I present a short experiment that shows that the output changes for regressors when implementing data normalization but it is the same for classifiers. Importing the libraries Loading the dataset The dataset selected is the Boston House-prices dataset, used for regression tasks. Keys: dict_keys(['data', 'target', 'feature_names', 'DESCR', 'filename'])Feature names: ['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO' 'B' 'LSTAT']Data shape: (506, 13)Target shape: (506,) To use this dataset also for classification, the target variable has been rounded. Random Forest classifier Here is the implementation of the Random Forest classifier under three conditions: (1) no normalization, (2) min-max normalization, and (3) standardization. As observed, the data normalization does not affect the accuracy score. Accuracy score without normalization: 0.12574850299401197Accuracy score with min-max normalization: 0.12574850299401197Accuracy score with standardization: 0.12574850299401197 Random Forest regressor Here is the implementation of the Random Forest regressor under three conditions: (1) no normalization, (2) min-max normalization, and (3) standardization. In this case, data normalization affects the mean squared score of the regressor. Accuracy score without normalization: 13.38962275449102Accuracy score with min-max normalization: 13.478456820359284Accuracy score with standardization: 13.38586179640719
[ { "code": null, "e": 182, "s": 47, "text": "Recently, I was implementing a Random Forest regressor when I faced the classical question of: Should I implement data normalization?." }, { "code": null, "e": 416, "s": 182, "text": "As far as I knew, decision tree-based algorithms do not need, in general, normalization. But, I realized that every time I heard this statement it was related to classifiers so, what about regressors? Do they need data normalization?" }, { "code": null, "e": 506, "s": 416, "text": "If you search on the internet Random Forest normalization, the first links indicate that:" }, { "code": null, "e": 659, "s": 506, "text": "Stack Overflow: (1) No, scaling is not necessary for random forests, (2) Random Forest is a tree-based model and hence does not require feature scaling." }, { "code": null, "e": 978, "s": 659, "text": "Stack Exchange: Thanks for the clarification by commenting. Tree-based models do not care about the absolute value that a feature takes. They only care about the order of the values. Hence, normalization is used mainly in linear models/KNN/neural networks because they’re affected by absolute values taken by features." }, { "code": null, "e": 1142, "s": 978, "text": "However, after deepening my research, I discovered that data normalization may affect the output. So, here I leave my takeaway and a short demonstration in Python." }, { "code": null, "e": 1327, "s": 1142, "text": "For classification tasks, the output of the random forest is the class selected by most trees. For regression tasks, the mean or average prediction of the individual trees is returned." }, { "code": null, "e": 1473, "s": 1327, "text": "Therefore, data normalization won’t affect the output for Random Forest classifiers while it will affect the output for Random Forest regressors." }, { "code": null, "e": 1684, "s": 1473, "text": "Regarding the regressor, the algorithm will be more affected by the high-end values if the data is not transformed. This means that they will probably be more accurate in predicting high values than low values." }, { "code": null, "e": 1821, "s": 1684, "text": "Consequently, transformations such as log-transform will reduce the relative importance of these high values, hence generalizing better." }, { "code": null, "e": 1978, "s": 1821, "text": "Here I present a short experiment that shows that the output changes for regressors when implementing data normalization but it is the same for classifiers." }, { "code": null, "e": 2002, "s": 1978, "text": "Importing the libraries" }, { "code": null, "e": 2022, "s": 2002, "text": "Loading the dataset" }, { "code": null, "e": 2106, "s": 2022, "text": "The dataset selected is the Boston House-prices dataset, used for regression tasks." }, { "code": null, "e": 2321, "s": 2106, "text": "Keys: dict_keys(['data', 'target', 'feature_names', 'DESCR', 'filename'])Feature names: ['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO' 'B' 'LSTAT']Data shape: (506, 13)Target shape: (506,)" }, { "code": null, "e": 2404, "s": 2321, "text": "To use this dataset also for classification, the target variable has been rounded." }, { "code": null, "e": 2429, "s": 2404, "text": "Random Forest classifier" }, { "code": null, "e": 2586, "s": 2429, "text": "Here is the implementation of the Random Forest classifier under three conditions: (1) no normalization, (2) min-max normalization, and (3) standardization." }, { "code": null, "e": 2658, "s": 2586, "text": "As observed, the data normalization does not affect the accuracy score." }, { "code": null, "e": 2834, "s": 2658, "text": "Accuracy score without normalization: 0.12574850299401197Accuracy score with min-max normalization: 0.12574850299401197Accuracy score with standardization: 0.12574850299401197" }, { "code": null, "e": 2858, "s": 2834, "text": "Random Forest regressor" }, { "code": null, "e": 3014, "s": 2858, "text": "Here is the implementation of the Random Forest regressor under three conditions: (1) no normalization, (2) min-max normalization, and (3) standardization." }, { "code": null, "e": 3096, "s": 3014, "text": "In this case, data normalization affects the mean squared score of the regressor." } ]
Crystal Reports - Creating Arrays
An Array variable in Crystal Report can be defined by using a keyword "Array". Global NumberVar Array Z := [1, 2, 3]; You can also assign values to the elements of Array and these values can be used for computations in formulas. For example − StringVar Array Z := ["Hello","World"]; Z[2] :=["Bye"]; UpperCase (Z [2] ) This formula will return the string "Bye". You can also resize Array using Redim and Redim Preserve keywords. Redim is used to remove previous entries of an Array while resizing it, and Redim Preserve is used to contain previous Array values. For example − Local NumberVar Array Z; Redim Z [2]; //Now Z is [0, 0] Z [2] := 10; //Now Z is [0, 10] Redim Z [3]; //Now Z is [0, 0, 0], Redim has erased previous Array values. Z [3] := 20; //Now Z is [0, 0, 20] Redim Preserve Z [4]; //Now Z is [0, 0, 20, 0], Redim Preserve has contained previous Array values. "finished" Arrays are also used with Loops: like For loop. Local NumberVar Array Z; Redim Z[10]; Local NumberVar x; For x := 1 To 10 Do ( Z[x] := 10 * x ); Z [5] //The formula returns the Number 50 37 Lectures 2 hours Neha Gupta 61 Lectures 4.5 hours Sasha Miller 31 Lectures 32 mins Prof Krishna N Sharma 35 Lectures 2 hours Prof Krishna N Sharma 24 Lectures 2 hours Prof Krishna N Sharma Print Add Notes Bookmark this page
[ { "code": null, "e": 3049, "s": 2970, "text": "An Array variable in Crystal Report can be defined by using a keyword \"Array\"." }, { "code": null, "e": 3089, "s": 3049, "text": "Global NumberVar Array Z := [1, 2, 3];\n" }, { "code": null, "e": 3214, "s": 3089, "text": "You can also assign values to the elements of Array and these values can be used for computations in formulas. For example −" }, { "code": null, "e": 3289, "s": 3214, "text": "StringVar Array Z := [\"Hello\",\"World\"];\nZ[2] :=[\"Bye\"];\nUpperCase (Z [2] )" }, { "code": null, "e": 3332, "s": 3289, "text": "This formula will return the string \"Bye\"." }, { "code": null, "e": 3546, "s": 3332, "text": "You can also resize Array using Redim and Redim Preserve keywords. Redim is used to remove previous entries of an Array while resizing it, and Redim Preserve is used to contain previous Array values. For example −" }, { "code": null, "e": 3859, "s": 3546, "text": "Local NumberVar Array Z;\nRedim Z [2]; //Now Z is [0, 0]\n\nZ [2] := 10; //Now Z is [0, 10]\nRedim Z [3]; //Now Z is [0, 0, 0], Redim has erased previous Array values.\n\nZ [3] := 20; //Now Z is [0, 0, 20]\nRedim Preserve Z [4]; //Now Z is [0, 0, 20, 0], Redim Preserve has contained previous \n\nArray values.\n\"finished\"" }, { "code": null, "e": 3907, "s": 3859, "text": "Arrays are also used with Loops: like For loop." }, { "code": null, "e": 4051, "s": 3907, "text": "Local NumberVar Array Z;\nRedim Z[10];\n\nLocal NumberVar x;\nFor x := 1 To 10 Do (\n Z[x] := 10 * x\n);\n\nZ [5] //The formula returns the Number 50" }, { "code": null, "e": 4084, "s": 4051, "text": "\n 37 Lectures \n 2 hours \n" }, { "code": null, "e": 4096, "s": 4084, "text": " Neha Gupta" }, { "code": null, "e": 4131, "s": 4096, "text": "\n 61 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4145, "s": 4131, "text": " Sasha Miller" }, { "code": null, "e": 4177, "s": 4145, "text": "\n 31 Lectures \n 32 mins\n" }, { "code": null, "e": 4200, "s": 4177, "text": " Prof Krishna N Sharma" }, { "code": null, "e": 4233, "s": 4200, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 4256, "s": 4233, "text": " Prof Krishna N Sharma" }, { "code": null, "e": 4289, "s": 4256, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 4312, "s": 4289, "text": " Prof Krishna N Sharma" }, { "code": null, "e": 4319, "s": 4312, "text": " Print" }, { "code": null, "e": 4330, "s": 4319, "text": " Add Notes" } ]
HTML5 Complete Reference - GeeksforGeeks
17 Mar, 2022 HTML stands for Hyper Text Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within the tag which defines the structure of web pages. HTML 5 is the fifth and current version of HTML. It has improved the markup available for documents and has introduced application programming interfaces(API) and Document Object Model(DOM). The below examples illustrate the HTML 5 content. Example: <!DOCTYPE html> <html> <head> <title>HTML 5 Demo</title> <style> .GFG { font-size:40px; font-weight:bold; color:green; } body { text-align:center; } </style> </head> <body> <div class = "GFG">GeeksforGeeks</div> <aside> <div>A computer science portal for geeks</div> </aside> </body> </html> Output: Features: It has introduced new multimedia features that support audio and video controls by using <audio> and <video> tags. There are new graphics elements including vector graphics and tags. Enrich semantic content by including <header> <footer>, <article>, <section> and <figure> are added. Drag and Drop- The user can grab an object and drag it further dropping it in a new location. Geo-location services- It helps to locate the geographical location of a client. Web storage facility which provides web application methods to store data on a web browser. Uses the SQL database to store data offline. Allows drawing various shapes like triangle, rectangle, circle, etc. Capable of handling incorrect syntax. Easy DOCTYPE declaration i.e. <!doctype html> Easy character encoding i.e. <meta charset=”UTF-8′′> Complete Reference: HTML5 | Introduction HTML5 | Editors HTML5 | Basics HTML5 | Attributes HTML5 | Paragraph HTML5 | Text Formatting HTML5 | Quotations HTML5 | Tables HTML5 | Lists HTML5 | Spell Check HTML5 | Color Styles and HSL HTML5 | Geolocation HTML5 | Drag and Drop HTML5 | Charsets HTML5 | Images HTML5 | Doctypes HTML5 | Layout HTML5 | File Paths HTML5 | Iframes HTML5 | Links HTML5 | Deprecated Tags HTML5 | URL Encoding HTML5 | SVG-Basics HTML5 | Canvas Basics HTML5 | Computer Code Elements HTML5 | Entities HTML5 | canvas drawImage() Method HTML5 | template Tag HTML5 | dropzone Attribute HTML5 | rp Tag HTML5 | rt Tag HTML5 | <ruby> Tag HTML5 | figure Tag HTML5 | figcaption Tag HTML5 | fieldset Tag HTML5 | <head> Tag HTML5 | <dialog> Tag HTML5 | <bdi> Tag HTML5 | <progress> Tag HTML5 | <meter> Tag HTML5 | <wbr> Tag HTML5 | mark Tag HTML5 | <header> Tag HTML5 | <footer> Tag HTML5 | article tag HTML5 | <aside> Tag HTML5 | <section> Tag HTML5 | <summary> Tag HTML5 | <details> tag HTML5 | Semantics HTML5 | Mathematical operators HTML5 | Video Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML5 HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 30011, "s": 29983, "text": "\n17 Mar, 2022" }, { "code": null, "e": 30330, "s": 30011, "text": "HTML stands for Hyper Text Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within the tag which defines the structure of web pages." }, { "code": null, "e": 30521, "s": 30330, "text": "HTML 5 is the fifth and current version of HTML. It has improved the markup available for documents and has introduced application programming interfaces(API) and Document Object Model(DOM)." }, { "code": null, "e": 30571, "s": 30521, "text": "The below examples illustrate the HTML 5 content." }, { "code": null, "e": 30580, "s": 30571, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title>HTML 5 Demo</title> <style> .GFG { font-size:40px; font-weight:bold; color:green; } body { text-align:center; } </style> </head> <body> <div class = \"GFG\">GeeksforGeeks</div> <aside> <div>A computer science portal for geeks</div> </aside> </body> </html> ", "e": 31017, "s": 30580, "text": null }, { "code": null, "e": 31025, "s": 31017, "text": "Output:" }, { "code": null, "e": 31035, "s": 31025, "text": "Features:" }, { "code": null, "e": 31150, "s": 31035, "text": "It has introduced new multimedia features that support audio and video controls by using <audio> and <video> tags." }, { "code": null, "e": 31218, "s": 31150, "text": "There are new graphics elements including vector graphics and tags." }, { "code": null, "e": 31319, "s": 31218, "text": "Enrich semantic content by including <header> <footer>, <article>, <section> and <figure> are added." }, { "code": null, "e": 31413, "s": 31319, "text": "Drag and Drop- The user can grab an object and drag it further dropping it in a new location." }, { "code": null, "e": 31494, "s": 31413, "text": "Geo-location services- It helps to locate the geographical location of a client." }, { "code": null, "e": 31586, "s": 31494, "text": "Web storage facility which provides web application methods to store data on a web browser." }, { "code": null, "e": 31631, "s": 31586, "text": "Uses the SQL database to store data offline." }, { "code": null, "e": 31700, "s": 31631, "text": "Allows drawing various shapes like triangle, rectangle, circle, etc." }, { "code": null, "e": 31738, "s": 31700, "text": "Capable of handling incorrect syntax." }, { "code": null, "e": 31784, "s": 31738, "text": "Easy DOCTYPE declaration i.e. <!doctype html>" }, { "code": null, "e": 31837, "s": 31784, "text": "Easy character encoding i.e. <meta charset=”UTF-8′′>" }, { "code": null, "e": 31857, "s": 31837, "text": "Complete Reference:" }, { "code": null, "e": 31878, "s": 31857, "text": "HTML5 | Introduction" }, { "code": null, "e": 31894, "s": 31878, "text": "HTML5 | Editors" }, { "code": null, "e": 31909, "s": 31894, "text": "HTML5 | Basics" }, { "code": null, "e": 31928, "s": 31909, "text": "HTML5 | Attributes" }, { "code": null, "e": 31946, "s": 31928, "text": "HTML5 | Paragraph" }, { "code": null, "e": 31970, "s": 31946, "text": "HTML5 | Text Formatting" }, { "code": null, "e": 31989, "s": 31970, "text": "HTML5 | Quotations" }, { "code": null, "e": 32004, "s": 31989, "text": "HTML5 | Tables" }, { "code": null, "e": 32018, "s": 32004, "text": "HTML5 | Lists" }, { "code": null, "e": 32038, "s": 32018, "text": "HTML5 | Spell Check" }, { "code": null, "e": 32067, "s": 32038, "text": "HTML5 | Color Styles and HSL" }, { "code": null, "e": 32087, "s": 32067, "text": "HTML5 | Geolocation" }, { "code": null, "e": 32109, "s": 32087, "text": "HTML5 | Drag and Drop" }, { "code": null, "e": 32126, "s": 32109, "text": "HTML5 | Charsets" }, { "code": null, "e": 32141, "s": 32126, "text": "HTML5 | Images" }, { "code": null, "e": 32158, "s": 32141, "text": "HTML5 | Doctypes" }, { "code": null, "e": 32173, "s": 32158, "text": "HTML5 | Layout" }, { "code": null, "e": 32192, "s": 32173, "text": "HTML5 | File Paths" }, { "code": null, "e": 32208, "s": 32192, "text": "HTML5 | Iframes" }, { "code": null, "e": 32222, "s": 32208, "text": "HTML5 | Links" }, { "code": null, "e": 32246, "s": 32222, "text": "HTML5 | Deprecated Tags" }, { "code": null, "e": 32267, "s": 32246, "text": "HTML5 | URL Encoding" }, { "code": null, "e": 32286, "s": 32267, "text": "HTML5 | SVG-Basics" }, { "code": null, "e": 32308, "s": 32286, "text": "HTML5 | Canvas Basics" }, { "code": null, "e": 32339, "s": 32308, "text": "HTML5 | Computer Code Elements" }, { "code": null, "e": 32356, "s": 32339, "text": "HTML5 | Entities" }, { "code": null, "e": 32390, "s": 32356, "text": "HTML5 | canvas drawImage() Method" }, { "code": null, "e": 32411, "s": 32390, "text": "HTML5 | template Tag" }, { "code": null, "e": 32438, "s": 32411, "text": "HTML5 | dropzone Attribute" }, { "code": null, "e": 32453, "s": 32438, "text": "HTML5 | rp Tag" }, { "code": null, "e": 32468, "s": 32453, "text": "HTML5 | rt Tag" }, { "code": null, "e": 32487, "s": 32468, "text": "HTML5 | <ruby> Tag" }, { "code": null, "e": 32506, "s": 32487, "text": "HTML5 | figure Tag" }, { "code": null, "e": 32529, "s": 32506, "text": "HTML5 | figcaption Tag" }, { "code": null, "e": 32550, "s": 32529, "text": "HTML5 | fieldset Tag" }, { "code": null, "e": 32569, "s": 32550, "text": "HTML5 | <head> Tag" }, { "code": null, "e": 32590, "s": 32569, "text": "HTML5 | <dialog> Tag" }, { "code": null, "e": 32608, "s": 32590, "text": "HTML5 | <bdi> Tag" }, { "code": null, "e": 32631, "s": 32608, "text": "HTML5 | <progress> Tag" }, { "code": null, "e": 32651, "s": 32631, "text": "HTML5 | <meter> Tag" }, { "code": null, "e": 32669, "s": 32651, "text": "HTML5 | <wbr> Tag" }, { "code": null, "e": 32686, "s": 32669, "text": "HTML5 | mark Tag" }, { "code": null, "e": 32707, "s": 32686, "text": "HTML5 | <header> Tag" }, { "code": null, "e": 32728, "s": 32707, "text": "HTML5 | <footer> Tag" }, { "code": null, "e": 32748, "s": 32728, "text": "HTML5 | article tag" }, { "code": null, "e": 32768, "s": 32748, "text": "HTML5 | <aside> Tag" }, { "code": null, "e": 32790, "s": 32768, "text": "HTML5 | <section> Tag" }, { "code": null, "e": 32812, "s": 32790, "text": "HTML5 | <summary> Tag" }, { "code": null, "e": 32834, "s": 32812, "text": "HTML5 | <details> tag" }, { "code": null, "e": 32852, "s": 32834, "text": "HTML5 | Semantics" }, { "code": null, "e": 32883, "s": 32852, "text": "HTML5 | Mathematical operators" }, { "code": null, "e": 32897, "s": 32883, "text": "HTML5 | Video" }, { "code": null, "e": 33034, "s": 32897, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 33040, "s": 33034, "text": "HTML5" }, { "code": null, "e": 33045, "s": 33040, "text": "HTML" }, { "code": null, "e": 33062, "s": 33045, "text": "Web Technologies" }, { "code": null, "e": 33067, "s": 33062, "text": "HTML" }, { "code": null, "e": 33165, "s": 33067, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33174, "s": 33165, "text": "Comments" }, { "code": null, "e": 33187, "s": 33174, "text": "Old Comments" }, { "code": null, "e": 33249, "s": 33187, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33299, "s": 33249, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33359, "s": 33299, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33407, "s": 33359, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33468, "s": 33407, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 33524, "s": 33468, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 33557, "s": 33524, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33619, "s": 33557, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33662, "s": 33619, "text": "How to fetch data from an API in ReactJS ?" } ]
How to add a horizontal line to the plot created by ggplot2 in R?
When we create a plot, it shows the values passed by the function for creating the plot but we might want to display some other values to provide some information through the plot and that information could be a threshold value as a horizontal line or we can also call it a cut off value. This can be done by using geom_hline function of ggplot2 package. Consider the below data frame − > x<-rnorm(20) > y<-rnorm(20,1.5) > df<-data.frame(x,y) > df x y 1 0.27810573 2.6545571 2 1.39185082 3.4845292 3 -0.19068920 1.7043852 4 1.00791317 1.4324814 5 -1.74964913 1.7996093 6 -0.13123079 2.5004350 7 0.15729145 2.6425085 8 0.42815918 -0.2970325 9 -0.84252471 0.2579510 10 0.25413824 3.0670546 11 -0.05608811 1.6974104 12 -0.85671276 0.8638574 13 -1.17183043 2.5650640 14 2.67224782 0.4832468 15 -0.01763065 3.3835275 16 1.26122484 1.1755709 17 1.91652453 1.6351443 18 0.82211772 0.9123337 19 -0.19153555 0.1831160 20 0.31878745 3.1280550 Creating a scatterplot between x and y − > library(ggplot2) > ggplot(df,aes(x,y))+geom_point() Adding a horizontal line in the above plot − > ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=0.5)
[ { "code": null, "e": 1417, "s": 1062, "text": "When we create a plot, it shows the values passed by the function for creating the plot but we might want to display some other values to provide some information through the plot and that information could be a threshold value as a horizontal line or we can also call it a cut off value. This can be done by using geom_hline function of ggplot2 package." }, { "code": null, "e": 1449, "s": 1417, "text": "Consider the below data frame −" }, { "code": null, "e": 1510, "s": 1449, "text": "> x<-rnorm(20)\n> y<-rnorm(20,1.5)\n> df<-data.frame(x,y)\n> df" }, { "code": null, "e": 2007, "s": 1510, "text": " x y\n1 0.27810573 2.6545571\n2 1.39185082 3.4845292\n3 -0.19068920 1.7043852\n4 1.00791317 1.4324814\n5 -1.74964913 1.7996093\n6 -0.13123079 2.5004350\n7 0.15729145 2.6425085\n8 0.42815918 -0.2970325\n9 -0.84252471 0.2579510\n10 0.25413824 3.0670546\n11 -0.05608811 1.6974104\n12 -0.85671276 0.8638574\n13 -1.17183043 2.5650640\n14 2.67224782 0.4832468\n15 -0.01763065 3.3835275\n16 1.26122484 1.1755709\n17 1.91652453 1.6351443\n18 0.82211772 0.9123337\n19 -0.19153555 0.1831160\n20 0.31878745 3.1280550" }, { "code": null, "e": 2048, "s": 2007, "text": "Creating a scatterplot between x and y −" }, { "code": null, "e": 2102, "s": 2048, "text": "> library(ggplot2)\n> ggplot(df,aes(x,y))+geom_point()" }, { "code": null, "e": 2147, "s": 2102, "text": "Adding a horizontal line in the above plot −" }, { "code": null, "e": 2209, "s": 2147, "text": "> ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=0.5)" } ]
Assignment Operators Overloading in C++
You can overload the assignment operator (=) just as you can other operators and it can be used to create an object just like the copy constructor. Following example explains how an assignment operator can be overloaded. #include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance() { feet = 0; inches = 0; } Distance(int f, int i) { feet = f; inches = i; } void operator = (const Distance &D ) { feet = D.feet; inches = D.inches; } // method to display distance void displayDistance() { cout << "F: " << feet << " I:" << inches << endl; } }; int main() { Distance D1(11, 10), D2(5, 11); cout << "First Distance : "; D1.displayDistance(); cout << "Second Distance :"; D2.displayDistance(); // use assignment operator D1 = D2; cout << "First Distance :"; D1.displayDistance(); return 0; } When the above code is compiled and executed, it produces the following result − First Distance : F: 11 I:10 Second Distance :F: 5 I:11 First Distance :F: 5 I:11 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2466, "s": 2318, "text": "You can overload the assignment operator (=) just as you can other operators and it can be used to create an object just like the copy constructor." }, { "code": null, "e": 2539, "s": 2466, "text": "Following example explains how an assignment operator can be overloaded." }, { "code": null, "e": 3424, "s": 2539, "text": "#include <iostream>\nusing namespace std;\n \nclass Distance {\n private:\n int feet; // 0 to infinite\n int inches; // 0 to 12\n \n public:\n // required constructors\n Distance() {\n feet = 0;\n inches = 0;\n }\n Distance(int f, int i) {\n feet = f;\n inches = i;\n }\n void operator = (const Distance &D ) { \n feet = D.feet;\n inches = D.inches;\n }\n \n // method to display distance\n void displayDistance() {\n cout << \"F: \" << feet << \" I:\" << inches << endl;\n }\n};\n\nint main() {\n Distance D1(11, 10), D2(5, 11);\n\n cout << \"First Distance : \"; \n D1.displayDistance();\n cout << \"Second Distance :\"; \n D2.displayDistance();\n\n // use assignment operator\n D1 = D2;\n cout << \"First Distance :\"; \n D1.displayDistance();\n\n return 0;\n}" }, { "code": null, "e": 3505, "s": 3424, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3587, "s": 3505, "text": "First Distance : F: 11 I:10\nSecond Distance :F: 5 I:11\nFirst Distance :F: 5 I:11\n" }, { "code": null, "e": 3624, "s": 3587, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 3643, "s": 3624, "text": " Arnab Chakraborty" }, { "code": null, "e": 3675, "s": 3643, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 3698, "s": 3675, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 3734, "s": 3698, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 3751, "s": 3734, "text": " Frahaan Hussain" }, { "code": null, "e": 3786, "s": 3751, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3803, "s": 3786, "text": " Frahaan Hussain" }, { "code": null, "e": 3838, "s": 3803, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3855, "s": 3838, "text": " Frahaan Hussain" }, { "code": null, "e": 3890, "s": 3855, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3907, "s": 3890, "text": " Frahaan Hussain" }, { "code": null, "e": 3914, "s": 3907, "text": " Print" }, { "code": null, "e": 3925, "s": 3914, "text": " Add Notes" } ]
Building Recommender Systems Engines with a Python Framework | by Arthur Fortes | Towards Data Science
A number of frameworks for Recommender Systems (RS) have been proposed by the scientific community, involving different programming languages, such as Java, C\#, Python, among others. However, most of them lack an integrated environment containing clustering and ensemble approaches which are capable to improve recommendation accuracy. On the one hand, clustering may support developers to pre-process their data to optimize or extend recommender algorithms. On the other hand, ensemble approaches are efficient tools to combine different types of data in a personalized way. In this article, I describe a python framework called Case Recommender, which contains a variety of content-based and collaborative recommender algorithms, as well as ensemble approaches for combining multiple algorithms and data sources. In addition, it provides a set of popular evaluation methods and metrics for rating prediction and item recommendation. Traditionally, recommender systems employ filtering techniques and machine learning information to generate appropriate recommendations to the user’s interests from the representation of his profile. However, other techniques, such as Neural Networks, Bayesian Networks and Association Rules, are also used in the filtering process . The most used types of filtering are currently: Content-Based (CBF), responsible for selecting information based on content filtering of elements, e.g., e-mail messages filtered out as trash for containing unwanted words; Collaborative Filtering (CF), based on the relationship between people and their subjective regarding the information to be filtered. The selection of e-mails based on the relationship between sender and recipient is an example of that. Besides, there is a hybrid approach that combines the content-based and the collaborative filtering methods. Case Recommender is currently being rewritten to support optimized calculations using known Python scientific libraries. I also developed and improved classes that allow developers to manipulate files, predict and evaluate models, compute (dis)similarities between users or items, beside use metadata and external information. The framework is now implemented in Python 3 and it addresses two common scenarios in recommender systems: rating prediction and item recommendation, using explicit, implicit or both types of feedback in several recommender strategies. To install Case Recommender on Mac OS X / Linux/ Windows, chances are that one of the following two commands will work for developers and users: easy_install CaseRecommender or alternatively: pip install CaseRecommender The important features while designing our framework were to enable the computation of recommendations in large-scale, easy creation and extension of algorithms for different types of filtering and scenarios. Another feature is to support sparse and large datasets in a way that there is as little as possible overhead for storing data and intermediate results. Developers can choose between using one of the available recommender algorithms, combining multiple recommendations using one of the available ensemble techniques, or develop their own algorithm using the BaseRatingPrediction or BaseItemRecommendation classes. Up to the current version, the algorithms available in the framework are shown at table bellow: The framework allows developers to deal with different datasets and not having to develop their own programs to execute recommender functions. The input ofalgorithms expects the data to be in a simple text format: user_id item_id feedback where user_id and item_id are integers referring to users and items IDs, respectively, and feedback is a number expressing how much the user likes an item or binary interaction. The separator between the values can be either spaces, tabs, or commas. If there are more than three columns, all additional columns are ignored. For example, below is a sample of data from the ML100k dataset: During my studies, I also build a repository of a topic-centric public data sources in high quality for RS. They are collected and tidied from Stack Overflow, articles, recommender sites and academic experiments. Most of the datasets presented in the repository are free, having open sorce linceses, however, some are not and you need to ask permission to use or cite the authors’ work. Access this link to obtain theses data. github.com For divide our dataset using Fold Cross Validation: from caserec.utils.split_database import SplitDatabaseSplitDatabase(input_file=dataset, dir_folds=dir_path, n_splits=10).k_fold_cross_validation() Run Item Recommendation Algorithm (E.g: ItemKNN) from caserec.recommenders.item_recommendation.itemknn import ItemKNNItemKNN(train_file, test_file).compute() Run Rating Prediction Algorithm (E.g: ItemKNN) from caserec.recommenders.rating_prediction.itemknn import ItemKNNItemKNN(train_file, test_file).compute() Evaluate Ranking (Prec@N, Recall@N, NDCG@, Map@N and Map Total) from caserec.evaluation.item_recommendation import ItemRecommendationEvaluation ItemRecommendationEvaluation().evaluate_with_files(predictions_file, test_file) Evaluate Ranking (MAE and RMSE) from caserec.evaluation.rating_prediction import RatingPredictionEvaluationRatingPredictionEvaluation().evaluate_with_files(predictions_file, test_file) Run ItemKNN in Fold Cross Validation Approach from caserec.recommenders.item_recommendation.itemknn import ItemKNNfrom caserec.utils.cross_validation import CrossValidation## Cross Validationrecommender = ItemKNN(as_binary=True)CrossValidation(input_file=db, recommender=recommender, dir_folds=folds_path, header=1, k_folds=5).compute() More examples can be found in this link. The goal of Case Recommender is to integrate and facilitate the experiments and development of new recommender techniques for different domains. Our framework contains a recommender engine, that contains content-based, collaborative and hybrid filtering approaches for rating prediction and item recommendation scenarios. In addition, the framework contains ensemble and clustering algorithms, validation and evaluation metrics to improve and measure the quality of the recommendation. Future releases are planned which will include more features (parallel processing techniques and new algorithms) and an evaluation tool with several plots and graphs to help developers to better understand the behavior of their recommender algorithms.
[ { "code": null, "e": 749, "s": 172, "text": "A number of frameworks for Recommender Systems (RS) have been proposed by the scientific community, involving different programming languages, such as Java, C\\#, Python, among others. However, most of them lack an integrated environment containing clustering and ensemble approaches which are capable to improve recommendation accuracy. On the one hand, clustering may support developers to pre-process their data to optimize or extend recommender algorithms. On the other hand, ensemble approaches are efficient tools to combine different types of data in a personalized way." }, { "code": null, "e": 1108, "s": 749, "text": "In this article, I describe a python framework called Case Recommender, which contains a variety of content-based and collaborative recommender algorithms, as well as ensemble approaches for combining multiple algorithms and data sources. In addition, it provides a set of popular evaluation methods and metrics for rating prediction and item recommendation." }, { "code": null, "e": 2010, "s": 1108, "text": "Traditionally, recommender systems employ filtering techniques and machine learning information to generate appropriate recommendations to the user’s interests from the representation of his profile. However, other techniques, such as Neural Networks, Bayesian Networks and Association Rules, are also used in the filtering process . The most used types of filtering are currently: Content-Based (CBF), responsible for selecting information based on content filtering of elements, e.g., e-mail messages filtered out as trash for containing unwanted words; Collaborative Filtering (CF), based on the relationship between people and their subjective regarding the information to be filtered. The selection of e-mails based on the relationship between sender and recipient is an example of that. Besides, there is a hybrid approach that combines the content-based and the collaborative filtering methods." }, { "code": null, "e": 2718, "s": 2010, "text": "Case Recommender is currently being rewritten to support optimized calculations using known Python scientific libraries. I also developed and improved classes that allow developers to manipulate files, predict and evaluate models, compute (dis)similarities between users or items, beside use metadata and external information. The framework is now implemented in Python 3 and it addresses two common scenarios in recommender systems: rating prediction and item recommendation, using explicit, implicit or both types of feedback in several recommender strategies. To install Case Recommender on Mac OS X / Linux/ Windows, chances are that one of the following two commands will work for developers and users:" }, { "code": null, "e": 2747, "s": 2718, "text": "easy_install CaseRecommender" }, { "code": null, "e": 2765, "s": 2747, "text": "or alternatively:" }, { "code": null, "e": 2793, "s": 2765, "text": "pip install CaseRecommender" }, { "code": null, "e": 3512, "s": 2793, "text": "The important features while designing our framework were to enable the computation of recommendations in large-scale, easy creation and extension of algorithms for different types of filtering and scenarios. Another feature is to support sparse and large datasets in a way that there is as little as possible overhead for storing data and intermediate results. Developers can choose between using one of the available recommender algorithms, combining multiple recommendations using one of the available ensemble techniques, or develop their own algorithm using the BaseRatingPrediction or BaseItemRecommendation classes. Up to the current version, the algorithms available in the framework are shown at table bellow:" }, { "code": null, "e": 3726, "s": 3512, "text": "The framework allows developers to deal with different datasets and not having to develop their own programs to execute recommender functions. The input ofalgorithms expects the data to be in a simple text format:" }, { "code": null, "e": 3751, "s": 3726, "text": "user_id item_id feedback" }, { "code": null, "e": 4139, "s": 3751, "text": "where user_id and item_id are integers referring to users and items IDs, respectively, and feedback is a number expressing how much the user likes an item or binary interaction. The separator between the values can be either spaces, tabs, or commas. If there are more than three columns, all additional columns are ignored. For example, below is a sample of data from the ML100k dataset:" }, { "code": null, "e": 4566, "s": 4139, "text": "During my studies, I also build a repository of a topic-centric public data sources in high quality for RS. They are collected and tidied from Stack Overflow, articles, recommender sites and academic experiments. Most of the datasets presented in the repository are free, having open sorce linceses, however, some are not and you need to ask permission to use or cite the authors’ work. Access this link to obtain theses data." }, { "code": null, "e": 4577, "s": 4566, "text": "github.com" }, { "code": null, "e": 4629, "s": 4577, "text": "For divide our dataset using Fold Cross Validation:" }, { "code": null, "e": 4776, "s": 4629, "text": "from caserec.utils.split_database import SplitDatabaseSplitDatabase(input_file=dataset, dir_folds=dir_path, n_splits=10).k_fold_cross_validation()" }, { "code": null, "e": 4825, "s": 4776, "text": "Run Item Recommendation Algorithm (E.g: ItemKNN)" }, { "code": null, "e": 4934, "s": 4825, "text": "from caserec.recommenders.item_recommendation.itemknn import ItemKNNItemKNN(train_file, test_file).compute()" }, { "code": null, "e": 4981, "s": 4934, "text": "Run Rating Prediction Algorithm (E.g: ItemKNN)" }, { "code": null, "e": 5088, "s": 4981, "text": "from caserec.recommenders.rating_prediction.itemknn import ItemKNNItemKNN(train_file, test_file).compute()" }, { "code": null, "e": 5152, "s": 5088, "text": "Evaluate Ranking (Prec@N, Recall@N, NDCG@, Map@N and Map Total)" }, { "code": null, "e": 5312, "s": 5152, "text": "from caserec.evaluation.item_recommendation import ItemRecommendationEvaluation ItemRecommendationEvaluation().evaluate_with_files(predictions_file, test_file)" }, { "code": null, "e": 5344, "s": 5312, "text": "Evaluate Ranking (MAE and RMSE)" }, { "code": null, "e": 5497, "s": 5344, "text": "from caserec.evaluation.rating_prediction import RatingPredictionEvaluationRatingPredictionEvaluation().evaluate_with_files(predictions_file, test_file)" }, { "code": null, "e": 5543, "s": 5497, "text": "Run ItemKNN in Fold Cross Validation Approach" }, { "code": null, "e": 5834, "s": 5543, "text": "from caserec.recommenders.item_recommendation.itemknn import ItemKNNfrom caserec.utils.cross_validation import CrossValidation## Cross Validationrecommender = ItemKNN(as_binary=True)CrossValidation(input_file=db, recommender=recommender, dir_folds=folds_path, header=1, k_folds=5).compute()" }, { "code": null, "e": 5875, "s": 5834, "text": "More examples can be found in this link." }, { "code": null, "e": 6361, "s": 5875, "text": "The goal of Case Recommender is to integrate and facilitate the experiments and development of new recommender techniques for different domains. Our framework contains a recommender engine, that contains content-based, collaborative and hybrid filtering approaches for rating prediction and item recommendation scenarios. In addition, the framework contains ensemble and clustering algorithms, validation and evaluation metrics to improve and measure the quality of the recommendation." } ]
Kali Linux - Exploitation Tools
In this chapter, we will learn about the various exploitation tools offered by Kali Linux. As we mentioned before, Metasploit is a product of Rapid7 and most of the resources can be found on their web page www.metasploit.com. It is available in two versions - commercial and free edition. The differences between these two versions is not much hence, in this case we will be using the Community version (free). As an Ethical Hacker, you will be using “Kali Ditribution” which has the Metasploit community version embedded, along with other ethical hacking tools which are very comfortable by saving time of installation. However, if you want to install as a separate tool it is an application that can be installed in the operating systems like Linux, Windows and OS X. First, open the Metasploit Console in Kali. Then, go to Applications → Exploitation Tools → Metasploit. After it starts, you will see the following screen, where the version of Metasploit is underlined in red. In the console, if you use help or ? symbol, it will show you a list with the commands of MSP along with their description. You can choose based on your needs and what you will use. Another important administration command is msfupdate which helps to update the metasploit with the latest vulnerability exploits. After running this command in the console, you will have to wait several minutes until the update is complete. It has a good command called “Search” which you can use to find what you want as shown in the following screenshot. For example, I want to find exploits related to Microsoft and the command can be msf >search name:Microsoft type:exploit. Where “search” is the command, ”name” is the name of the object that we are looking for, and “type” is what kind of script we are looking for. Another command is “info”. It provides the information regarding a module or platform where it is used, who is the author, vulnerability reference, and the payload restriction that this can have. Armitage GUI for metasploit is a complement tool for metasploit. It visualizes targets, recommends exploits, and exposes the advanced post-exploitation features. Let’s open it, but firstly metasploit console should be opened and started. To open Armitage, go to Applications → Exploit Tools → Armitage. Click the Connect button, as shown in the following screenshot. When it opens, you will see the following screen. Armitage is user friendly. The area “Targets” lists all the machines that you have discovered and you are working with, the hacked targets are red in color with a thunderstorm on it. After you have hacked the target, you can right-click on it and continue exploring with what you need to do such as exploring (browsing) the folders. In the following GUI, you will see the view for the folders, which is called console. Just by clicking the folders, you can navigate through the folders without the need of metasploit commands. On the right side of the GUI, is a section where the modules of vulnerabilities are listed. BeEF stands for Browser Exploitation Framework. It is a penetration testing tool that focuses on the web browser. BeEF allows the professional penetration tester to assess the actual security posture of a target environment using client-side attack vectors. First, you have to update the Kali package using the following commands − root@kali:/# apt-get update root@kali:/# apt-get install beef-xss To start, use the following command − root@kali:/# cd /usr/share/beef-xss root@kali:/# ./beef Open the browser and enter the username and password: beef. The BeEF hook is a JavaScript file hosted on the BeEF server that needs to run on client browsers. When it does, it calls back to the BeEF server communicating a lot of information about the target. It also allows additional commands and modules to be ran against the target. In this example, the location of BeEF hook is at http://192.168.1.101:3000/hook.js. In order to attack a browser, include the JavaScript hook in a page that the client will view. There are a number of ways to do that, however the easiest is to insert the following into a page and somehow get the client to open it. <script src = "http://192.168.1.101:3000/hook.js" type = "text/javascript"></script> Once the page loads, go back to the BeEF Control Panel and click “Online Browsers” on the top left. After a few seconds, you should see your IP address pop-up representing a hooked browser. Hovering over the IP will quickly provide information such as the browser version, operating system, and what plugins are installed. To remotely run the command, click the “Owned” host. Then, on the command click the module that you want to execute, and finally click “Execute”. It suggests possible exploits given the release version ‘uname -r’ of the Linux Operating System. To run it, type the following command − root@kali:/usr/share/linux-exploit-suggester# ./Linux_Exploit_Suggester.pl -k 3.0.0 3.0.0 is the kernel version of Linux OS that we want to exploit. 84 Lectures 6.5 hours Mohamad Mahjoub 8 Lectures 1 hours Corey Charles 21 Lectures 4 hours Atul Tiwari 55 Lectures 3 hours Musab Zayadneh 29 Lectures 2 hours Musab Zayadneh 32 Lectures 4 hours Adnaan Arbaaz Ahmed Print Add Notes Bookmark this page
[ { "code": null, "e": 2120, "s": 2029, "text": "In this chapter, we will learn about the various exploitation tools offered by Kali Linux." }, { "code": null, "e": 2440, "s": 2120, "text": "As we mentioned before, Metasploit is a product of Rapid7 and most of the resources can be found on their web page www.metasploit.com. It is available in two versions - commercial and free edition. The differences between these two versions is not much hence, in this case we will be using the Community version (free)." }, { "code": null, "e": 2799, "s": 2440, "text": "As an Ethical Hacker, you will be using “Kali Ditribution” which has the Metasploit community version embedded, along with other ethical hacking tools which are very comfortable by saving time of installation. However, if you want to install as a separate tool it is an application that can be installed in the operating systems like Linux, Windows and OS X." }, { "code": null, "e": 2903, "s": 2799, "text": "First, open the Metasploit Console in Kali. Then, go to Applications → Exploitation Tools → Metasploit." }, { "code": null, "e": 3009, "s": 2903, "text": "After it starts, you will see the following screen, where the version of Metasploit is underlined in red." }, { "code": null, "e": 3191, "s": 3009, "text": "In the console, if you use help or ? symbol, it will show you a list with the commands of MSP along with their description. You can choose based on your needs and what you will use." }, { "code": null, "e": 3433, "s": 3191, "text": "Another important administration command is msfupdate which helps to update the metasploit with the latest vulnerability exploits. After running this command in the console, you will have to wait several minutes until the update is complete." }, { "code": null, "e": 3671, "s": 3433, "text": "It has a good command called “Search” which you can use to find what you want as shown in the following screenshot. For example, I want to find exploits related to Microsoft and the command can be msf >search name:Microsoft type:exploit." }, { "code": null, "e": 3814, "s": 3671, "text": "Where “search” is the command, ”name” is the name of the object that we are looking for, and “type” is what kind of script we are looking for." }, { "code": null, "e": 4010, "s": 3814, "text": "Another command is “info”. It provides the information regarding a module or platform where it is used, who is the author, vulnerability reference, and the payload restriction that this can have." }, { "code": null, "e": 4172, "s": 4010, "text": "Armitage GUI for metasploit is a complement tool for metasploit. It visualizes targets, recommends exploits, and exposes the advanced post-exploitation features." }, { "code": null, "e": 4313, "s": 4172, "text": "Let’s open it, but firstly metasploit console should be opened and started. To open Armitage, go to Applications → Exploit Tools → Armitage." }, { "code": null, "e": 4377, "s": 4313, "text": "Click the Connect button, as shown in the following screenshot." }, { "code": null, "e": 4427, "s": 4377, "text": "When it opens, you will see the following screen." }, { "code": null, "e": 4610, "s": 4427, "text": "Armitage is user friendly. The area “Targets” lists all the machines that you have discovered and you are working with, the hacked targets are red in color with a thunderstorm on it." }, { "code": null, "e": 4760, "s": 4610, "text": "After you have hacked the target, you can right-click on it and continue exploring with what you need to do such as exploring (browsing) the folders." }, { "code": null, "e": 4954, "s": 4760, "text": "In the following GUI, you will see the view for the folders, which is called console. Just by clicking the folders, you can navigate through the folders without the need of metasploit commands." }, { "code": null, "e": 5046, "s": 4954, "text": "On the right side of the GUI, is a section where the modules of vulnerabilities are listed." }, { "code": null, "e": 5304, "s": 5046, "text": "BeEF stands for Browser Exploitation Framework. It is a penetration testing tool that focuses on the web browser. BeEF allows the professional penetration tester to assess the actual security posture of a target environment using client-side attack vectors." }, { "code": null, "e": 5378, "s": 5304, "text": "First, you have to update the Kali package using the following commands −" }, { "code": null, "e": 5448, "s": 5378, "text": "root@kali:/# apt-get update \nroot@kali:/# apt-get install beef-xss \n" }, { "code": null, "e": 5486, "s": 5448, "text": "To start, use the following command −" }, { "code": null, "e": 5546, "s": 5486, "text": "root@kali:/# cd /usr/share/beef-xss \nroot@kali:/# ./beef \n" }, { "code": null, "e": 5606, "s": 5546, "text": "Open the browser and enter the username and password: beef." }, { "code": null, "e": 5966, "s": 5606, "text": "The BeEF hook is a JavaScript file hosted on the BeEF server that needs to run on client browsers. When it does, it calls back to the BeEF server communicating a lot of information about the target. It also allows additional commands and modules to be ran against the target. In this example, the location of BeEF hook is at http://192.168.1.101:3000/hook.js." }, { "code": null, "e": 6198, "s": 5966, "text": "In order to attack a browser, include the JavaScript hook in a page that the client will view. There are a number of ways to do that, however the easiest is to insert the following into a page and somehow get the client to open it." }, { "code": null, "e": 6285, "s": 6198, "text": "<script src = \"http://192.168.1.101:3000/hook.js\" type = \"text/javascript\"></script> \n" }, { "code": null, "e": 6608, "s": 6285, "text": "Once the page loads, go back to the BeEF Control Panel and click “Online Browsers” on the top left. After a few seconds, you should see your IP address pop-up representing a hooked browser. Hovering over the IP will quickly provide information such as the browser version, operating system, and what plugins are installed." }, { "code": null, "e": 6754, "s": 6608, "text": "To remotely run the command, click the “Owned” host. Then, on the command click the module that you want to execute, and finally click “Execute”." }, { "code": null, "e": 6852, "s": 6754, "text": "It suggests possible exploits given the release version ‘uname -r’ of the Linux Operating System." }, { "code": null, "e": 6892, "s": 6852, "text": "To run it, type the following command −" }, { "code": null, "e": 6977, "s": 6892, "text": "root@kali:/usr/share/linux-exploit-suggester# ./Linux_Exploit_Suggester.pl -k 3.0.0\n" }, { "code": null, "e": 7042, "s": 6977, "text": "3.0.0 is the kernel version of Linux OS that we want to exploit." }, { "code": null, "e": 7077, "s": 7042, "text": "\n 84 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7094, "s": 7077, "text": " Mohamad Mahjoub" }, { "code": null, "e": 7126, "s": 7094, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 7141, "s": 7126, "text": " Corey Charles" }, { "code": null, "e": 7174, "s": 7141, "text": "\n 21 Lectures \n 4 hours \n" }, { "code": null, "e": 7187, "s": 7174, "text": " Atul Tiwari" }, { "code": null, "e": 7220, "s": 7187, "text": "\n 55 Lectures \n 3 hours \n" }, { "code": null, "e": 7236, "s": 7220, "text": " Musab Zayadneh" }, { "code": null, "e": 7269, "s": 7236, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 7285, "s": 7269, "text": " Musab Zayadneh" }, { "code": null, "e": 7318, "s": 7285, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 7339, "s": 7318, "text": " Adnaan Arbaaz Ahmed" }, { "code": null, "e": 7346, "s": 7339, "text": " Print" }, { "code": null, "e": 7357, "s": 7346, "text": " Add Notes" } ]
Verifying whether an element present or visible in Selenium Webdriver
We can verify whether an element is present or visible in a page with Selenium webdriver. To check the presence of an element, we can use the method – findElements. The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list. If the size is 0, it means that this element is absent from the page. int j = driver.findElements(By.id("txt")).size(); To check the visibility of an element in a page, the method isDisplayed is used. It returns a Boolean value( true is returned if the element is visible, and otherwise false). boolean t = driver.findElement(By.name("txt-val")).isDisplayed(); Code Implementation for element visible. 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 ElementVisible{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element with partial link text WebElement n =driver.findElement(By.partialLinkText("Refund")); //check if element visible boolean t = driver.findElement(By.partialLinkText("Refund")).isDisplayed(); if (t) { System.out.println("Element is dispalyed"); } else { System.out.println("Element is not dispalyed"); } driver.quit(); } } Code Implementation for element presence. 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 ElementPresence{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); //check if element present int t = driver.findElements(By.partialLinkText("Refund")).size(); if (t > 0) { System.out.println("Element is present"); }else { System.out.println("Element is not present"); } driver.quit(); } }
[ { "code": null, "e": 1227, "s": 1062, "text": "We can verify whether an element is present or visible in a page with Selenium webdriver. To check the presence of an element, we can use the method – findElements." }, { "code": null, "e": 1435, "s": 1227, "text": "The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list. If the size is 0, it means that this element is absent from the page." }, { "code": null, "e": 1485, "s": 1435, "text": "int j = driver.findElements(By.id(\"txt\")).size();" }, { "code": null, "e": 1660, "s": 1485, "text": "To check the visibility of an element in a page, the method isDisplayed is used. It returns a Boolean value( true is returned if the element is visible, and otherwise false)." }, { "code": null, "e": 1726, "s": 1660, "text": "boolean t = driver.findElement(By.name(\"txt-val\")).isDisplayed();" }, { "code": null, "e": 1767, "s": 1726, "text": "Code Implementation for element visible." }, { "code": null, "e": 2785, "s": 1767, "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 ElementVisible{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify element with partial link text\n WebElement n =driver.findElement(By.partialLinkText(\"Refund\"));\n //check if element visible\n boolean t = driver.findElement(By.partialLinkText(\"Refund\")).isDisplayed();\n if (t) {\n System.out.println(\"Element is dispalyed\");\n } else {\n System.out.println(\"Element is not dispalyed\");\n }\n driver.quit();\n }\n}" }, { "code": null, "e": 2827, "s": 2785, "text": "Code Implementation for element presence." }, { "code": null, "e": 3716, "s": 2827, "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 ElementPresence{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n //check if element present\n int t = driver.findElements(By.partialLinkText(\"Refund\")).size();\n if (t > 0) {\n System.out.println(\"Element is present\");\n }else {\n System.out.println(\"Element is not present\");\n }\n driver.quit();\n }\n}" } ]
HTML input Tag - GeeksforGeeks
09 Feb, 2021 In HTML, the input field can be specified using where a user can enter data. The input tag is used within < form> element to declare input controls that allow users to input data. An input field can be of various types depending upon the attribute type. The Input tag is an empty element which only contains attributes. For defining labels for the input element, < label> can be used. <input type = "value" .... /> type: The type attribute is used to specify the type of the input element. Its default value is text. value: The value attribute is used to specify the value of the input element. placeholder: Placeholder attribute is used to specify hint that describes the expected value of an input field. name: The name attribute is used to specify the name of the input element. alt: The alt attribute is used to provide alternate text for the user, if they cannot view the image. autofocus: Autofocus attribute specifies that an element should automatically get focus when the page loads. checked: The checked attribute specifies that an element should be pre-selected (checked) when the page loads. The checked attribute can be used with < input type=”checkbox” > and < input type=”radio” >. disabled: The disabled attribute specifies that the element should be disabled. The disabled attribute can be set to keep a user from using the < input > element until some other condition has been met. form: The form attribute is used to specify one or more forms to which the <input> element belongs to. max : The max attribute is used to specify the maximum value for an < input > element. required: The required attribute specifies that an input field must be filled out before submitting the form. readonly: The readonly attribute specifies that an input field is read-only. A read-only input field cannot be modified. A form will still submit an input field that is readonly, but will not submit an input field that is disabled. accept: This property is used to specifies the types of files that the server accepts. align: This property is used to specifies the alignment of an image input. autocomplete: This property is used to specifies whether an <input> element should have autocomplete enabled. dirname: This property is used to specifies that the text direction will be submitted. formaction: This property is used to specifies the URL of the file that will process the input control when the form is submitted (for type=”submit” and type=”image”) formenctype: This property is used to specifies how the form-data should be encoded when submitting it to the server (for type=”submit” and type=”image”) formmethod: This property is used to defines the HTTP method for sending data to the action URL (for type=”submit” and type=”image”) formnovalidate: This property is used to defines that form elements should not be validated when submitted formtarget : This property is used to specifies where to display the response that is received after submitting the form (for type=”submit” and type=”image”) height: This property is used to specifies the height of an <input> element (only for type=”image”) list: This property is used to refers to a <datalist> element that contains pre-defined options for an <input> element maxlength: This property is used to specifies the maximum number of characters allowed in an <input> element min: This property is used to specifies a minimum value for an <input> element multiple: This property is used to specifies that a user can enter more than one value in an <input> element pattern: This property is used to specifies a regular expression that an <input> element’s value is checked against size: This property is used to specifies the width, in characters, of an <input> element src: This property is used to specifies the URL of the image to use as a submit button (only for type=”image”) step: This property is used to specifies the legal number intervals for an input field width: This property is used to specifies the width of an <input> element (only for type=”image”) Example-1: Using “type” attribute. html <!DOCTYPE html><html> <body> <h1>GeeksForGeeks</h1> <form> <label>Name:</label> <input type="text" name="name" value=""> <br><br> <label>E-mail:</label> <input type="email" name="emailaddress"> <br><br> <label>Password: </label> <input type="password" name="password"> <br><br> <input type="submit"> </form></body> </html> Output: Example-2: Using “value” attribute. html <!DOCTYPE html><html> <body> <h1>GeeksForGeeks</h1> <form> <label> Name: </label> <input type="text" name="name1" value="Rahul"> <br> <br> <input type="submit" value="Submit form"> </form></body> </html> Output: Supported Browsers: Google Chrome Internet Explore Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ghoshsuman0129 HTML-DOM Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction) Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 23728, "s": 23700, "text": "\n09 Feb, 2021" }, { "code": null, "e": 24113, "s": 23728, "text": "In HTML, the input field can be specified using where a user can enter data. The input tag is used within < form> element to declare input controls that allow users to input data. An input field can be of various types depending upon the attribute type. The Input tag is an empty element which only contains attributes. For defining labels for the input element, < label> can be used." }, { "code": null, "e": 24143, "s": 24113, "text": "<input type = \"value\" .... />" }, { "code": null, "e": 24245, "s": 24143, "text": "type: The type attribute is used to specify the type of the input element. Its default value is text." }, { "code": null, "e": 24323, "s": 24245, "text": "value: The value attribute is used to specify the value of the input element." }, { "code": null, "e": 24435, "s": 24323, "text": "placeholder: Placeholder attribute is used to specify hint that describes the expected value of an input field." }, { "code": null, "e": 24510, "s": 24435, "text": "name: The name attribute is used to specify the name of the input element." }, { "code": null, "e": 24612, "s": 24510, "text": "alt: The alt attribute is used to provide alternate text for the user, if they cannot view the image." }, { "code": null, "e": 24721, "s": 24612, "text": "autofocus: Autofocus attribute specifies that an element should automatically get focus when the page loads." }, { "code": null, "e": 24925, "s": 24721, "text": "checked: The checked attribute specifies that an element should be pre-selected (checked) when the page loads. The checked attribute can be used with < input type=”checkbox” > and < input type=”radio” >." }, { "code": null, "e": 25128, "s": 24925, "text": "disabled: The disabled attribute specifies that the element should be disabled. The disabled attribute can be set to keep a user from using the < input > element until some other condition has been met." }, { "code": null, "e": 25233, "s": 25128, "text": "form: The form attribute is used to specify one or more forms to which the <input> element belongs to. " }, { "code": null, "e": 25320, "s": 25233, "text": "max : The max attribute is used to specify the maximum value for an < input > element." }, { "code": null, "e": 25432, "s": 25320, "text": "required: The required attribute specifies that an input field must be filled out before submitting the form. " }, { "code": null, "e": 25666, "s": 25432, "text": "readonly: The readonly attribute specifies that an input field is read-only. A read-only input field cannot be modified. A form will still submit an input field that is readonly, but will not submit an input field that is disabled. " }, { "code": null, "e": 25753, "s": 25666, "text": "accept: This property is used to specifies the types of files that the server accepts." }, { "code": null, "e": 25828, "s": 25753, "text": "align: This property is used to specifies the alignment of an image input." }, { "code": null, "e": 25938, "s": 25828, "text": "autocomplete: This property is used to specifies whether an <input> element should have autocomplete enabled." }, { "code": null, "e": 26025, "s": 25938, "text": "dirname: This property is used to specifies that the text direction will be submitted." }, { "code": null, "e": 26192, "s": 26025, "text": "formaction: This property is used to specifies the URL of the file that will process the input control when the form is submitted (for type=”submit” and type=”image”)" }, { "code": null, "e": 26346, "s": 26192, "text": "formenctype: This property is used to specifies how the form-data should be encoded when submitting it to the server (for type=”submit” and type=”image”)" }, { "code": null, "e": 26479, "s": 26346, "text": "formmethod: This property is used to defines the HTTP method for sending data to the action URL (for type=”submit” and type=”image”)" }, { "code": null, "e": 26586, "s": 26479, "text": "formnovalidate: This property is used to defines that form elements should not be validated when submitted" }, { "code": null, "e": 26744, "s": 26586, "text": "formtarget : This property is used to specifies where to display the response that is received after submitting the form (for type=”submit” and type=”image”)" }, { "code": null, "e": 26844, "s": 26744, "text": "height: This property is used to specifies the height of an <input> element (only for type=”image”)" }, { "code": null, "e": 26963, "s": 26844, "text": "list: This property is used to refers to a <datalist> element that contains pre-defined options for an <input> element" }, { "code": null, "e": 27072, "s": 26963, "text": "maxlength: This property is used to specifies the maximum number of characters allowed in an <input> element" }, { "code": null, "e": 27151, "s": 27072, "text": "min: This property is used to specifies a minimum value for an <input> element" }, { "code": null, "e": 27260, "s": 27151, "text": "multiple: This property is used to specifies that a user can enter more than one value in an <input> element" }, { "code": null, "e": 27376, "s": 27260, "text": "pattern: This property is used to specifies a regular expression that an <input> element’s value is checked against" }, { "code": null, "e": 27465, "s": 27376, "text": "size: This property is used to specifies the width, in characters, of an <input> element" }, { "code": null, "e": 27576, "s": 27465, "text": "src: This property is used to specifies the URL of the image to use as a submit button (only for type=”image”)" }, { "code": null, "e": 27663, "s": 27576, "text": "step: This property is used to specifies the legal number intervals for an input field" }, { "code": null, "e": 27761, "s": 27663, "text": "width: This property is used to specifies the width of an <input> element (only for type=”image”)" }, { "code": null, "e": 27798, "s": 27761, "text": "Example-1: Using “type” attribute. " }, { "code": null, "e": 27803, "s": 27798, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksForGeeks</h1> <form> <label>Name:</label> <input type=\"text\" name=\"name\" value=\"\"> <br><br> <label>E-mail:</label> <input type=\"email\" name=\"emailaddress\"> <br><br> <label>Password: </label> <input type=\"password\" name=\"password\"> <br><br> <input type=\"submit\"> </form></body> </html>", "e": 28210, "s": 27803, "text": null }, { "code": null, "e": 28220, "s": 28210, "text": "Output: " }, { "code": null, "e": 28258, "s": 28220, "text": "Example-2: Using “value” attribute. " }, { "code": null, "e": 28263, "s": 28258, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksForGeeks</h1> <form> <label> Name: </label> <input type=\"text\" name=\"name1\" value=\"Rahul\"> <br> <br> <input type=\"submit\" value=\"Submit form\"> </form></body> </html>", "e": 28513, "s": 28263, "text": null }, { "code": null, "e": 28523, "s": 28513, "text": "Output: " }, { "code": null, "e": 28545, "s": 28523, "text": "Supported Browsers: " }, { "code": null, "e": 28559, "s": 28545, "text": "Google Chrome" }, { "code": null, "e": 28576, "s": 28559, "text": "Internet Explore" }, { "code": null, "e": 28584, "s": 28576, "text": "Firefox" }, { "code": null, "e": 28590, "s": 28584, "text": "Opera" }, { "code": null, "e": 28597, "s": 28590, "text": "Safari" }, { "code": null, "e": 28736, "s": 28599, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28751, "s": 28736, "text": "ghoshsuman0129" }, { "code": null, "e": 28760, "s": 28751, "text": "HTML-DOM" }, { "code": null, "e": 28767, "s": 28760, "text": "Picked" }, { "code": null, "e": 28772, "s": 28767, "text": "HTML" }, { "code": null, "e": 28789, "s": 28772, "text": "Web Technologies" }, { "code": null, "e": 28794, "s": 28789, "text": "HTML" }, { "code": null, "e": 28892, "s": 28794, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28901, "s": 28892, "text": "Comments" }, { "code": null, "e": 28914, "s": 28901, "text": "Old Comments" }, { "code": null, "e": 28962, "s": 28914, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28999, "s": 28962, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 29049, "s": 28999, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29099, "s": 29049, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 29123, "s": 29099, "text": "REST API (Introduction)" }, { "code": null, "e": 29179, "s": 29123, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29212, "s": 29179, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29255, "s": 29212, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29316, "s": 29255, "text": "Difference between var, let and const keywords in JavaScript" } ]
Web Services with Ruby - SOAP4R
The Simple Object Access Protocol (SOAP), is a cross-platform and language-independent RPC protocol based on XML and, usually (but not necessarily) HTTP. It uses XML to encode the information that makes the remote procedure call, and HTTP to transport that information across a network from clients to servers and vice versa. SOAP has several advantages over other technologies like COM, CORBA etc: for example, its relatively cheap deployment and debugging costs, its extensibility and ease-of-use, and the existence of several implementations for different languages and platforms. Please refer to our simple tutorial SOAP to understand it in detail. This chapter makes you familiar with the SOAP implementation for Ruby (SOAP4R). This is a basic tutorial, so if you need a deep detail, you would need to refer other resources. SOAP4R is the SOAP implementation for Ruby developed by Hiroshi Nakamura and can be downloaded from − NOTE − There may be a great chance that you already have installed this component. Download SOAP If you are aware of gem utility then you can use the following command to install SOAP4R and related packages. $ gem install soap4r --include-dependencies If you are working on Windows, then you need to download a zipped file from the above location and need to install it using the standard installation method by running ruby install.rb. SOAP4R supports two different types of servers − CGI/FastCGI based (SOAP::RPC::CGIStub) Standalone (SOAP::RPC:StandaloneServer) This chapter gives detail on writing a stand alone server. The following steps are involved in writing a SOAP server. To implement your own stand alone server you need to write a new class, which will be child of SOAP::StandaloneServer as follows − class MyServer < SOAP::RPC::StandaloneServer ............... end NOTE − If you want to write a FastCGI based server then you need to take SOAP::RPC::CGIStub as parent class, rest of the procedure will remain the same. Second step is to write your Web Services methods, which you would like to expose to the outside world. They can be written as simple Ruby methods. For example, let's write two methods to add two numbers and divide two numbers − class MyServer < SOAP::RPC::StandaloneServer ............... # Handler methods def add(a, b) return a + b end def div(a, b) return a / b end end Next step is to add our defined methods to our server. The initialize method is used to expose service methods with one of the two following methods − class MyServer < SOAP::RPC::StandaloneServer def initialize(*args) add_method(receiver, methodName, *paramArg) end end Here is the description of the parameters − receiver The object that contains the methodName method. You define the service methods in the same class as the methodDef method, this parameter is self. methodName The name of the method that is called due to an RPC request. paramArg Specifies, when given, the parameter names and parameter modes. To understand the usage of inout or out parameters, consider the following service method that takes two parameters (inParam and inoutParam), returns one normal return value (retVal) and two further parameters: inoutParam and outParam − def aMeth(inParam, inoutParam) retVal = inParam + inoutParam outParam = inParam . inoutParam inoutParam = inParam * inoutParam return retVal, inoutParam, outParam end Now, we can expose this method as follows − add_method(self, 'aMeth', [ %w(in inParam), %w(inout inoutParam), %w(out outParam), %w(retval return) ]) The final step is to start your server by instantiating one instance of the derived class and calling start method. myServer = MyServer.new('ServerName', 'urn:ruby:ServiceName', hostname, port) myServer.start Here is the description of required parameters − ServerName A server name, you can give what you like most. urn:ruby:ServiceName Here urn:ruby is constant but you can give a unique ServiceName name for this server. hostname Specifies the hostname on which this server will listen. port An available port number to be used for the web service. Now, using the above steps, let us write one standalone server − require "soap/rpc/standaloneserver" begin class MyServer < SOAP::RPC::StandaloneServer # Expose our services def initialize(*args) add_method(self, 'add', 'a', 'b') add_method(self, 'div', 'a', 'b') end # Handler methods def add(a, b) return a + b end def div(a, b) return a / b end end server = MyServer.new("MyServer", 'urn:ruby:calculation', 'localhost', 8080) trap('INT){ server.shutdown } server.start rescue => err puts err.message end When executed, this server application starts a standalone SOAP server on localhost and listens for requests on port 8080. It exposes one service methods, add and div, which takes two parameters and return the result. Now, you can run this server in background as follows − $ ruby MyServer.rb& The SOAP::RPC::Driver class provides support for writing SOAP client applications. This chapter describes this class and demonstrate its usage on the basis of an application. Following is the bare minimum information you would need to call a SOAP service − The URL of the SOAP service (SOAP Endpoint URL). The namespace of the service methods (Method Namespace URI). The names of the service methods and their parameters. Now, we will write a SOAP client which would call service methods defined in above example, named add and div. Here are the main steps to create a SOAP client. We create an instance of SOAP::RPC::Driver by calling its new method as follows − SOAP::RPC::Driver.new(endPoint, nameSpace, soapAction) Here is the description of required parameters − endPoint URL of the SOAP server to connect with. nameSpace The namespace to use for all RPCs done with this SOAP::RPC::Driver object. soapAction A value for the SOAPAction field of the HTTP header. If nil this defaults to the empty string "". To add a SOAP service method to a SOAP::RPC::Driver we can call the following method using SOAP::RPC::Driver instance − driver.add_method(name, *paramArg) Here is the description of the parameters − name The name of the remote web service method. paramArg Specifies the names of the remote procedures' parameters. The final step is to invoice SOAP service using SOAP::RPC::Driver instance as follows − result = driver.serviceMethod(paramArg...) Here serviceMethod is the actual web service method and paramArg... is the list parameters required to pass in the service method. Example Based on the above steps, we will write a SOAP client as follows − #!/usr/bin/ruby -w require 'soap/rpc/driver' NAMESPACE = 'urn:ruby:calculation' URL = 'http://localhost:8080/' begin driver = SOAP::RPC::Driver.new(URL, NAMESPACE) # Add remote sevice methods driver.add_method('add', 'a', 'b') # Call remote service methods puts driver.add(20, 30) rescue => err puts err.message end I have explained you just very basic concepts of Web Services with Ruby. If you want to drill down it further, then there is following link to find more details on Web Services with Ruby. 46 Lectures 9.5 hours Eduonix Learning Solutions 97 Lectures 7.5 hours Skillbakerystudios 227 Lectures 40 hours YouAccel 19 Lectures 10 hours Programming Line 51 Lectures 5 hours Stone River ELearning 39 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2448, "s": 2294, "text": "The Simple Object Access Protocol (SOAP), is a cross-platform and language-independent RPC protocol based on XML and, usually (but not necessarily) HTTP." }, { "code": null, "e": 2620, "s": 2448, "text": "It uses XML to encode the information that makes the remote procedure call, and HTTP to transport that information across a network from clients to servers and vice versa." }, { "code": null, "e": 2878, "s": 2620, "text": "SOAP has several advantages over other technologies like COM, CORBA etc: for example, its relatively cheap deployment and debugging costs, its extensibility and ease-of-use, and the existence of several implementations for different languages and platforms." }, { "code": null, "e": 2947, "s": 2878, "text": "Please refer to our simple tutorial SOAP to understand it in detail." }, { "code": null, "e": 3124, "s": 2947, "text": "This chapter makes you familiar with the SOAP implementation for Ruby (SOAP4R). This is a basic tutorial, so if you need a deep detail, you would need to refer other resources." }, { "code": null, "e": 3226, "s": 3124, "text": "SOAP4R is the SOAP implementation for Ruby developed by Hiroshi Nakamura and can be downloaded from −" }, { "code": null, "e": 3309, "s": 3226, "text": "NOTE − There may be a great chance that you already have installed this component." }, { "code": null, "e": 3324, "s": 3309, "text": "Download SOAP\n" }, { "code": null, "e": 3435, "s": 3324, "text": "If you are aware of gem utility then you can use the following command to install SOAP4R and related packages." }, { "code": null, "e": 3480, "s": 3435, "text": "$ gem install soap4r --include-dependencies\n" }, { "code": null, "e": 3665, "s": 3480, "text": "If you are working on Windows, then you need to download a zipped file from the above location and need to install it using the standard installation method by running ruby install.rb." }, { "code": null, "e": 3714, "s": 3665, "text": "SOAP4R supports two different types of servers −" }, { "code": null, "e": 3753, "s": 3714, "text": "CGI/FastCGI based (SOAP::RPC::CGIStub)" }, { "code": null, "e": 3793, "s": 3753, "text": "Standalone (SOAP::RPC:StandaloneServer)" }, { "code": null, "e": 3911, "s": 3793, "text": "This chapter gives detail on writing a stand alone server. The following steps are involved in writing a SOAP server." }, { "code": null, "e": 4042, "s": 3911, "text": "To implement your own stand alone server you need to write a new class, which will be child of SOAP::StandaloneServer as follows −" }, { "code": null, "e": 4109, "s": 4042, "text": "class MyServer < SOAP::RPC::StandaloneServer\n ...............\nend" }, { "code": null, "e": 4262, "s": 4109, "text": "NOTE − If you want to write a FastCGI based server then you need to take SOAP::RPC::CGIStub as parent class, rest of the procedure will remain the same." }, { "code": null, "e": 4366, "s": 4262, "text": "Second step is to write your Web Services methods, which you would like to expose to the outside world." }, { "code": null, "e": 4491, "s": 4366, "text": "They can be written as simple Ruby methods. For example, let's write two methods to add two numbers and divide two numbers −" }, { "code": null, "e": 4669, "s": 4491, "text": "class MyServer < SOAP::RPC::StandaloneServer\n ...............\n\n # Handler methods\n def add(a, b)\n return a + b\n end\n def div(a, b) \n return a / b \n end\nend" }, { "code": null, "e": 4820, "s": 4669, "text": "Next step is to add our defined methods to our server. The initialize method is used to expose service methods with one of the two following methods −" }, { "code": null, "e": 4951, "s": 4820, "text": "class MyServer < SOAP::RPC::StandaloneServer\n def initialize(*args)\n add_method(receiver, methodName, *paramArg)\n end\nend" }, { "code": null, "e": 4995, "s": 4951, "text": "Here is the description of the parameters −" }, { "code": null, "e": 5004, "s": 4995, "text": "receiver" }, { "code": null, "e": 5150, "s": 5004, "text": "The object that contains the methodName method. You define the service methods in the same class as the methodDef method, this parameter is self." }, { "code": null, "e": 5161, "s": 5150, "text": "methodName" }, { "code": null, "e": 5222, "s": 5161, "text": "The name of the method that is called due to an RPC request." }, { "code": null, "e": 5231, "s": 5222, "text": "paramArg" }, { "code": null, "e": 5295, "s": 5231, "text": "Specifies, when given, the parameter names and parameter modes." }, { "code": null, "e": 5532, "s": 5295, "text": "To understand the usage of inout or out parameters, consider the following service method that takes two parameters (inParam and inoutParam), returns one normal return value (retVal) and two further parameters: inoutParam and outParam −" }, { "code": null, "e": 5711, "s": 5532, "text": "def aMeth(inParam, inoutParam)\n retVal = inParam + inoutParam\n outParam = inParam . inoutParam\n inoutParam = inParam * inoutParam\n return retVal, inoutParam, outParam\nend" }, { "code": null, "e": 5755, "s": 5711, "text": "Now, we can expose this method as follows −" }, { "code": null, "e": 5872, "s": 5755, "text": "add_method(self, 'aMeth', [\n %w(in inParam),\n %w(inout inoutParam),\n %w(out outParam),\n %w(retval return)\n])" }, { "code": null, "e": 5988, "s": 5872, "text": "The final step is to start your server by instantiating one instance of the derived class and calling start method." }, { "code": null, "e": 6082, "s": 5988, "text": "myServer = MyServer.new('ServerName', 'urn:ruby:ServiceName', hostname, port)\n\nmyServer.start" }, { "code": null, "e": 6131, "s": 6082, "text": "Here is the description of required parameters −" }, { "code": null, "e": 6142, "s": 6131, "text": "ServerName" }, { "code": null, "e": 6190, "s": 6142, "text": "A server name, you can give what you like most." }, { "code": null, "e": 6211, "s": 6190, "text": "urn:ruby:ServiceName" }, { "code": null, "e": 6297, "s": 6211, "text": "Here urn:ruby is constant but you can give a unique ServiceName name for this server." }, { "code": null, "e": 6306, "s": 6297, "text": "hostname" }, { "code": null, "e": 6363, "s": 6306, "text": "Specifies the hostname on which this server will listen." }, { "code": null, "e": 6368, "s": 6363, "text": "port" }, { "code": null, "e": 6425, "s": 6368, "text": "An available port number to be used for the web service." }, { "code": null, "e": 6490, "s": 6425, "text": "Now, using the above steps, let us write one standalone server −" }, { "code": null, "e": 7058, "s": 6490, "text": "require \"soap/rpc/standaloneserver\"\n\nbegin\n class MyServer < SOAP::RPC::StandaloneServer\n\n # Expose our services\n def initialize(*args)\n add_method(self, 'add', 'a', 'b')\n add_method(self, 'div', 'a', 'b')\n end\n\n # Handler methods\n def add(a, b)\n return a + b\n end\n def div(a, b) \n return a / b \n end\nend\n server = MyServer.new(\"MyServer\", \n 'urn:ruby:calculation', 'localhost', 8080)\n trap('INT){\n server.shutdown\n }\n server.start\nrescue => err\n puts err.message\nend" }, { "code": null, "e": 7276, "s": 7058, "text": "When executed, this server application starts a standalone SOAP server on localhost and listens for requests on port 8080. It exposes one service methods, add and div, which takes two parameters and return the result." }, { "code": null, "e": 7332, "s": 7276, "text": "Now, you can run this server in background as follows −" }, { "code": null, "e": 7353, "s": 7332, "text": "$ ruby MyServer.rb&\n" }, { "code": null, "e": 7528, "s": 7353, "text": "The SOAP::RPC::Driver class provides support for writing SOAP client applications. This chapter describes this class and demonstrate its usage on the basis of an application." }, { "code": null, "e": 7610, "s": 7528, "text": "Following is the bare minimum information you would need to call a SOAP service −" }, { "code": null, "e": 7659, "s": 7610, "text": "The URL of the SOAP service (SOAP Endpoint URL)." }, { "code": null, "e": 7720, "s": 7659, "text": "The namespace of the service methods (Method Namespace URI)." }, { "code": null, "e": 7775, "s": 7720, "text": "The names of the service methods and their parameters." }, { "code": null, "e": 7886, "s": 7775, "text": "Now, we will write a SOAP client which would call service methods defined in above example, named add and div." }, { "code": null, "e": 7935, "s": 7886, "text": "Here are the main steps to create a SOAP client." }, { "code": null, "e": 8017, "s": 7935, "text": "We create an instance of SOAP::RPC::Driver by calling its new method as follows −" }, { "code": null, "e": 8072, "s": 8017, "text": "SOAP::RPC::Driver.new(endPoint, nameSpace, soapAction)" }, { "code": null, "e": 8121, "s": 8072, "text": "Here is the description of required parameters −" }, { "code": null, "e": 8130, "s": 8121, "text": "endPoint" }, { "code": null, "e": 8170, "s": 8130, "text": "URL of the SOAP server to connect with." }, { "code": null, "e": 8180, "s": 8170, "text": "nameSpace" }, { "code": null, "e": 8255, "s": 8180, "text": "The namespace to use for all RPCs done with this SOAP::RPC::Driver object." }, { "code": null, "e": 8266, "s": 8255, "text": "soapAction" }, { "code": null, "e": 8364, "s": 8266, "text": "A value for the SOAPAction field of the HTTP header. If nil this defaults to the empty string \"\"." }, { "code": null, "e": 8484, "s": 8364, "text": "To add a SOAP service method to a SOAP::RPC::Driver we can call the following method using SOAP::RPC::Driver instance −" }, { "code": null, "e": 8519, "s": 8484, "text": "driver.add_method(name, *paramArg)" }, { "code": null, "e": 8563, "s": 8519, "text": "Here is the description of the parameters −" }, { "code": null, "e": 8568, "s": 8563, "text": "name" }, { "code": null, "e": 8611, "s": 8568, "text": "The name of the remote web service method." }, { "code": null, "e": 8620, "s": 8611, "text": "paramArg" }, { "code": null, "e": 8678, "s": 8620, "text": "Specifies the names of the remote procedures' parameters." }, { "code": null, "e": 8766, "s": 8678, "text": "The final step is to invoice SOAP service using SOAP::RPC::Driver instance as follows −" }, { "code": null, "e": 8809, "s": 8766, "text": "result = driver.serviceMethod(paramArg...)" }, { "code": null, "e": 8940, "s": 8809, "text": "Here serviceMethod is the actual web service method and paramArg... is the list parameters required to pass in the service method." }, { "code": null, "e": 8948, "s": 8940, "text": "Example" }, { "code": null, "e": 9015, "s": 8948, "text": "Based on the above steps, we will write a SOAP client as follows −" }, { "code": null, "e": 9357, "s": 9015, "text": "#!/usr/bin/ruby -w\n\nrequire 'soap/rpc/driver'\n\nNAMESPACE = 'urn:ruby:calculation'\nURL = 'http://localhost:8080/'\n\nbegin\n driver = SOAP::RPC::Driver.new(URL, NAMESPACE)\n \n # Add remote sevice methods\n driver.add_method('add', 'a', 'b')\n\n # Call remote service methods\n puts driver.add(20, 30)\nrescue => err\n puts err.message\nend" }, { "code": null, "e": 9545, "s": 9357, "text": "I have explained you just very basic concepts of Web Services with Ruby. If you want to drill down it further, then there is following link to find more details on Web Services with Ruby." }, { "code": null, "e": 9580, "s": 9545, "text": "\n 46 Lectures \n 9.5 hours \n" }, { "code": null, "e": 9608, "s": 9580, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9643, "s": 9608, "text": "\n 97 Lectures \n 7.5 hours \n" }, { "code": null, "e": 9663, "s": 9643, "text": " Skillbakerystudios" }, { "code": null, "e": 9698, "s": 9663, "text": "\n 227 Lectures \n 40 hours \n" }, { "code": null, "e": 9708, "s": 9698, "text": " YouAccel" }, { "code": null, "e": 9742, "s": 9708, "text": "\n 19 Lectures \n 10 hours \n" }, { "code": null, "e": 9760, "s": 9742, "text": " Programming Line" }, { "code": null, "e": 9793, "s": 9760, "text": "\n 51 Lectures \n 5 hours \n" }, { "code": null, "e": 9816, "s": 9793, "text": " Stone River ELearning" }, { "code": null, "e": 9851, "s": 9816, "text": "\n 39 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9874, "s": 9851, "text": " Stone River ELearning" }, { "code": null, "e": 9881, "s": 9874, "text": " Print" }, { "code": null, "e": 9892, "s": 9881, "text": " Add Notes" } ]
HTML | Marquee behavior attribute - GeeksforGeeks
09 Feb, 2022 The Marquee behavior attribute in HTML is used to set the behavior of scrolling. The default value is scroll.Syntax: <marquee behavior=slide > Attribute value: alternate: It defines that text moving to the end and then starting in the opposite direction. scroll: It has a default value. specify the text scrolls to the end and starts over. slide: It specifies the text moving to the end and then stops it. Example: html <!DOCTYPE html><html> <head> <title>HTML Marquee behavior attribute</title> <style> .main { text-align: center; } .marq { padding-top: 30px; padding-bottom: 30px; } </style></head> <body> <h1 style="color:green; text-align:center;">GeeksforGeeks</h1> <div class="main"> <marquee class="marq" bgcolor="Green" direction="left" behavior=scroll loop=""> Scroll </marquee> <marquee class="marq" bgcolor="Green" behavior=alternate direction="left" loop=""> Alternate </marquee> </div></body> </html> Output: Supported Browsers: The browsers supported by HTML Marquee behavior attribute are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to update Node.js and NPM to next version ? How to Insert Form Data into Database using PHP ? REST API (Introduction) Types of CSS (Cascading Style Sheet) Form validation using HTML and JavaScript Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 24172, "s": 24144, "text": "\n09 Feb, 2022" }, { "code": null, "e": 24291, "s": 24172, "text": "The Marquee behavior attribute in HTML is used to set the behavior of scrolling. The default value is scroll.Syntax: " }, { "code": null, "e": 24317, "s": 24291, "text": "<marquee behavior=slide >" }, { "code": null, "e": 24335, "s": 24317, "text": "Attribute value: " }, { "code": null, "e": 24430, "s": 24335, "text": "alternate: It defines that text moving to the end and then starting in the opposite direction." }, { "code": null, "e": 24516, "s": 24430, "text": "scroll: It has a default value. specify the text scrolls to the end and starts over." }, { "code": null, "e": 24582, "s": 24516, "text": "slide: It specifies the text moving to the end and then stops it." }, { "code": null, "e": 24593, "s": 24582, "text": "Example: " }, { "code": null, "e": 24598, "s": 24593, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML Marquee behavior attribute</title> <style> .main { text-align: center; } .marq { padding-top: 30px; padding-bottom: 30px; } </style></head> <body> <h1 style=\"color:green; text-align:center;\">GeeksforGeeks</h1> <div class=\"main\"> <marquee class=\"marq\" bgcolor=\"Green\" direction=\"left\" behavior=scroll loop=\"\"> Scroll </marquee> <marquee class=\"marq\" bgcolor=\"Green\" behavior=alternate direction=\"left\" loop=\"\"> Alternate </marquee> </div></body> </html>", "e": 25358, "s": 24598, "text": null }, { "code": null, "e": 25368, "s": 25358, "text": "Output: " }, { "code": null, "e": 25466, "s": 25368, "text": "Supported Browsers: The browsers supported by HTML Marquee behavior attribute are listed below: " }, { "code": null, "e": 25480, "s": 25466, "text": "Google Chrome" }, { "code": null, "e": 25498, "s": 25480, "text": "Internet Explorer" }, { "code": null, "e": 25506, "s": 25498, "text": "Firefox" }, { "code": null, "e": 25519, "s": 25506, "text": "Apple Safari" }, { "code": null, "e": 25525, "s": 25519, "text": "Opera" }, { "code": null, "e": 25664, "s": 25527, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 25678, "s": 25664, "text": "ManasChhabra2" }, { "code": null, "e": 25698, "s": 25678, "text": "hritikbhatnagar2182" }, { "code": null, "e": 25714, "s": 25698, "text": "HTML-Attributes" }, { "code": null, "e": 25719, "s": 25714, "text": "HTML" }, { "code": null, "e": 25736, "s": 25719, "text": "Web Technologies" }, { "code": null, "e": 25741, "s": 25736, "text": "HTML" }, { "code": null, "e": 25839, "s": 25741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25848, "s": 25839, "text": "Comments" }, { "code": null, "e": 25861, "s": 25848, "text": "Old Comments" }, { "code": null, "e": 25909, "s": 25861, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25959, "s": 25909, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 25983, "s": 25959, "text": "REST API (Introduction)" }, { "code": null, "e": 26020, "s": 25983, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 26062, "s": 26020, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 26104, "s": 26062, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26137, "s": 26104, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26180, "s": 26137, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26225, "s": 26180, "text": "Convert a string to an integer in JavaScript" } ]
Data visualization with Python Using Seaborn and Plotly_ GDP per Capita & Life Expectency Dataset | by Fatima Zahra Iazza | Towards Data Science
This tutorial is intended to help you get up-and-running with python data visualization libraries very quickly. I choose seaborn and plotly that is the most used and awesome tools to visualize fully-interactive plots and make data looking great. Also you will get to discover the relationship between economy and social factors. The dataset we would be dealing with in this illustration is GDP per Capita, Social support, Healthy life expectancy, Freedom to make choices, Generosity... in all over the world. I use jupyter notebook that you can get access from Anaconda packages. If you want to install Anaconda here. Seaborn is a visualization library based on matplotlib, it works very well with pandas library. One of the reasons to use seaborn is that it produces beautiful statistical plots. It is very important to realize that seaborn is a complement and not a substitute to matplotlib. To install seaborn, you can use pip or conda at your command line or terminal with: !pip install seabornor!conda install seaborn Import libraries Import libraries Let us begin by importing few libraries, numpy (numerical python library), pandas for dataframe and dataseries, seaborn and matplotlib for visualization. import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline #use it to show plot directly below the code 2. Read data using pandas This data called ‘2019.csv’ in format csv file. that is the dataset that we gonna work with throughout this tutorial. head() function return top 5 rows of dataframe as we can see below: df= pd.read_csv('2019.csv')df.head() 1.distplot: What i do here is simply plot a distribution of a single column in a dataframe (GDP per capita) using sns.distplot(dataofsinglecolumn). To remove kernal density estimation plot you can use kde=False. bins=30 represents the number of bins that define the shape of the histogram, i use 8 bins in the left plot and 30 for the other so you can see the difference. sns.distplot(df['GDP per capita'], bins=8) out[5]sns.distplot(df['GDP per capita'], kde = False , bins = 30)out[6] 2.jointplot: Seaborn’s jointplot displays a relationship between two variables. Here shows plots of the two columns x and y in data using scatter plot and histogram. sns.jointplot(x=df['GDP per capita'], y= df['Healthy life expectancy'],data=df) #two ditribution here below you can add kind of plot to draw, example kind=’reg’ means draw scatter plot with regression line, and kind=’hex’ that bins the data into hexagons with histogram in the margins. You can see here that GDP per capita and Healthy life expectancy are positive lineary correlated. means if GDP per capita is high, Healthy life expectancy would be high too. sns.jointplot(x=df['GDP per capita'], y= df['Healthy life expectancy'],data=df,kind='reg') #plot in the right sidens.jointplot(x=df['GDP per capita'], y= df['Healthy life expectancy'],data=df,kind='hex') # plot in the left sns.pairplot(df)#relationship entire datasets It is amazing that one simple line of code gives us this entire plot! This represent the relationship between the entire dataset. The histogram allow us to see the distribution of a single variable while scatter plots show the relationship between two variables. barplot is used to plot categorical variable example sex male/female... here i use country as category and plot GDP per capita of top 3 countries using head() function. sns.barplot(x=df['Country or region'].head(3),y=df['GDP per capita'],data=df) What i do here is select 4 columns of the data and use corr() function to find correlation between the data that have been selected. # Matrix form for correlation datadata_select = df[['GDP per capita','Social support','Healthy life expectancy','Perceptions of corruption']]data_select.corr() you can see here a matrix form that indicates some sort of values which represent the level of correlation, that level range in general from -1 to 1. if corr value approches to 1, that means variables have strong positive correlation. sns.heatmap(df_select.corr(), cmap='coolwarm') here what heatmap really does is represent the data correlation values as colors in the gragh based on some sort of gradient scale: you can change color map by adding cmap= ‘...’ , example ‘Greens’ , ‘Blues’, ‘coolwarm’...For all the colormaps, check out: http://matplotlib.org/users/colormaps.html Plotly is a data visualization library that you can use to create different types of interactive charts, maps and plots.. here plotly website The first thing you can do is to install plotly and cufflinks libraries. cufflinks connects plotly with pandas, you can’t make plot from dataframe unless cufflinks installed. !pip install plotly!pip install cufflinks To connect with chart_studio, you can go to home page plotly to sign up and get your api_key in settings account. Since plotly is an online platform, login credential must be introduced in order to use it in online mode. chart_studio.tools.set_credentials_file(username='XXXX, api_key='xxxxxxxxxx') Below import plotly and cufflinks on jupyter notebook, also chart_studio, plotly tools and graph object. cf.go_offline()cf.set_config_file(offline =False , world_readable= True) In this article we will use online mode which is quite enough for Jupyter Notebook usage. First i select two columns in dataset; Healthy life expectancy and GDP per capita, then i create a dictionary for title name and xaxis / yaxis names and put them in layout object. I use dict() function for example; dict(a=8, b=10) instead of {“a”: 8, “b”: 10 } To plot the dataframe as a line chart all you have to do is call iplot method of the dataframe object. cufflinks and plotly allow to plot data using the syntax data.iplot, then pass in a filename and layout created. data= df[['Healthy life expectancy', 'GDP per capita']]layout = dict(title = 'Line Chart From Pandas DataFrame', xaxis= dict(title='x-axis'), yaxis= dict(title='y-axis'))data.iplot(filename='cf-simple-line-chart', layout=layout) the mode parameter should always be set to “markers” , by default plotly will draw lines between data points. So if you want the points with no lines, you need to make sure to set plot mode as a markers. Just like the previous example, we need a fig object, it should be a dictionary object that contain two dictionaries one for data and one for layout. In the data dictionary we define two sets of x and y variables to be plotted, in both plots the x variable will be the same, this allows to compare GDP per capita and Healthy life expectancy relate with countries column. Then i create data object that contains both data1 and data2 using data.go syntax, and assign to mydata variable. Also create the layout object and pass in the title of scatter plot. data1=go.Scatter(x=df['Country or region'],y=df['GDP per capita'], name="GDP per capita", mode="markers") data2=go.Scatter(x=df['Country or region'],y=df['Healthy life expectancy'],name="Healthy life expectancy",mode="markers")mydata = go.Data([data1, data2])mylayout = go.Layout( title="GDP per capita vs. Life expectancy")fig = go.Figure(data=mydata, layout=mylayout)chart_studio.plotly.iplot(fig) There we go our plot using chart_studio package! Here the same code but i use mode=”lines + markers” , it will be connect data points as lines and at the same time shows the scatter plot. Here shows how to customize colors in plotly. Here we need to use a dictionary object called color_theme and we gonna generate a list color that contains the RGBA codes for the colors we want to use in our bar chart. color_theme = dict(color=['rgba(169,169,169,1)', 'rgba(255,160,122,1)','rgba(176,224,230,1)', 'rgba(255,228,196,1)', 'rgba(189,183,107,1)', 'rgba(188,143,143,1)','rgba(221,160,221,1)']) Now i will show you how to create Bar charts using plotly . Here we use trace object to specify what kind of chart we want. So in this case we use go.Bar() function then we pass in two variables x and y that represent respectively the 7 countries on the head of data and Healthy life expectancy, also pass in the color_theme that we’ve already defined. Now let’s specify our layout parameters, in this code i use just one parameter to name the title of our plot you can add x-axis and y-axis names. Finally plot this using iplot() function and then pass in our data. trace0 = go.Bar(x=df['Country or region'].head(7), y=df['Healthy life expectancy'], marker=color_theme)data = [trace0]layout = go.Layout(title='Healthy life expectancy')fig = go.Figure(data=data, layout=layout)chart_studio.plotly.iplot(fig, filename='color-bar-chart') Box plot usued usually in statistics, it gives us more information on how data spread out by measure median, mean and mode of the dataset. In the code below we just select 2 columns of our data, then we use iplot method and pass in an argument to specify the kind of plot, then we give file name of our boxplot. df_select = df[['GDP per capita','Healthy life expectancy']] df_select.iplot(kind='box', filename='box-plot') Here i create a simple pie chart using the index of 10 countries as labels, and plot the GDP per capita values for each country. Then create a gragh object using go.Pie() and fill in labels and values variables. finally plot this using iplot()function. labels = df['Country or region'].head(10).value_counts().indexvalues = df['GDP per capita'].head(10).valuestrace = go.Pie(labels=labels, values=values)chart_studio.plotly.iplot([trace], filename='basic_pie_chart') Using plotly is the simplest way to generate maps in python. We have two main types of plotly mapping objects; data object and layout object. First we need data to pass in a dictionary and set parameters for the data in our map. Let’s start by passing choropleth type, this means what type of map we want plotly to generate. Then define our colorscale and reverse the scale to have yellow down and violet up the scale. We set locations as countries in the dataframe, and z variable that is represented by the colors in the map. Lastly we gonna pass in the text argument to define the text that is displayed when you move over the map. Second create a layout dictionary to set title of our map. Then create a new dictionary that contains data and layout objects we call it fig. To plot this we just gonna call iplot method on our fig object and then give in a file name. Here we go... data = dict( type = 'choropleth', colorscale = 'Viridis', reversescale = True, locations = df['Country or region'], locationmode = "country names", z = df['GDP per capita'], text = df['Country or region'], colorbar = {'title' : 'GDP per capita_world'}, ) layout=dict(title_text = '2019 GDP per capita by State')fig = go.Figure(data=data,layout=layout) chart_studio.plotly.iplot(fig, filename='choropleth') Data visualization is a great tool to get data more readable and make a huge chance for you to discover more insights in the real world. All of the code for this article is available on GitHub . The charts are all interactive and can be viewed on plotly here. I welcome feedback . I can be reached on Linkedin here.
[ { "code": null, "e": 417, "s": 171, "text": "This tutorial is intended to help you get up-and-running with python data visualization libraries very quickly. I choose seaborn and plotly that is the most used and awesome tools to visualize fully-interactive plots and make data looking great." }, { "code": null, "e": 680, "s": 417, "text": "Also you will get to discover the relationship between economy and social factors. The dataset we would be dealing with in this illustration is GDP per Capita, Social support, Healthy life expectancy, Freedom to make choices, Generosity... in all over the world." }, { "code": null, "e": 751, "s": 680, "text": "I use jupyter notebook that you can get access from Anaconda packages." }, { "code": null, "e": 789, "s": 751, "text": "If you want to install Anaconda here." }, { "code": null, "e": 885, "s": 789, "text": "Seaborn is a visualization library based on matplotlib, it works very well with pandas library." }, { "code": null, "e": 1065, "s": 885, "text": "One of the reasons to use seaborn is that it produces beautiful statistical plots. It is very important to realize that seaborn is a complement and not a substitute to matplotlib." }, { "code": null, "e": 1149, "s": 1065, "text": "To install seaborn, you can use pip or conda at your command line or terminal with:" }, { "code": null, "e": 1194, "s": 1149, "text": "!pip install seabornor!conda install seaborn" }, { "code": null, "e": 1211, "s": 1194, "text": "Import libraries" }, { "code": null, "e": 1228, "s": 1211, "text": "Import libraries" }, { "code": null, "e": 1382, "s": 1228, "text": "Let us begin by importing few libraries, numpy (numerical python library), pandas for dataframe and dataseries, seaborn and matplotlib for visualization." }, { "code": null, "e": 1536, "s": 1382, "text": "import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline #use it to show plot directly below the code " }, { "code": null, "e": 1562, "s": 1536, "text": "2. Read data using pandas" }, { "code": null, "e": 1680, "s": 1562, "text": "This data called ‘2019.csv’ in format csv file. that is the dataset that we gonna work with throughout this tutorial." }, { "code": null, "e": 1748, "s": 1680, "text": "head() function return top 5 rows of dataframe as we can see below:" }, { "code": null, "e": 1785, "s": 1748, "text": "df= pd.read_csv('2019.csv')df.head()" }, { "code": null, "e": 1797, "s": 1785, "text": "1.distplot:" }, { "code": null, "e": 1933, "s": 1797, "text": "What i do here is simply plot a distribution of a single column in a dataframe (GDP per capita) using sns.distplot(dataofsinglecolumn)." }, { "code": null, "e": 1997, "s": 1933, "text": "To remove kernal density estimation plot you can use kde=False." }, { "code": null, "e": 2157, "s": 1997, "text": "bins=30 represents the number of bins that define the shape of the histogram, i use 8 bins in the left plot and 30 for the other so you can see the difference." }, { "code": null, "e": 2272, "s": 2157, "text": "sns.distplot(df['GDP per capita'], bins=8) out[5]sns.distplot(df['GDP per capita'], kde = False , bins = 30)out[6]" }, { "code": null, "e": 2285, "s": 2272, "text": "2.jointplot:" }, { "code": null, "e": 2352, "s": 2285, "text": "Seaborn’s jointplot displays a relationship between two variables." }, { "code": null, "e": 2438, "s": 2352, "text": "Here shows plots of the two columns x and y in data using scatter plot and histogram." }, { "code": null, "e": 2535, "s": 2438, "text": "sns.jointplot(x=df['GDP per capita'], y= df['Healthy life expectancy'],data=df) #two ditribution" }, { "code": null, "e": 2724, "s": 2535, "text": "here below you can add kind of plot to draw, example kind=’reg’ means draw scatter plot with regression line, and kind=’hex’ that bins the data into hexagons with histogram in the margins." }, { "code": null, "e": 2898, "s": 2724, "text": "You can see here that GDP per capita and Healthy life expectancy are positive lineary correlated. means if GDP per capita is high, Healthy life expectancy would be high too." }, { "code": null, "e": 3121, "s": 2898, "text": "sns.jointplot(x=df['GDP per capita'], y= df['Healthy life expectancy'],data=df,kind='reg') #plot in the right sidens.jointplot(x=df['GDP per capita'], y= df['Healthy life expectancy'],data=df,kind='hex') # plot in the left" }, { "code": null, "e": 3167, "s": 3121, "text": "sns.pairplot(df)#relationship entire datasets" }, { "code": null, "e": 3237, "s": 3167, "text": "It is amazing that one simple line of code gives us this entire plot!" }, { "code": null, "e": 3430, "s": 3237, "text": "This represent the relationship between the entire dataset. The histogram allow us to see the distribution of a single variable while scatter plots show the relationship between two variables." }, { "code": null, "e": 3502, "s": 3430, "text": "barplot is used to plot categorical variable example sex male/female..." }, { "code": null, "e": 3599, "s": 3502, "text": "here i use country as category and plot GDP per capita of top 3 countries using head() function." }, { "code": null, "e": 3677, "s": 3599, "text": "sns.barplot(x=df['Country or region'].head(3),y=df['GDP per capita'],data=df)" }, { "code": null, "e": 3810, "s": 3677, "text": "What i do here is select 4 columns of the data and use corr() function to find correlation between the data that have been selected." }, { "code": null, "e": 3970, "s": 3810, "text": "# Matrix form for correlation datadata_select = df[['GDP per capita','Social support','Healthy life expectancy','Perceptions of corruption']]data_select.corr()" }, { "code": null, "e": 4120, "s": 3970, "text": "you can see here a matrix form that indicates some sort of values which represent the level of correlation, that level range in general from -1 to 1." }, { "code": null, "e": 4205, "s": 4120, "text": "if corr value approches to 1, that means variables have strong positive correlation." }, { "code": null, "e": 4252, "s": 4205, "text": "sns.heatmap(df_select.corr(), cmap='coolwarm')" }, { "code": null, "e": 4384, "s": 4252, "text": "here what heatmap really does is represent the data correlation values as colors in the gragh based on some sort of gradient scale:" }, { "code": null, "e": 4551, "s": 4384, "text": "you can change color map by adding cmap= ‘...’ , example ‘Greens’ , ‘Blues’, ‘coolwarm’...For all the colormaps, check out: http://matplotlib.org/users/colormaps.html" }, { "code": null, "e": 4673, "s": 4551, "text": "Plotly is a data visualization library that you can use to create different types of interactive charts, maps and plots.." }, { "code": null, "e": 4693, "s": 4673, "text": "here plotly website" }, { "code": null, "e": 4766, "s": 4693, "text": "The first thing you can do is to install plotly and cufflinks libraries." }, { "code": null, "e": 4868, "s": 4766, "text": "cufflinks connects plotly with pandas, you can’t make plot from dataframe unless cufflinks installed." }, { "code": null, "e": 4910, "s": 4868, "text": "!pip install plotly!pip install cufflinks" }, { "code": null, "e": 5024, "s": 4910, "text": "To connect with chart_studio, you can go to home page plotly to sign up and get your api_key in settings account." }, { "code": null, "e": 5131, "s": 5024, "text": "Since plotly is an online platform, login credential must be introduced in order to use it in online mode." }, { "code": null, "e": 5209, "s": 5131, "text": "chart_studio.tools.set_credentials_file(username='XXXX, api_key='xxxxxxxxxx')" }, { "code": null, "e": 5314, "s": 5209, "text": "Below import plotly and cufflinks on jupyter notebook, also chart_studio, plotly tools and graph object." }, { "code": null, "e": 5387, "s": 5314, "text": "cf.go_offline()cf.set_config_file(offline =False , world_readable= True)" }, { "code": null, "e": 5477, "s": 5387, "text": "In this article we will use online mode which is quite enough for Jupyter Notebook usage." }, { "code": null, "e": 5657, "s": 5477, "text": "First i select two columns in dataset; Healthy life expectancy and GDP per capita, then i create a dictionary for title name and xaxis / yaxis names and put them in layout object." }, { "code": null, "e": 5738, "s": 5657, "text": "I use dict() function for example; dict(a=8, b=10) instead of {“a”: 8, “b”: 10 }" }, { "code": null, "e": 5841, "s": 5738, "text": "To plot the dataframe as a line chart all you have to do is call iplot method of the dataframe object." }, { "code": null, "e": 5954, "s": 5841, "text": "cufflinks and plotly allow to plot data using the syntax data.iplot, then pass in a filename and layout created." }, { "code": null, "e": 6183, "s": 5954, "text": "data= df[['Healthy life expectancy', 'GDP per capita']]layout = dict(title = 'Line Chart From Pandas DataFrame', xaxis= dict(title='x-axis'), yaxis= dict(title='y-axis'))data.iplot(filename='cf-simple-line-chart', layout=layout)" }, { "code": null, "e": 6387, "s": 6183, "text": "the mode parameter should always be set to “markers” , by default plotly will draw lines between data points. So if you want the points with no lines, you need to make sure to set plot mode as a markers." }, { "code": null, "e": 6537, "s": 6387, "text": "Just like the previous example, we need a fig object, it should be a dictionary object that contain two dictionaries one for data and one for layout." }, { "code": null, "e": 6758, "s": 6537, "text": "In the data dictionary we define two sets of x and y variables to be plotted, in both plots the x variable will be the same, this allows to compare GDP per capita and Healthy life expectancy relate with countries column." }, { "code": null, "e": 6872, "s": 6758, "text": "Then i create data object that contains both data1 and data2 using data.go syntax, and assign to mydata variable." }, { "code": null, "e": 6941, "s": 6872, "text": "Also create the layout object and pass in the title of scatter plot." }, { "code": null, "e": 7341, "s": 6941, "text": "data1=go.Scatter(x=df['Country or region'],y=df['GDP per capita'], name=\"GDP per capita\", mode=\"markers\") data2=go.Scatter(x=df['Country or region'],y=df['Healthy life expectancy'],name=\"Healthy life expectancy\",mode=\"markers\")mydata = go.Data([data1, data2])mylayout = go.Layout( title=\"GDP per capita vs. Life expectancy\")fig = go.Figure(data=mydata, layout=mylayout)chart_studio.plotly.iplot(fig)" }, { "code": null, "e": 7390, "s": 7341, "text": "There we go our plot using chart_studio package!" }, { "code": null, "e": 7529, "s": 7390, "text": "Here the same code but i use mode=”lines + markers” , it will be connect data points as lines and at the same time shows the scatter plot." }, { "code": null, "e": 7575, "s": 7529, "text": "Here shows how to customize colors in plotly." }, { "code": null, "e": 7746, "s": 7575, "text": "Here we need to use a dictionary object called color_theme and we gonna generate a list color that contains the RGBA codes for the colors we want to use in our bar chart." }, { "code": null, "e": 7957, "s": 7746, "text": "color_theme = dict(color=['rgba(169,169,169,1)', 'rgba(255,160,122,1)','rgba(176,224,230,1)', 'rgba(255,228,196,1)', 'rgba(189,183,107,1)', 'rgba(188,143,143,1)','rgba(221,160,221,1)'])" }, { "code": null, "e": 8017, "s": 7957, "text": "Now i will show you how to create Bar charts using plotly ." }, { "code": null, "e": 8310, "s": 8017, "text": "Here we use trace object to specify what kind of chart we want. So in this case we use go.Bar() function then we pass in two variables x and y that represent respectively the 7 countries on the head of data and Healthy life expectancy, also pass in the color_theme that we’ve already defined." }, { "code": null, "e": 8456, "s": 8310, "text": "Now let’s specify our layout parameters, in this code i use just one parameter to name the title of our plot you can add x-axis and y-axis names." }, { "code": null, "e": 8524, "s": 8456, "text": "Finally plot this using iplot() function and then pass in our data." }, { "code": null, "e": 8793, "s": 8524, "text": "trace0 = go.Bar(x=df['Country or region'].head(7), y=df['Healthy life expectancy'], marker=color_theme)data = [trace0]layout = go.Layout(title='Healthy life expectancy')fig = go.Figure(data=data, layout=layout)chart_studio.plotly.iplot(fig, filename='color-bar-chart')" }, { "code": null, "e": 8932, "s": 8793, "text": "Box plot usued usually in statistics, it gives us more information on how data spread out by measure median, mean and mode of the dataset." }, { "code": null, "e": 9105, "s": 8932, "text": "In the code below we just select 2 columns of our data, then we use iplot method and pass in an argument to specify the kind of plot, then we give file name of our boxplot." }, { "code": null, "e": 9215, "s": 9105, "text": "df_select = df[['GDP per capita','Healthy life expectancy']] df_select.iplot(kind='box', filename='box-plot')" }, { "code": null, "e": 9344, "s": 9215, "text": "Here i create a simple pie chart using the index of 10 countries as labels, and plot the GDP per capita values for each country." }, { "code": null, "e": 9468, "s": 9344, "text": "Then create a gragh object using go.Pie() and fill in labels and values variables. finally plot this using iplot()function." }, { "code": null, "e": 9682, "s": 9468, "text": "labels = df['Country or region'].head(10).value_counts().indexvalues = df['GDP per capita'].head(10).valuestrace = go.Pie(labels=labels, values=values)chart_studio.plotly.iplot([trace], filename='basic_pie_chart')" }, { "code": null, "e": 9743, "s": 9682, "text": "Using plotly is the simplest way to generate maps in python." }, { "code": null, "e": 9824, "s": 9743, "text": "We have two main types of plotly mapping objects; data object and layout object." }, { "code": null, "e": 10317, "s": 9824, "text": "First we need data to pass in a dictionary and set parameters for the data in our map. Let’s start by passing choropleth type, this means what type of map we want plotly to generate. Then define our colorscale and reverse the scale to have yellow down and violet up the scale. We set locations as countries in the dataframe, and z variable that is represented by the colors in the map. Lastly we gonna pass in the text argument to define the text that is displayed when you move over the map." }, { "code": null, "e": 10459, "s": 10317, "text": "Second create a layout dictionary to set title of our map. Then create a new dictionary that contains data and layout objects we call it fig." }, { "code": null, "e": 10566, "s": 10459, "text": "To plot this we just gonna call iplot method on our fig object and then give in a file name. Here we go..." }, { "code": null, "e": 11036, "s": 10566, "text": "data = dict( type = 'choropleth', colorscale = 'Viridis', reversescale = True, locations = df['Country or region'], locationmode = \"country names\", z = df['GDP per capita'], text = df['Country or region'], colorbar = {'title' : 'GDP per capita_world'}, ) layout=dict(title_text = '2019 GDP per capita by State')fig = go.Figure(data=data,layout=layout) chart_studio.plotly.iplot(fig, filename='choropleth')" }, { "code": null, "e": 11173, "s": 11036, "text": "Data visualization is a great tool to get data more readable and make a huge chance for you to discover more insights in the real world." }, { "code": null, "e": 11296, "s": 11173, "text": "All of the code for this article is available on GitHub . The charts are all interactive and can be viewed on plotly here." } ]
Beginner’s Guide to Data Cleaning and Feature Extraction in NLP | by Enes Gokce | Towards Data Science
This article will explain the steps of data cleaning and future extraction for text analysis done by using Neural Language Processing (NLP). On the internet, there are many great text cleaning guides. Some of the guides are making feature extraction after text cleaning while some of them are making before the text cleaning. Both of the approaches work fine. However, here is the issue that gets little attention: In the data cleaning process, we are losing some possible features(variables). We need feature extraction before the data cleaning. On the other hand, some features make sense only when they are extracted after the data cleaning. Thus, we also need feature extraction after the data cleaning. This study pays attention to this point, and this is what makes this study unique. In order to address the stated points above, this study follows three steps in order: Feature Extraction — Round 1Data CleaningFeature Extraction — Round 2 Feature Extraction — Round 1 Data Cleaning Feature Extraction — Round 2 This study article is a part of an Amazon Review Analysis with NLP methods. Here is my GitHub repo for the Colab Notebook of the codes for the main study, and codes for this study. Brief information about the data I use: The data used in this project was downloaded from Kaggle. It was uploaded by the Stanford Network Analysis Project. The original data is coming from the study of ‘From amateurs to connoisseurs: modeling the evolution of user expertise through online reviews’ done by J. McAuley and J. Leskovec (2013). This data set consists of reviews of fine foods from Amazon. The data includes all 568,454 reviews spanning 1999 to 2012. Reviews include product and user information, ratings, and a plain text review. In this part, the features that are not possible to obtain after data cleaning will be extracted. Number of stop words: A stop word is a commonly used word (such as “the”, “a”, “an”, “in”) that a search engine has been programmed to ignore, both when indexing entries for searching and when retrieving them as the result of a search query. In Python’s nltk package, there are 127 English stop words default. With applying stopwords, these 127 words were ignored. Before removing the stopwords, let’s have the ‘number of stopwords’ as a variable. Number of stop words: A stop word is a commonly used word (such as “the”, “a”, “an”, “in”) that a search engine has been programmed to ignore, both when indexing entries for searching and when retrieving them as the result of a search query. In Python’s nltk package, there are 127 English stop words default. With applying stopwords, these 127 words were ignored. Before removing the stopwords, let’s have the ‘number of stopwords’ as a variable. df['stopwords'] = df['Text'].apply(lambda x: len([x for x in x.split() if x in stop]))df[['Text','stopwords']].head() 2. The number of punctuation: Another feature that can’t be obtained after the data cleaning be because pronunciations will be deleted. def count_punct(text): count = sum([1 for char in text if char in string.punctuation]) return count#Apply the defined function on the text datadf['punctuation'] = df['Text'].apply(lambda x: count_punct(x))#Let's check the datasetdf[['Text','punctuation']].head() 3. Number of hashtag characters: One more interesting feature which we can extract from text data is the number of hashtags or mentions present in it. During the data cleaning, hashtags will be deleted, and we won’t have access to this information. Therefore, let’s extract this feature while we can still access it. df['hastags'] = df['Text'].apply(lambda x: len([x for x in x.split() if x.startswith('#')]))df[['Text','hastags']].head() 4. Number of numerical characters: Having the number of numeric characters that are present in the reviews can be useful. df['numerics'] = df['Text'].apply(lambda x: len([x for x in x.split() if x.isdigit()]))df[['Text','numerics']].head() 5. Number of Uppercase words: Emotions such as anger, rage are quite often expressed by writing in UPPERCASE words which makes this a necessary operation to identify those words. During the data cleaning, all letters will converted to lowercase. df['upper'] = df['Text'].apply(lambda x: len([x for x in x.split() if x.isupper()]))df[['Text','upper']].head() Now, we are done with features that can only be obtained before data cleaning. We are ready to clean the data. Before applying NLP techniques on the data, firstly the data needs to be cleaned and prepared the data for the analysis. If this process is not done properly, it can ruin the analysis part totally. Here are the steps that were applied to the data: Make all text lower case: The first pre-processing step is transforming the reviews into lower case. This avoids having multiple copies of the same words. For example, while calculating the word count, ‘Dog’ and ‘dog’ will be taken as different words if we ignore this transformation. Make all text lower case: The first pre-processing step is transforming the reviews into lower case. This avoids having multiple copies of the same words. For example, while calculating the word count, ‘Dog’ and ‘dog’ will be taken as different words if we ignore this transformation. df['Text'] = df['Text'].apply(lambda x: " ".join(x.lower() for x in x.split()))df['Text'].head() 2) Removing Punctuation: Punctuations creates noise in the data and, should be cleared. For now, NLP methods do not have a meaningful way to analyze punctuations. Thus, they were removed from the text data. With this step, these characters were removed: [!”#$%&’()*+,-./:;=>?@[\]^_`{|}~] df['Text'] = df['Text'].apply(lambda x: " ".join(x.lower() for x in df['Text'] = df['Text'].str.replace('[^\w\s]','')df['Text'].head() 3) Removal of Stop Words: With this step, I removed all default English stop words in nltk package. from nltk.corpus import stopwordsstop = stopwords.words('english')df['Text'] = df['Text'].apply(lambda x: " ".join(x for x in x.split() if x not in stop))df['Text'].sample(10) Adding your own stopwords: At this point, you may want to add your own stopwords. I do this mostly after checking the most frequent words. We can check the most frequent words in this way: import pandas as pdfreq = pd.Series(' '.join(df['Text']).split()).value_counts()[:20]freq From these words, I want to remove ‘br’, ‘get’, and ‘also’ because they don’t make much sense. Let’s add them to the list of the stopwords: # Adding common words from our document to stop_wordsadd_words = ["br", "get", "also"]stop_words = set(stopwords.words("english"))stop_added = stop_words.union(add_words)df['Text'] = df['Text'].apply(lambda x: " ".join(x for x in x.split() if x not in stop_added))df['Text'].sample(10) Note: In other guides, you may come across that TF-IDF method. TF-IDF is another way to get rid of words that have no semantic value from the text data. If you are using TF-IDF, you don’t need to apply stopwords (but applying both of them is no harm). 4) Removing URLs: URLs are another noise in the data that were removed. def remove_url(text): url = re.compile(r'https?://\S+|www\.\S+') return url.sub(r'', text)# remove all urls from dfimport reimport stringdf['Text'] = df['Text'].apply(lambda x: remove_url(x)) 5) Remove html HTML tags: HTML is used extensively on the Internet. But HTML tags themselves are not helpful when processing text. Thus, all texts beginning with url will be deleted. def remove_html(text): html=re.compile(r'<.*?>') return html.sub(r'',text)# remove all html tags from dfdf['Text'] = df['Text'].apply(lambda x: remove_html(x)) 6) Removing Emojis: Emojis can be an indicator of some emotions that can be related to being customer satisfaction. Unfortunately, we need to remove the emojis in our text analysis because for now, it is currently not possible to analyze emojis with NLP. # Reference : https://gist.github.com/slowkow/7a7f61f495e3dbb7e3d767f97bd7304bdef remove_emoji(text): emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F680-\U0001F6FF" # transport & map symbols u"\U0001F1E0-\U0001F1FF" # flags u"\U00002702-\U000027B0" u"\U000024C2-\U0001F251" "]+", flags=re.UNICODE) return emoji_pattern.sub(r'', text)#Exampleremove_emoji("Omg another Earthquake 😔😔") # remove all emojis from dfdf['Text'] = df['Text'].apply(lambda x: remove_emoji(x)) 7) Remove Emoticons: What is the difference between emoji and emoticons? ·:-) is an emoticon ·😜 is an→ emoji. !pip install emot #This may be required for the Colab notebookfrom emot.emo_unicode import UNICODE_EMO, EMOTICONS# Function for removing emoticonsdef remove_emoticons(text): emoticon_pattern = re.compile(u'(' + u'|'.join(k for k in EMOTICONS) + u')') return emoticon_pattern.sub(r'', text)#Exampleremove_emoticons("Hello :-)") df['Text'] = df['Text'].apply(lambda x: remove_emoticons(x)) 8) Spell Correction: On Amazon reviews, there are a plethora of spelling mistakes. Product reviews are sometimes filled with hastily sent reviews that are barely legible at times. In that regard, spelling correction is a useful pre-processing step because this also will help us in reducing multiple copies of words. For example, “Analytics” and “analytcs” will be treated as different words even if they are used in the same sense. from textblob import TextBlobdf['Text'][:5].apply(lambda x: str(TextBlob(x).correct())) 9. Lemmatization: Lemmatization is the process of converting a word to its base form. Lemmatization considers the context and converts the word to its meaningful base form. For example: ‘Caring’ -> Lemmatization -> ‘Care’ Python NLTK provides WordNet Lemmatizer that uses the WordNet Database to lookup lemmas of words. import nltkfrom nltk.stem import WordNetLemmatizer # Init the Wordnet Lemmatizerlemmatizer = WordNetLemmatizer()df['Text'] = df['Text'].apply(lambda x: lemmatizer(x)) For more detailed background about lemmatization, you can check Datacamp. Here, I will stop cleaning the data. However, as a researcher, you may need more text cleaning depending on your data. For example, you may want to use: ⚫ stemming the text data ⚫ Alternative ways for spell correction: isolated-term correction and context-sensitive correction methods ⚫ Different packages use different numbers of stopwords. You can try other NLP packages. Some features will be extracted after text cleaning because they are more meaningful to obtain at this step. For example, the number of characters would be affected badly from URL links if we would extract this feature before the data cleaning. At this point, we must try to extract as many features as possible since extra features have a chance to provide useful information during the text analysis. We don’t have to worry about whether the features will actually be useful in the future or not. In the worst case, we don’t use them. Number of Words: This feature tells how many words there are in the review Number of Words: This feature tells how many words there are in the review df['word_count'] = df['Text'].apply(lambda x: len(str(x).split(" ")))df[['Text','word_count']].head() 2. Number of characters: How many letters are contained in the review. df['char_count'] = df['Text'].str.len() ## this also includes spacesdf[['Text','char_count']].head() 3. Average Word Length: Average number of letters in the words in a review. def avg_word(sentence): words = sentence.split() return (sum(len(word) for word in words)/(len(words)+0.000001))df['avg_word'] = df['Text'].apply(lambda x: avg_word(x)).round(1)df[['Text','avg_word']].head() Let’s check how the extracted features look like in the dataframe: df.sample(5) This study explains the steps of text cleaning. In addition, this guide is unique in a way that feature extraction is done by two rounds: before the text cleaning and the after text cleaning. We need to remember that for an actual study, text cleaning is a recursive process. Once we see an anomaly, we come back and make more cleaning by addressing the anomaly. *Special thanks to my friend Tabitha Stickel for proofreading this article.
[ { "code": null, "e": 313, "s": 172, "text": "This article will explain the steps of data cleaning and future extraction for text analysis done by using Neural Language Processing (NLP)." }, { "code": null, "e": 963, "s": 313, "text": "On the internet, there are many great text cleaning guides. Some of the guides are making feature extraction after text cleaning while some of them are making before the text cleaning. Both of the approaches work fine. However, here is the issue that gets little attention: In the data cleaning process, we are losing some possible features(variables). We need feature extraction before the data cleaning. On the other hand, some features make sense only when they are extracted after the data cleaning. Thus, we also need feature extraction after the data cleaning. This study pays attention to this point, and this is what makes this study unique." }, { "code": null, "e": 1049, "s": 963, "text": "In order to address the stated points above, this study follows three steps in order:" }, { "code": null, "e": 1119, "s": 1049, "text": "Feature Extraction — Round 1Data CleaningFeature Extraction — Round 2" }, { "code": null, "e": 1148, "s": 1119, "text": "Feature Extraction — Round 1" }, { "code": null, "e": 1162, "s": 1148, "text": "Data Cleaning" }, { "code": null, "e": 1191, "s": 1162, "text": "Feature Extraction — Round 2" }, { "code": null, "e": 1372, "s": 1191, "text": "This study article is a part of an Amazon Review Analysis with NLP methods. Here is my GitHub repo for the Colab Notebook of the codes for the main study, and codes for this study." }, { "code": null, "e": 1916, "s": 1372, "text": "Brief information about the data I use: The data used in this project was downloaded from Kaggle. It was uploaded by the Stanford Network Analysis Project. The original data is coming from the study of ‘From amateurs to connoisseurs: modeling the evolution of user expertise through online reviews’ done by J. McAuley and J. Leskovec (2013). This data set consists of reviews of fine foods from Amazon. The data includes all 568,454 reviews spanning 1999 to 2012. Reviews include product and user information, ratings, and a plain text review." }, { "code": null, "e": 2014, "s": 1916, "text": "In this part, the features that are not possible to obtain after data cleaning will be extracted." }, { "code": null, "e": 2462, "s": 2014, "text": "Number of stop words: A stop word is a commonly used word (such as “the”, “a”, “an”, “in”) that a search engine has been programmed to ignore, both when indexing entries for searching and when retrieving them as the result of a search query. In Python’s nltk package, there are 127 English stop words default. With applying stopwords, these 127 words were ignored. Before removing the stopwords, let’s have the ‘number of stopwords’ as a variable." }, { "code": null, "e": 2910, "s": 2462, "text": "Number of stop words: A stop word is a commonly used word (such as “the”, “a”, “an”, “in”) that a search engine has been programmed to ignore, both when indexing entries for searching and when retrieving them as the result of a search query. In Python’s nltk package, there are 127 English stop words default. With applying stopwords, these 127 words were ignored. Before removing the stopwords, let’s have the ‘number of stopwords’ as a variable." }, { "code": null, "e": 3028, "s": 2910, "text": "df['stopwords'] = df['Text'].apply(lambda x: len([x for x in x.split() if x in stop]))df[['Text','stopwords']].head()" }, { "code": null, "e": 3164, "s": 3028, "text": "2. The number of punctuation: Another feature that can’t be obtained after the data cleaning be because pronunciations will be deleted." }, { "code": null, "e": 3433, "s": 3164, "text": "def count_punct(text): count = sum([1 for char in text if char in string.punctuation]) return count#Apply the defined function on the text datadf['punctuation'] = df['Text'].apply(lambda x: count_punct(x))#Let's check the datasetdf[['Text','punctuation']].head()" }, { "code": null, "e": 3750, "s": 3433, "text": "3. Number of hashtag characters: One more interesting feature which we can extract from text data is the number of hashtags or mentions present in it. During the data cleaning, hashtags will be deleted, and we won’t have access to this information. Therefore, let’s extract this feature while we can still access it." }, { "code": null, "e": 3872, "s": 3750, "text": "df['hastags'] = df['Text'].apply(lambda x: len([x for x in x.split() if x.startswith('#')]))df[['Text','hastags']].head()" }, { "code": null, "e": 3994, "s": 3872, "text": "4. Number of numerical characters: Having the number of numeric characters that are present in the reviews can be useful." }, { "code": null, "e": 4112, "s": 3994, "text": "df['numerics'] = df['Text'].apply(lambda x: len([x for x in x.split() if x.isdigit()]))df[['Text','numerics']].head()" }, { "code": null, "e": 4358, "s": 4112, "text": "5. Number of Uppercase words: Emotions such as anger, rage are quite often expressed by writing in UPPERCASE words which makes this a necessary operation to identify those words. During the data cleaning, all letters will converted to lowercase." }, { "code": null, "e": 4470, "s": 4358, "text": "df['upper'] = df['Text'].apply(lambda x: len([x for x in x.split() if x.isupper()]))df[['Text','upper']].head()" }, { "code": null, "e": 4581, "s": 4470, "text": "Now, we are done with features that can only be obtained before data cleaning. We are ready to clean the data." }, { "code": null, "e": 4829, "s": 4581, "text": "Before applying NLP techniques on the data, firstly the data needs to be cleaned and prepared the data for the analysis. If this process is not done properly, it can ruin the analysis part totally. Here are the steps that were applied to the data:" }, { "code": null, "e": 5114, "s": 4829, "text": "Make all text lower case: The first pre-processing step is transforming the reviews into lower case. This avoids having multiple copies of the same words. For example, while calculating the word count, ‘Dog’ and ‘dog’ will be taken as different words if we ignore this transformation." }, { "code": null, "e": 5399, "s": 5114, "text": "Make all text lower case: The first pre-processing step is transforming the reviews into lower case. This avoids having multiple copies of the same words. For example, while calculating the word count, ‘Dog’ and ‘dog’ will be taken as different words if we ignore this transformation." }, { "code": null, "e": 5496, "s": 5399, "text": "df['Text'] = df['Text'].apply(lambda x: \" \".join(x.lower() for x in x.split()))df['Text'].head()" }, { "code": null, "e": 5784, "s": 5496, "text": "2) Removing Punctuation: Punctuations creates noise in the data and, should be cleared. For now, NLP methods do not have a meaningful way to analyze punctuations. Thus, they were removed from the text data. With this step, these characters were removed: [!”#$%&’()*+,-./:;=>?@[\\]^_`{|}~]" }, { "code": null, "e": 5919, "s": 5784, "text": "df['Text'] = df['Text'].apply(lambda x: \" \".join(x.lower() for x in df['Text'] = df['Text'].str.replace('[^\\w\\s]','')df['Text'].head()" }, { "code": null, "e": 6019, "s": 5919, "text": "3) Removal of Stop Words: With this step, I removed all default English stop words in nltk package." }, { "code": null, "e": 6195, "s": 6019, "text": "from nltk.corpus import stopwordsstop = stopwords.words('english')df['Text'] = df['Text'].apply(lambda x: \" \".join(x for x in x.split() if x not in stop))df['Text'].sample(10)" }, { "code": null, "e": 6384, "s": 6195, "text": "Adding your own stopwords: At this point, you may want to add your own stopwords. I do this mostly after checking the most frequent words. We can check the most frequent words in this way:" }, { "code": null, "e": 6474, "s": 6384, "text": "import pandas as pdfreq = pd.Series(' '.join(df['Text']).split()).value_counts()[:20]freq" }, { "code": null, "e": 6614, "s": 6474, "text": "From these words, I want to remove ‘br’, ‘get’, and ‘also’ because they don’t make much sense. Let’s add them to the list of the stopwords:" }, { "code": null, "e": 6900, "s": 6614, "text": "# Adding common words from our document to stop_wordsadd_words = [\"br\", \"get\", \"also\"]stop_words = set(stopwords.words(\"english\"))stop_added = stop_words.union(add_words)df['Text'] = df['Text'].apply(lambda x: \" \".join(x for x in x.split() if x not in stop_added))df['Text'].sample(10)" }, { "code": null, "e": 7152, "s": 6900, "text": "Note: In other guides, you may come across that TF-IDF method. TF-IDF is another way to get rid of words that have no semantic value from the text data. If you are using TF-IDF, you don’t need to apply stopwords (but applying both of them is no harm)." }, { "code": null, "e": 7224, "s": 7152, "text": "4) Removing URLs: URLs are another noise in the data that were removed." }, { "code": null, "e": 7423, "s": 7224, "text": "def remove_url(text): url = re.compile(r'https?://\\S+|www\\.\\S+') return url.sub(r'', text)# remove all urls from dfimport reimport stringdf['Text'] = df['Text'].apply(lambda x: remove_url(x))" }, { "code": null, "e": 7606, "s": 7423, "text": "5) Remove html HTML tags: HTML is used extensively on the Internet. But HTML tags themselves are not helpful when processing text. Thus, all texts beginning with url will be deleted." }, { "code": null, "e": 7772, "s": 7606, "text": "def remove_html(text): html=re.compile(r'<.*?>') return html.sub(r'',text)# remove all html tags from dfdf['Text'] = df['Text'].apply(lambda x: remove_html(x))" }, { "code": null, "e": 8027, "s": 7772, "text": "6) Removing Emojis: Emojis can be an indicator of some emotions that can be related to being customer satisfaction. Unfortunately, we need to remove the emojis in our text analysis because for now, it is currently not possible to analyze emojis with NLP." }, { "code": null, "e": 8549, "s": 8027, "text": "# Reference : https://gist.github.com/slowkow/7a7f61f495e3dbb7e3d767f97bd7304bdef remove_emoji(text): emoji_pattern = re.compile(\"[\" u\"\\U0001F600-\\U0001F64F\" # emoticons u\"\\U0001F300-\\U0001F5FF\" # symbols & pictographs u\"\\U0001F680-\\U0001F6FF\" # transport & map symbols u\"\\U0001F1E0-\\U0001F1FF\" # flags u\"\\U00002702-\\U000027B0\" u\"\\U000024C2-\\U0001F251\" \"]+\", flags=re.UNICODE) return emoji_pattern.sub(r'', text)#Exampleremove_emoji(\"Omg another Earthquake 😔😔\")" }, { "code": null, "e": 8633, "s": 8549, "text": "# remove all emojis from dfdf['Text'] = df['Text'].apply(lambda x: remove_emoji(x))" }, { "code": null, "e": 8706, "s": 8633, "text": "7) Remove Emoticons: What is the difference between emoji and emoticons?" }, { "code": null, "e": 8726, "s": 8706, "text": "·:-) is an emoticon" }, { "code": null, "e": 8743, "s": 8726, "text": "·😜 is an→ emoji." }, { "code": null, "e": 9078, "s": 8743, "text": "!pip install emot #This may be required for the Colab notebookfrom emot.emo_unicode import UNICODE_EMO, EMOTICONS# Function for removing emoticonsdef remove_emoticons(text): emoticon_pattern = re.compile(u'(' + u'|'.join(k for k in EMOTICONS) + u')') return emoticon_pattern.sub(r'', text)#Exampleremove_emoticons(\"Hello :-)\")" }, { "code": null, "e": 9139, "s": 9078, "text": "df['Text'] = df['Text'].apply(lambda x: remove_emoticons(x))" }, { "code": null, "e": 9319, "s": 9139, "text": "8) Spell Correction: On Amazon reviews, there are a plethora of spelling mistakes. Product reviews are sometimes filled with hastily sent reviews that are barely legible at times." }, { "code": null, "e": 9572, "s": 9319, "text": "In that regard, spelling correction is a useful pre-processing step because this also will help us in reducing multiple copies of words. For example, “Analytics” and “analytcs” will be treated as different words even if they are used in the same sense." }, { "code": null, "e": 9660, "s": 9572, "text": "from textblob import TextBlobdf['Text'][:5].apply(lambda x: str(TextBlob(x).correct()))" }, { "code": null, "e": 9846, "s": 9660, "text": "9. Lemmatization: Lemmatization is the process of converting a word to its base form. Lemmatization considers the context and converts the word to its meaningful base form. For example:" }, { "code": null, "e": 9882, "s": 9846, "text": "‘Caring’ -> Lemmatization -> ‘Care’" }, { "code": null, "e": 9980, "s": 9882, "text": "Python NLTK provides WordNet Lemmatizer that uses the WordNet Database to lookup lemmas of words." }, { "code": null, "e": 10147, "s": 9980, "text": "import nltkfrom nltk.stem import WordNetLemmatizer # Init the Wordnet Lemmatizerlemmatizer = WordNetLemmatizer()df['Text'] = df['Text'].apply(lambda x: lemmatizer(x))" }, { "code": null, "e": 10221, "s": 10147, "text": "For more detailed background about lemmatization, you can check Datacamp." }, { "code": null, "e": 10374, "s": 10221, "text": "Here, I will stop cleaning the data. However, as a researcher, you may need more text cleaning depending on your data. For example, you may want to use:" }, { "code": null, "e": 10399, "s": 10374, "text": "⚫ stemming the text data" }, { "code": null, "e": 10506, "s": 10399, "text": "⚫ Alternative ways for spell correction: isolated-term correction and context-sensitive correction methods" }, { "code": null, "e": 10595, "s": 10506, "text": "⚫ Different packages use different numbers of stopwords. You can try other NLP packages." }, { "code": null, "e": 11132, "s": 10595, "text": "Some features will be extracted after text cleaning because they are more meaningful to obtain at this step. For example, the number of characters would be affected badly from URL links if we would extract this feature before the data cleaning. At this point, we must try to extract as many features as possible since extra features have a chance to provide useful information during the text analysis. We don’t have to worry about whether the features will actually be useful in the future or not. In the worst case, we don’t use them." }, { "code": null, "e": 11207, "s": 11132, "text": "Number of Words: This feature tells how many words there are in the review" }, { "code": null, "e": 11282, "s": 11207, "text": "Number of Words: This feature tells how many words there are in the review" }, { "code": null, "e": 11384, "s": 11282, "text": "df['word_count'] = df['Text'].apply(lambda x: len(str(x).split(\" \")))df[['Text','word_count']].head()" }, { "code": null, "e": 11455, "s": 11384, "text": "2. Number of characters: How many letters are contained in the review." }, { "code": null, "e": 11556, "s": 11455, "text": "df['char_count'] = df['Text'].str.len() ## this also includes spacesdf[['Text','char_count']].head()" }, { "code": null, "e": 11632, "s": 11556, "text": "3. Average Word Length: Average number of letters in the words in a review." }, { "code": null, "e": 11846, "s": 11632, "text": "def avg_word(sentence): words = sentence.split() return (sum(len(word) for word in words)/(len(words)+0.000001))df['avg_word'] = df['Text'].apply(lambda x: avg_word(x)).round(1)df[['Text','avg_word']].head()" }, { "code": null, "e": 11913, "s": 11846, "text": "Let’s check how the extracted features look like in the dataframe:" }, { "code": null, "e": 11926, "s": 11913, "text": "df.sample(5)" }, { "code": null, "e": 12289, "s": 11926, "text": "This study explains the steps of text cleaning. In addition, this guide is unique in a way that feature extraction is done by two rounds: before the text cleaning and the after text cleaning. We need to remember that for an actual study, text cleaning is a recursive process. Once we see an anomaly, we come back and make more cleaning by addressing the anomaly." } ]
Lucene - IndexWriter
This class acts as a core component which creates/updates indexes during indexing process. Following is the declaration for org.apache.lucene.index.IndexWriter class − public class IndexWriter extends Object implements Closeable, TwoPhaseCommit Following are the fields for the org.apache.lucene.index.IndexWriter class − static int DEFAULT_MAX_BUFFERED_DELETE_TERMS − Deprecated. use IndexWriterConfig.DEFAULT_MAX_BUFFERED_DELETE_TERMS instead. static int DEFAULT_MAX_BUFFERED_DELETE_TERMS − Deprecated. use IndexWriterConfig.DEFAULT_MAX_BUFFERED_DELETE_TERMS instead. static int DEFAULT_MAX_BUFFERED_DOCS − Deprecated. Use IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS instead. static int DEFAULT_MAX_BUFFERED_DOCS − Deprecated. Use IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS instead. static int DEFAULT_MAX_FIELD_LENGTH − Deprecated. See IndexWriterConfig. static int DEFAULT_MAX_FIELD_LENGTH − Deprecated. See IndexWriterConfig. static double DEFAULT_RAM_BUFFER_SIZE_MB − Deprecated. Use IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB instead. static double DEFAULT_RAM_BUFFER_SIZE_MB − Deprecated. Use IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB instead. static int DEFAULT_TERM_INDEX_INTERVAL − Deprecated. Use IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL instead. static int DEFAULT_TERM_INDEX_INTERVAL − Deprecated. Use IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL instead. static int DISABLE_AUTO_FLUSH − Deprecated. Use IndexWriterConfig.DISABLE_AUTO_FLUSH instead. static int DISABLE_AUTO_FLUSH − Deprecated. Use IndexWriterConfig.DISABLE_AUTO_FLUSH instead. static int MAX_TERM_LENGTH − Absolute maximum length for a term. static int MAX_TERM_LENGTH − Absolute maximum length for a term. static String WRITE_LOCK_NAME − Name of the write lock in the index. static String WRITE_LOCK_NAME − Name of the write lock in the index. static long WRITE_LOCK_TIMEOUT − Deprecated. Use IndexWriterConfig.WRITE_LOCK_TIMEOUT instead. static long WRITE_LOCK_TIMEOUT − Deprecated. Use IndexWriterConfig.WRITE_LOCK_TIMEOUT instead. Following table shows the class constructors for IndexWriter − IndexWriter(Directory d, Analyzer a, boolean create, IndexDeletionPolicy deletionPolicy, IndexWriter.MaxFieldLength mfl) Deprecated. Use IndexWriter(Directory, IndexWriterConfig) instead. IndexWriter(Directory d, Analyzer a, boolean create, IndexWriter.MaxFieldLength mfl) Deprecated. Use IndexWriter(Directory, IndexWriterConfig) instead. IndexWriter(Directory d, Analyzer a, IndexDeletionPolicy deletionPolicy, IndexWriter.MaxFieldLength mfl) Deprecated. Use IndexWriter(Directory, IndexWriterConfig) instead. IndexWriter(Directory d, Analyzer a, IndexDeletionPolicy deletionPolicy, IndexWriter.MaxFieldLength mfl, IndexCommit commit) Deprecated. Use IndexWriter(Directory, IndexWriterConfig) instead. IndexWriter(Directory d, Analyzer a, IndexWriter.MaxFieldLength mfl) Deprecated. Use IndexWriter(Directory, IndexWriterConfig) instead. IndexWriter(Directory d, IndexWriterConfig conf) Constructs a new IndexWriter per the settings given in conf. void addDocument(Document doc) Adds a document to this index. void addDocument(Document doc, Analyzer analyzer) Adds a document to this index, using the provided analyzer instead of the value of getAnalyzer(). void addDocuments(Collection docs) Atomically adds a block of documents with sequentially-assigned document IDs, such that an external reader will see all or none of the documents. void addDocuments(Collection docs, Analyzer analyzer) Atomically adds a block of documents, analyzed using the provided analyzer, with sequentially assigned document IDs, such that an external reader will see all or none of the documents. void addIndexes(Directory... dirs) Adds all segments from an array of indexes into this index. void addIndexes(IndexReader... readers) Merges the provided indexes into this index. void addIndexesNoOptimize(Directory... dirs) Deprecated. Use addIndexes(Directory...) instead. void close() Commits all changes to an index and closes all associated files. void close(boolean waitForMerges) Closes the index with or without waiting for currently running merges to finish. void commit() Commits all pending changes (added & deleted documents, segment merges, added indexes, etc.) to the index, and syncs all referenced index files, such that a reader will see the changes and the index updates will survive an OS or machine crash or power loss. void commit(Map<String,String> commitUserData) Commits all changes to the index, specifying a commitUserData Map (String > String). void deleteAll() Deletes all documents in the index. void deleteDocuments(Query... queries) Deletes the document(s) matching any of the provided queries. void deleteDocuments(Query query) Deletes the document(s) matching the provided query. void deleteDocuments(Term... terms) Deletes the document(s) containing any of the terms. void deleteDocuments(Term term) Deletes the document(s) containing term. void deleteUnusedFiles() Expert: remove the index files that are no longer used. protected void doAfterFlush() A hook for extending classes to execute operations after pending added and deleted documents have been flushed to the Directory but before the change is committed (new segments_N file written). protected void doBeforeFlush() A hook for extending classes to execute operations before pending added and deleted documents are flushed to the Directory. protected void ensureOpen() protected void ensureOpen(boolean includePendingClose) Used internally to throw an AlreadyClosedException if this IndexWriter has been closed. void expungeDeletes() Deprecated. void expungeDeletes(boolean doWait) Deprecated. protected void flush(boolean triggerMerge, boolean applyAllDeletes) Flushes all in-memory buffered updates (adds and deletes) to the Directory. protected void flush(boolean triggerMerge, boolean flushDocStores, boolean flushDeletes) NOTE: flushDocStores is ignored now (hardwired to true); this method is only here for backwards compatibility. void forceMerge(int maxNumSegments) This is a force merging policy to merge segments until there's <= maxNumSegments. void forceMerge(int maxNumSegments, boolean doWait) Just like forceMerge(int), except you can specify whether the call should block until all merging completes. void forceMergeDeletes() Forces merging of all segments that have deleted documents. void forceMergeDeletes(boolean doWait) Just like forceMergeDeletes(), except you can specify whether the call should be blocked until the operation completes. Analyzer getAnalyzer() Returns the analyzer used by this index. IndexWriterConfig getConfig() Returns the private IndexWriterConfig, cloned from the IndexWriterConfig passed to IndexWriter(Directory, IndexWriterConfig). static PrintStream getDefaultInfoStream() Returns the current default infoStream for newly instantiated IndexWriters. static long getDefaultWriteLockTimeout() Deprecated. Use IndexWriterConfig.getDefaultWriteLockTimeout() instead. Directory getDirectory() Returns the Directory used by this index. PrintStream getInfoStream() Returns the current infoStream in use by this writer. int getMaxBufferedDeleteTerms() Deprecated. Use IndexWriterConfig.getMaxBufferedDeleteTerms() instead. int getMaxBufferedDocs() Deprecated. Use IndexWriterConfig.getMaxBufferedDocs() instead. int getMaxFieldLength() Deprecated. Use LimitTokenCountAnalyzer to limit number of tokens. int getMaxMergeDocs() Deprecated. Use LogMergePolicy.getMaxMergeDocs() directly. IndexWriter.IndexReaderWarmer getMergedSegmentWarmer() Deprecated. Use IndexWriterConfig.getMergedSegmentWarmer() instead. int getMergeFactor() Deprecated. Use LogMergePolicy.getMergeFactor() directly. MergePolicy getMergePolicy() Deprecated. Use IndexWriterConfig.getMergePolicy() instead. MergeScheduler getMergeScheduler() Deprecated. Use IndexWriterConfig.getMergeScheduler() instead Collection<SegmentInfo> getMergingSegments() Expert: to be used by a MergePolicy to a void selecting merges for segments already being merged. MergePolicy.OneMerge getNextMerge() Expert: the MergeScheduler calls this method to retrieve the next merge requested by the MergePolicy. PayloadProcessorProvider getPayloadProcessorProvider() Returns the PayloadProcessorProvider that is used during segment merges to process payloads. double getRAMBufferSizeMB() Deprecated. Use IndexWriterConfig.getRAMBufferSizeMB() instead. IndexReader getReader() Deprecated. Use IndexReader.open(IndexWriter,boolean) instead. IndexReader getReader(int termInfosIndexDivisor) Deprecated. Use IndexReader.open(IndexWriter,boolean) instead. Furthermore, this method cannot guarantee the reader (and its sub-readers) will be opened with the termInfosIndexDivisor setting because some of them may already have been opened according to IndexWriterConfig.setReaderTermsIndexDivisor(int). You should set the requested termInfosIndexDivisor through IndexWriterConfig.setReaderTermsIndexDivisor(int) and use getReader(). int getReaderTermsIndexDivisor() Deprecated. Use IndexWriterConfig.getReaderTermsIndexDivisor() instead. Similarity getSimilarity() Deprecated. Use IndexWriterConfig.getSimilarity() instead. int getTermIndexInterval() Deprecated. Use IndexWriterConfig.getTermIndexInterval(). boolean getUseCompoundFile() Deprecated. Use LogMergePolicy.getUseCompoundFile(). long getWriteLockTimeout() Deprecated. Use IndexWriterConfig.getWriteLockTimeout() boolean hasDeletions() static boolean isLocked(Directory directory) Returns true if the index in the named directory is currently locked. int maxDoc() Returns total number of docs in this index, including docs not yet flushed (still in the RAM buffer), not counting deletions. void maybeMerge() Expert: Asks the mergePolicy whether any merges are necessary now and if so, runs the requested merges and then iterate (test again if merges are needed) until no more merges are returned by the mergePolicy. void merge(MergePolicy.OneMerge merge) Merges the indicated segments, replacing them in the stack with a single segment. void message(String message) Prints a message to the infoStream (if non-null), prefixed with the identifying information for this writer and the thread that's calling it. int numDeletedDocs(SegmentInfo info) Obtains the number of deleted docs for a pooled reader. int numDocs() Returns total number of docs in this index, including docs not yet flushed (still in the RAM buffer), and including deletions. int numRamDocs() Expert: Returns the number of documents currently buffered in RAM. void optimize() Deprecated. void optimize(boolean doWait) Deprecated. void optimize(int maxNumSegments) Deprecated. void prepareCommit() Expert: prepare for commit. void prepareCommit(Map<String,String> commitUserData) Expert: Prepare for commit, specifying commitUserData Map (String -> String). long ramSizeInBytes() Expert: Return the total size of all index files currently cached in memory. void rollback() Closes the IndexWriter without committing any changes that have occurred since the last commit (or since it was opened, if commit hasn't been called). String segString() String segString(Iterable<SegmentInfo> infos) String segString(SegmentInfo info) static void setDefaultInfoStream(PrintStream infoStream) If non-null, this will be the default infoStream used by a newly instantiated IndexWriter. static void setDefaultWriteLockTimeout(long writeLockTimeout) Deprecated. Use IndexWriterConfig.setDefaultWriteLockTimeout(long) instead. void setInfoStream(PrintStream infoStream) If non-null, information about merges, deletes and a message when maxFieldLength is reached will be printed to this. void setMaxBufferedDeleteTerms(int maxBufferedDeleteTerms) Deprecated. Use IndexWriterConfig.setMaxBufferedDeleteTerms(int) instead. void setMaxBufferedDocs(int maxBufferedDocs) Deprecated. Use IndexWriterConfig.setMaxBufferedDocs(int) instead. void setMaxFieldLength(int maxFieldLength) Deprecated. Use LimitTokenCountAnalyzer instead. Observe the change in the behavior - the analyzer limits the number of tokens per token stream created, while this setting limits the total number of tokens to index. This matters only if you index many multi-valued fields though. void setMaxMergeDocs(int maxMergeDocs) Deprecated. Use LogMergePolicy.setMaxMergeDocs(int) directly. void setMergedSegmentWarmer(IndexWriter.IndexReaderWarmer warmer) Deprecated. Use IndexWriterConfig.setMergedSegmentWarmer( org.apache.lucene.index.IndexWriter.IndexReaderWarmer ) instead. void setMergeFactor(int mergeFactor) Deprecated. Use LogMergePolicy.setMergeFactor(int) directly. void setMergePolicy(MergePolicy mp) Deprecated. Use IndexWriterConfig.setMergePolicy(MergePolicy) instead. void setMergeScheduler(MergeScheduler mergeScheduler) Deprecated. Use IndexWriterConfig.setMergeScheduler(MergeScheduler) instead void setPayloadProcessorProvider(PayloadProcessorProvider pcp) Sets the PayloadProcessorProvider to use when merging payloads. void setRAMBufferSizeMB(double mb) Deprecated. Use IndexWriterConfig.setRAMBufferSizeMB(double) instead. void setReaderTermsIndexDivisor(int divisor) Deprecated. Use IndexWriterConfig.setReaderTermsIndexDivisor(int) instead. void setSimilarity(Similarity similarity) Deprecated. Use IndexWriterConfig.setSimilarity(Similarity) instead. void setTermIndexInterval(int interval) Deprecated. Use IndexWriterConfig.setTermIndexInterval(int). void setUseCompoundFile(boolean value) Deprecated. Use LogMergePolicy.setUseCompoundFile(boolean). void setWriteLockTimeout(long writeLockTimeout) Deprecated. Use IndexWriterConfig.setWriteLockTimeout(long) instead. static void unlock(Directory directory) Forcibly unlocks the index in the named directory. void updateDocument(Term term, Document doc) Updates a document by first deleting the document(s) containing term and then adding the new document. void updateDocument(Term term, Document doc, Analyzer analyzer) Updates a document by first deleting the document(s) containing term and then adding the new document. void updateDocuments(Term delTerm, Collection<Document> docs) Atomically deletes documents matching the provided delTerm and adds a block of documents with sequentially assigned document IDs, such that an external reader will see all or none of the documents. void updateDocuments(Term delTerm, Collection<Document> docs, Analyzer analyzer) Atomically deletes documents matching the provided delTerm and adds a block of documents, analyzed using the provided analyzer, with sequentially assigned document IDs, such that an external reader will see all or none of the documents. boolean verbose() Returns true if verbosing is enabled (i.e., infoStream) void waitForMerges() Waits for any currently outstanding merges to finish. This class inherits methods from the following classes − java.lang.Object Print Add Notes Bookmark this page
[ { "code": null, "e": 1934, "s": 1843, "text": "This class acts as a core component which creates/updates indexes during indexing process." }, { "code": null, "e": 2011, "s": 1934, "text": "Following is the declaration for org.apache.lucene.index.IndexWriter class −" }, { "code": null, "e": 2098, "s": 2011, "text": "public class IndexWriter\n extends Object\n implements Closeable, TwoPhaseCommit\n" }, { "code": null, "e": 2175, "s": 2098, "text": "Following are the fields for the org.apache.lucene.index.IndexWriter class −" }, { "code": null, "e": 2299, "s": 2175, "text": "static int DEFAULT_MAX_BUFFERED_DELETE_TERMS − Deprecated. use IndexWriterConfig.DEFAULT_MAX_BUFFERED_DELETE_TERMS instead." }, { "code": null, "e": 2423, "s": 2299, "text": "static int DEFAULT_MAX_BUFFERED_DELETE_TERMS − Deprecated. use IndexWriterConfig.DEFAULT_MAX_BUFFERED_DELETE_TERMS instead." }, { "code": null, "e": 2531, "s": 2423, "text": "static int DEFAULT_MAX_BUFFERED_DOCS − Deprecated. Use IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS instead." }, { "code": null, "e": 2639, "s": 2531, "text": "static int DEFAULT_MAX_BUFFERED_DOCS − Deprecated. Use IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS instead." }, { "code": null, "e": 2712, "s": 2639, "text": "static int DEFAULT_MAX_FIELD_LENGTH − Deprecated. See IndexWriterConfig." }, { "code": null, "e": 2785, "s": 2712, "text": "static int DEFAULT_MAX_FIELD_LENGTH − Deprecated. See IndexWriterConfig." }, { "code": null, "e": 2898, "s": 2785, "text": "static double DEFAULT_RAM_BUFFER_SIZE_MB − Deprecated. Use IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB instead." }, { "code": null, "e": 3011, "s": 2898, "text": "static double DEFAULT_RAM_BUFFER_SIZE_MB − Deprecated. Use IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB instead." }, { "code": null, "e": 3123, "s": 3011, "text": "static int DEFAULT_TERM_INDEX_INTERVAL − Deprecated. Use IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL instead." }, { "code": null, "e": 3235, "s": 3123, "text": "static int DEFAULT_TERM_INDEX_INTERVAL − Deprecated. Use IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL instead." }, { "code": null, "e": 3329, "s": 3235, "text": "static int DISABLE_AUTO_FLUSH − Deprecated. Use IndexWriterConfig.DISABLE_AUTO_FLUSH instead." }, { "code": null, "e": 3423, "s": 3329, "text": "static int DISABLE_AUTO_FLUSH − Deprecated. Use IndexWriterConfig.DISABLE_AUTO_FLUSH instead." }, { "code": null, "e": 3488, "s": 3423, "text": "static int MAX_TERM_LENGTH − Absolute maximum length for a term." }, { "code": null, "e": 3553, "s": 3488, "text": "static int MAX_TERM_LENGTH − Absolute maximum length for a term." }, { "code": null, "e": 3622, "s": 3553, "text": "static String WRITE_LOCK_NAME − Name of the write lock in the index." }, { "code": null, "e": 3691, "s": 3622, "text": "static String WRITE_LOCK_NAME − Name of the write lock in the index." }, { "code": null, "e": 3786, "s": 3691, "text": "static long WRITE_LOCK_TIMEOUT − Deprecated. Use IndexWriterConfig.WRITE_LOCK_TIMEOUT instead." }, { "code": null, "e": 3881, "s": 3786, "text": "static long WRITE_LOCK_TIMEOUT − Deprecated. Use IndexWriterConfig.WRITE_LOCK_TIMEOUT instead." }, { "code": null, "e": 3944, "s": 3881, "text": "Following table shows the class constructors for IndexWriter −" }, { "code": null, "e": 4065, "s": 3944, "text": "IndexWriter(Directory d, Analyzer a, boolean create, IndexDeletionPolicy deletionPolicy, IndexWriter.MaxFieldLength mfl)" }, { "code": null, "e": 4132, "s": 4065, "text": "Deprecated. Use IndexWriter(Directory, IndexWriterConfig) instead." }, { "code": null, "e": 4217, "s": 4132, "text": "IndexWriter(Directory d, Analyzer a, boolean create, IndexWriter.MaxFieldLength mfl)" }, { "code": null, "e": 4284, "s": 4217, "text": "Deprecated. Use IndexWriter(Directory, IndexWriterConfig) instead." }, { "code": null, "e": 4389, "s": 4284, "text": "IndexWriter(Directory d, Analyzer a, IndexDeletionPolicy deletionPolicy, IndexWriter.MaxFieldLength mfl)" }, { "code": null, "e": 4456, "s": 4389, "text": "Deprecated. Use IndexWriter(Directory, IndexWriterConfig) instead." }, { "code": null, "e": 4581, "s": 4456, "text": "IndexWriter(Directory d, Analyzer a, IndexDeletionPolicy deletionPolicy, IndexWriter.MaxFieldLength mfl, IndexCommit commit)" }, { "code": null, "e": 4648, "s": 4581, "text": "Deprecated. Use IndexWriter(Directory, IndexWriterConfig) instead." }, { "code": null, "e": 4717, "s": 4648, "text": "IndexWriter(Directory d, Analyzer a, IndexWriter.MaxFieldLength mfl)" }, { "code": null, "e": 4784, "s": 4717, "text": "Deprecated. Use IndexWriter(Directory, IndexWriterConfig) instead." }, { "code": null, "e": 4833, "s": 4784, "text": "IndexWriter(Directory d, IndexWriterConfig conf)" }, { "code": null, "e": 4894, "s": 4833, "text": "Constructs a new IndexWriter per the settings given in conf." }, { "code": null, "e": 4925, "s": 4894, "text": "void addDocument(Document doc)" }, { "code": null, "e": 4956, "s": 4925, "text": "Adds a document to this index." }, { "code": null, "e": 5006, "s": 4956, "text": "void addDocument(Document doc, Analyzer analyzer)" }, { "code": null, "e": 5104, "s": 5006, "text": "Adds a document to this index, using the provided analyzer instead of the value of getAnalyzer()." }, { "code": null, "e": 5139, "s": 5104, "text": "void addDocuments(Collection docs)" }, { "code": null, "e": 5285, "s": 5139, "text": "Atomically adds a block of documents with sequentially-assigned document IDs, such that an external reader will see all or none of the documents." }, { "code": null, "e": 5339, "s": 5285, "text": "void addDocuments(Collection docs, Analyzer analyzer)" }, { "code": null, "e": 5524, "s": 5339, "text": "Atomically adds a block of documents, analyzed using the provided analyzer, with sequentially assigned document IDs, such that an external reader will see all or none of the documents." }, { "code": null, "e": 5559, "s": 5524, "text": "void addIndexes(Directory... dirs)" }, { "code": null, "e": 5619, "s": 5559, "text": "Adds all segments from an array of indexes into this index." }, { "code": null, "e": 5659, "s": 5619, "text": "void addIndexes(IndexReader... readers)" }, { "code": null, "e": 5704, "s": 5659, "text": "Merges the provided indexes into this index." }, { "code": null, "e": 5749, "s": 5704, "text": "void addIndexesNoOptimize(Directory... dirs)" }, { "code": null, "e": 5799, "s": 5749, "text": "Deprecated. Use addIndexes(Directory...) instead." }, { "code": null, "e": 5812, "s": 5799, "text": "void close()" }, { "code": null, "e": 5877, "s": 5812, "text": "Commits all changes to an index and closes all associated files." }, { "code": null, "e": 5911, "s": 5877, "text": "void close(boolean waitForMerges)" }, { "code": null, "e": 5992, "s": 5911, "text": "Closes the index with or without waiting for currently running merges to finish." }, { "code": null, "e": 6006, "s": 5992, "text": "void commit()" }, { "code": null, "e": 6264, "s": 6006, "text": "Commits all pending changes (added & deleted documents, segment merges, added indexes, etc.) to the index, and syncs all referenced index files, such that a reader will see the changes and the index updates will survive an OS or machine crash or power loss." }, { "code": null, "e": 6311, "s": 6264, "text": "void commit(Map<String,String> commitUserData)" }, { "code": null, "e": 6396, "s": 6311, "text": "Commits all changes to the index, specifying a commitUserData Map (String > String)." }, { "code": null, "e": 6413, "s": 6396, "text": "void deleteAll()" }, { "code": null, "e": 6449, "s": 6413, "text": "Deletes all documents in the index." }, { "code": null, "e": 6488, "s": 6449, "text": "void deleteDocuments(Query... queries)" }, { "code": null, "e": 6550, "s": 6488, "text": "Deletes the document(s) matching any of the provided queries." }, { "code": null, "e": 6584, "s": 6550, "text": "void deleteDocuments(Query query)" }, { "code": null, "e": 6637, "s": 6584, "text": "Deletes the document(s) matching the provided query." }, { "code": null, "e": 6673, "s": 6637, "text": "void deleteDocuments(Term... terms)" }, { "code": null, "e": 6726, "s": 6673, "text": "Deletes the document(s) containing any of the terms." }, { "code": null, "e": 6758, "s": 6726, "text": "void deleteDocuments(Term term)" }, { "code": null, "e": 6799, "s": 6758, "text": "Deletes the document(s) containing term." }, { "code": null, "e": 6824, "s": 6799, "text": "void deleteUnusedFiles()" }, { "code": null, "e": 6880, "s": 6824, "text": "Expert: remove the index files that are no longer used." }, { "code": null, "e": 6910, "s": 6880, "text": "protected void doAfterFlush()" }, { "code": null, "e": 7104, "s": 6910, "text": "A hook for extending classes to execute operations after pending added and deleted documents have been flushed to the Directory but before the change is committed (new segments_N file written)." }, { "code": null, "e": 7135, "s": 7104, "text": "protected void doBeforeFlush()" }, { "code": null, "e": 7259, "s": 7135, "text": "A hook for extending classes to execute operations before pending added and deleted documents are flushed to the Directory." }, { "code": null, "e": 7287, "s": 7259, "text": "protected void ensureOpen()" }, { "code": null, "e": 7342, "s": 7287, "text": "protected void ensureOpen(boolean includePendingClose)" }, { "code": null, "e": 7430, "s": 7342, "text": "Used internally to throw an AlreadyClosedException if this IndexWriter has been closed." }, { "code": null, "e": 7452, "s": 7430, "text": "void expungeDeletes()" }, { "code": null, "e": 7464, "s": 7452, "text": "Deprecated." }, { "code": null, "e": 7500, "s": 7464, "text": "void expungeDeletes(boolean doWait)" }, { "code": null, "e": 7512, "s": 7500, "text": "Deprecated." }, { "code": null, "e": 7580, "s": 7512, "text": "protected void flush(boolean triggerMerge, boolean applyAllDeletes)" }, { "code": null, "e": 7656, "s": 7580, "text": "Flushes all in-memory buffered updates (adds and deletes) to the Directory." }, { "code": null, "e": 7745, "s": 7656, "text": "protected void flush(boolean triggerMerge, boolean flushDocStores, boolean flushDeletes)" }, { "code": null, "e": 7856, "s": 7745, "text": "NOTE: flushDocStores is ignored now (hardwired to true); this method is only here for backwards compatibility." }, { "code": null, "e": 7892, "s": 7856, "text": "void forceMerge(int maxNumSegments)" }, { "code": null, "e": 7974, "s": 7892, "text": "This is a force merging policy to merge segments until there's <= maxNumSegments." }, { "code": null, "e": 8026, "s": 7974, "text": "void forceMerge(int maxNumSegments, boolean doWait)" }, { "code": null, "e": 8135, "s": 8026, "text": "Just like forceMerge(int), except you can specify whether the call should block until all merging completes." }, { "code": null, "e": 8160, "s": 8135, "text": "void forceMergeDeletes()" }, { "code": null, "e": 8220, "s": 8160, "text": "Forces merging of all segments that have deleted documents." }, { "code": null, "e": 8259, "s": 8220, "text": "void forceMergeDeletes(boolean doWait)" }, { "code": null, "e": 8379, "s": 8259, "text": "Just like forceMergeDeletes(), except you can specify whether the call should be blocked until the operation completes." }, { "code": null, "e": 8402, "s": 8379, "text": "Analyzer getAnalyzer()" }, { "code": null, "e": 8443, "s": 8402, "text": "Returns the analyzer used by this index." }, { "code": null, "e": 8473, "s": 8443, "text": "IndexWriterConfig getConfig()" }, { "code": null, "e": 8599, "s": 8473, "text": "Returns the private IndexWriterConfig, cloned from the IndexWriterConfig passed to IndexWriter(Directory, IndexWriterConfig)." }, { "code": null, "e": 8641, "s": 8599, "text": "static PrintStream getDefaultInfoStream()" }, { "code": null, "e": 8717, "s": 8641, "text": "Returns the current default infoStream for newly instantiated IndexWriters." }, { "code": null, "e": 8758, "s": 8717, "text": "static long getDefaultWriteLockTimeout()" }, { "code": null, "e": 8830, "s": 8758, "text": "Deprecated. Use IndexWriterConfig.getDefaultWriteLockTimeout() instead." }, { "code": null, "e": 8855, "s": 8830, "text": "Directory getDirectory()" }, { "code": null, "e": 8897, "s": 8855, "text": "Returns the Directory used by this index." }, { "code": null, "e": 8925, "s": 8897, "text": "PrintStream getInfoStream()" }, { "code": null, "e": 8979, "s": 8925, "text": "Returns the current infoStream in use by this writer." }, { "code": null, "e": 9011, "s": 8979, "text": "int getMaxBufferedDeleteTerms()" }, { "code": null, "e": 9082, "s": 9011, "text": "Deprecated. Use IndexWriterConfig.getMaxBufferedDeleteTerms() instead." }, { "code": null, "e": 9107, "s": 9082, "text": "int getMaxBufferedDocs()" }, { "code": null, "e": 9171, "s": 9107, "text": "Deprecated. Use IndexWriterConfig.getMaxBufferedDocs() instead." }, { "code": null, "e": 9195, "s": 9171, "text": "int getMaxFieldLength()" }, { "code": null, "e": 9262, "s": 9195, "text": "Deprecated. Use LimitTokenCountAnalyzer to limit number of tokens." }, { "code": null, "e": 9284, "s": 9262, "text": "int getMaxMergeDocs()" }, { "code": null, "e": 9343, "s": 9284, "text": "Deprecated. Use LogMergePolicy.getMaxMergeDocs() directly." }, { "code": null, "e": 9398, "s": 9343, "text": "IndexWriter.IndexReaderWarmer getMergedSegmentWarmer()" }, { "code": null, "e": 9466, "s": 9398, "text": "Deprecated. Use IndexWriterConfig.getMergedSegmentWarmer() instead." }, { "code": null, "e": 9487, "s": 9466, "text": "int getMergeFactor()" }, { "code": null, "e": 9545, "s": 9487, "text": "Deprecated. Use LogMergePolicy.getMergeFactor() directly." }, { "code": null, "e": 9574, "s": 9545, "text": "MergePolicy getMergePolicy()" }, { "code": null, "e": 9634, "s": 9574, "text": "Deprecated. Use IndexWriterConfig.getMergePolicy() instead." }, { "code": null, "e": 9669, "s": 9634, "text": "MergeScheduler getMergeScheduler()" }, { "code": null, "e": 9731, "s": 9669, "text": "Deprecated. Use IndexWriterConfig.getMergeScheduler() instead" }, { "code": null, "e": 9776, "s": 9731, "text": "Collection<SegmentInfo> getMergingSegments()" }, { "code": null, "e": 9874, "s": 9776, "text": "Expert: to be used by a MergePolicy to a void selecting merges for segments already being merged." }, { "code": null, "e": 9910, "s": 9874, "text": "MergePolicy.OneMerge getNextMerge()" }, { "code": null, "e": 10012, "s": 9910, "text": "Expert: the MergeScheduler calls this method to retrieve the next merge requested by the MergePolicy." }, { "code": null, "e": 10067, "s": 10012, "text": "PayloadProcessorProvider getPayloadProcessorProvider()" }, { "code": null, "e": 10160, "s": 10067, "text": "Returns the PayloadProcessorProvider that is used during segment merges to process payloads." }, { "code": null, "e": 10188, "s": 10160, "text": "double getRAMBufferSizeMB()" }, { "code": null, "e": 10252, "s": 10188, "text": "Deprecated. Use IndexWriterConfig.getRAMBufferSizeMB() instead." }, { "code": null, "e": 10276, "s": 10252, "text": "IndexReader getReader()" }, { "code": null, "e": 10339, "s": 10276, "text": "Deprecated. Use IndexReader.open(IndexWriter,boolean) instead." }, { "code": null, "e": 10388, "s": 10339, "text": "IndexReader getReader(int termInfosIndexDivisor)" }, { "code": null, "e": 10824, "s": 10388, "text": "Deprecated. Use IndexReader.open(IndexWriter,boolean) instead. Furthermore, this method cannot guarantee the reader (and its sub-readers) will be opened with the termInfosIndexDivisor setting because some of them may already have been opened according to IndexWriterConfig.setReaderTermsIndexDivisor(int). You should set the requested termInfosIndexDivisor through IndexWriterConfig.setReaderTermsIndexDivisor(int) and use getReader()." }, { "code": null, "e": 10857, "s": 10824, "text": "int getReaderTermsIndexDivisor()" }, { "code": null, "e": 10929, "s": 10857, "text": "Deprecated. Use IndexWriterConfig.getReaderTermsIndexDivisor() instead." }, { "code": null, "e": 10956, "s": 10929, "text": "Similarity getSimilarity()" }, { "code": null, "e": 11015, "s": 10956, "text": "Deprecated. Use IndexWriterConfig.getSimilarity() instead." }, { "code": null, "e": 11042, "s": 11015, "text": "int getTermIndexInterval()" }, { "code": null, "e": 11100, "s": 11042, "text": "Deprecated. Use IndexWriterConfig.getTermIndexInterval()." }, { "code": null, "e": 11129, "s": 11100, "text": "boolean getUseCompoundFile()" }, { "code": null, "e": 11182, "s": 11129, "text": "Deprecated. Use LogMergePolicy.getUseCompoundFile()." }, { "code": null, "e": 11209, "s": 11182, "text": "long getWriteLockTimeout()" }, { "code": null, "e": 11265, "s": 11209, "text": "Deprecated. Use IndexWriterConfig.getWriteLockTimeout()" }, { "code": null, "e": 11288, "s": 11265, "text": "boolean hasDeletions()" }, { "code": null, "e": 11333, "s": 11288, "text": "static boolean isLocked(Directory directory)" }, { "code": null, "e": 11403, "s": 11333, "text": "Returns true if the index in the named directory is currently locked." }, { "code": null, "e": 11416, "s": 11403, "text": "int maxDoc()" }, { "code": null, "e": 11542, "s": 11416, "text": "Returns total number of docs in this index, including docs not yet flushed (still in the RAM buffer), not counting deletions." }, { "code": null, "e": 11560, "s": 11542, "text": "void maybeMerge()" }, { "code": null, "e": 11768, "s": 11560, "text": "Expert: Asks the mergePolicy whether any merges are necessary now and if so, runs the requested merges and then iterate (test again if merges are needed) until no more merges are returned by the mergePolicy." }, { "code": null, "e": 11807, "s": 11768, "text": "void merge(MergePolicy.OneMerge merge)" }, { "code": null, "e": 11889, "s": 11807, "text": "Merges the indicated segments, replacing them in the stack with a single segment." }, { "code": null, "e": 11918, "s": 11889, "text": "void message(String message)" }, { "code": null, "e": 12060, "s": 11918, "text": "Prints a message to the infoStream (if non-null), prefixed with the identifying information for this writer and the thread that's calling it." }, { "code": null, "e": 12097, "s": 12060, "text": "int numDeletedDocs(SegmentInfo info)" }, { "code": null, "e": 12153, "s": 12097, "text": "Obtains the number of deleted docs for a pooled reader." }, { "code": null, "e": 12167, "s": 12153, "text": "int numDocs()" }, { "code": null, "e": 12294, "s": 12167, "text": "Returns total number of docs in this index, including docs not yet flushed (still in the RAM buffer), and including deletions." }, { "code": null, "e": 12311, "s": 12294, "text": "int numRamDocs()" }, { "code": null, "e": 12378, "s": 12311, "text": "Expert: Returns the number of documents currently buffered in RAM." }, { "code": null, "e": 12394, "s": 12378, "text": "void optimize()" }, { "code": null, "e": 12406, "s": 12394, "text": "Deprecated." }, { "code": null, "e": 12436, "s": 12406, "text": "void optimize(boolean doWait)" }, { "code": null, "e": 12448, "s": 12436, "text": "Deprecated." }, { "code": null, "e": 12482, "s": 12448, "text": "void optimize(int maxNumSegments)" }, { "code": null, "e": 12494, "s": 12482, "text": "Deprecated." }, { "code": null, "e": 12515, "s": 12494, "text": "void prepareCommit()" }, { "code": null, "e": 12543, "s": 12515, "text": "Expert: prepare for commit." }, { "code": null, "e": 12597, "s": 12543, "text": "void prepareCommit(Map<String,String> commitUserData)" }, { "code": null, "e": 12675, "s": 12597, "text": "Expert: Prepare for commit, specifying commitUserData Map (String -> String)." }, { "code": null, "e": 12697, "s": 12675, "text": "long ramSizeInBytes()" }, { "code": null, "e": 12774, "s": 12697, "text": "Expert: Return the total size of all index files currently cached in memory." }, { "code": null, "e": 12790, "s": 12774, "text": "void rollback()" }, { "code": null, "e": 12941, "s": 12790, "text": "Closes the IndexWriter without committing any changes that have occurred since the last commit (or since it was opened, if commit hasn't been called)." }, { "code": null, "e": 12960, "s": 12941, "text": "String segString()" }, { "code": null, "e": 13006, "s": 12960, "text": "String segString(Iterable<SegmentInfo> infos)" }, { "code": null, "e": 13041, "s": 13006, "text": "String segString(SegmentInfo info)" }, { "code": null, "e": 13098, "s": 13041, "text": "static void setDefaultInfoStream(PrintStream infoStream)" }, { "code": null, "e": 13189, "s": 13098, "text": "If non-null, this will be the default infoStream used by a newly instantiated IndexWriter." }, { "code": null, "e": 13251, "s": 13189, "text": "static void setDefaultWriteLockTimeout(long writeLockTimeout)" }, { "code": null, "e": 13327, "s": 13251, "text": "Deprecated. Use IndexWriterConfig.setDefaultWriteLockTimeout(long) instead." }, { "code": null, "e": 13370, "s": 13327, "text": "void setInfoStream(PrintStream infoStream)" }, { "code": null, "e": 13487, "s": 13370, "text": "If non-null, information about merges, deletes and a message when maxFieldLength is reached will be printed to this." }, { "code": null, "e": 13546, "s": 13487, "text": "void setMaxBufferedDeleteTerms(int maxBufferedDeleteTerms)" }, { "code": null, "e": 13620, "s": 13546, "text": "Deprecated. Use IndexWriterConfig.setMaxBufferedDeleteTerms(int) instead." }, { "code": null, "e": 13665, "s": 13620, "text": "void setMaxBufferedDocs(int maxBufferedDocs)" }, { "code": null, "e": 13732, "s": 13665, "text": "Deprecated. Use IndexWriterConfig.setMaxBufferedDocs(int) instead." }, { "code": null, "e": 13775, "s": 13732, "text": "void setMaxFieldLength(int maxFieldLength)" }, { "code": null, "e": 14055, "s": 13775, "text": "Deprecated. Use LimitTokenCountAnalyzer instead. Observe the change in the behavior - the analyzer limits the number of tokens per token stream created, while this setting limits the total number of tokens to index. This matters only if you index many multi-valued fields though." }, { "code": null, "e": 14094, "s": 14055, "text": "void setMaxMergeDocs(int maxMergeDocs)" }, { "code": null, "e": 14156, "s": 14094, "text": "Deprecated. Use LogMergePolicy.setMaxMergeDocs(int) directly." }, { "code": null, "e": 14222, "s": 14156, "text": "void setMergedSegmentWarmer(IndexWriter.IndexReaderWarmer warmer)" }, { "code": null, "e": 14345, "s": 14222, "text": "Deprecated. Use IndexWriterConfig.setMergedSegmentWarmer( org.apache.lucene.index.IndexWriter.IndexReaderWarmer ) instead." }, { "code": null, "e": 14382, "s": 14345, "text": "void setMergeFactor(int mergeFactor)" }, { "code": null, "e": 14443, "s": 14382, "text": "Deprecated. Use LogMergePolicy.setMergeFactor(int) directly." }, { "code": null, "e": 14479, "s": 14443, "text": "void setMergePolicy(MergePolicy mp)" }, { "code": null, "e": 14550, "s": 14479, "text": "Deprecated. Use IndexWriterConfig.setMergePolicy(MergePolicy) instead." }, { "code": null, "e": 14604, "s": 14550, "text": "void setMergeScheduler(MergeScheduler mergeScheduler)" }, { "code": null, "e": 14680, "s": 14604, "text": "Deprecated. Use IndexWriterConfig.setMergeScheduler(MergeScheduler) instead" }, { "code": null, "e": 14743, "s": 14680, "text": "void setPayloadProcessorProvider(PayloadProcessorProvider pcp)" }, { "code": null, "e": 14807, "s": 14743, "text": "Sets the PayloadProcessorProvider to use when merging payloads." }, { "code": null, "e": 14842, "s": 14807, "text": "void setRAMBufferSizeMB(double mb)" }, { "code": null, "e": 14912, "s": 14842, "text": "Deprecated. Use IndexWriterConfig.setRAMBufferSizeMB(double) instead." }, { "code": null, "e": 14957, "s": 14912, "text": "void setReaderTermsIndexDivisor(int divisor)" }, { "code": null, "e": 15032, "s": 14957, "text": "Deprecated. Use IndexWriterConfig.setReaderTermsIndexDivisor(int) instead." }, { "code": null, "e": 15074, "s": 15032, "text": "void setSimilarity(Similarity similarity)" }, { "code": null, "e": 15143, "s": 15074, "text": "Deprecated. Use IndexWriterConfig.setSimilarity(Similarity) instead." }, { "code": null, "e": 15183, "s": 15143, "text": "void setTermIndexInterval(int interval)" }, { "code": null, "e": 15244, "s": 15183, "text": "Deprecated. Use IndexWriterConfig.setTermIndexInterval(int)." }, { "code": null, "e": 15283, "s": 15244, "text": "void setUseCompoundFile(boolean value)" }, { "code": null, "e": 15343, "s": 15283, "text": "Deprecated. Use LogMergePolicy.setUseCompoundFile(boolean)." }, { "code": null, "e": 15391, "s": 15343, "text": "void setWriteLockTimeout(long writeLockTimeout)" }, { "code": null, "e": 15461, "s": 15391, "text": "Deprecated. Use IndexWriterConfig.setWriteLockTimeout(long) instead. " }, { "code": null, "e": 15501, "s": 15461, "text": "static void unlock(Directory directory)" }, { "code": null, "e": 15552, "s": 15501, "text": "Forcibly unlocks the index in the named directory." }, { "code": null, "e": 15597, "s": 15552, "text": "void updateDocument(Term term, Document doc)" }, { "code": null, "e": 15700, "s": 15597, "text": "Updates a document by first deleting the document(s) containing term and then adding the new document." }, { "code": null, "e": 15764, "s": 15700, "text": "void updateDocument(Term term, Document doc, Analyzer analyzer)" }, { "code": null, "e": 15867, "s": 15764, "text": "Updates a document by first deleting the document(s) containing term and then adding the new document." }, { "code": null, "e": 15929, "s": 15867, "text": "void updateDocuments(Term delTerm, Collection<Document> docs)" }, { "code": null, "e": 16127, "s": 15929, "text": "Atomically deletes documents matching the provided delTerm and adds a block of documents with sequentially assigned document IDs, such that an external reader will see all or none of the documents." }, { "code": null, "e": 16208, "s": 16127, "text": "void updateDocuments(Term delTerm, Collection<Document> docs, Analyzer analyzer)" }, { "code": null, "e": 16445, "s": 16208, "text": "Atomically deletes documents matching the provided delTerm and adds a block of documents, analyzed using the provided analyzer, with sequentially assigned document IDs, such that an external reader will see all or none of the documents." }, { "code": null, "e": 16463, "s": 16445, "text": "boolean verbose()" }, { "code": null, "e": 16519, "s": 16463, "text": "Returns true if verbosing is enabled (i.e., infoStream)" }, { "code": null, "e": 16540, "s": 16519, "text": "void waitForMerges()" }, { "code": null, "e": 16594, "s": 16540, "text": "Waits for any currently outstanding merges to finish." }, { "code": null, "e": 16651, "s": 16594, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 16668, "s": 16651, "text": "java.lang.Object" }, { "code": null, "e": 16675, "s": 16668, "text": " Print" }, { "code": null, "e": 16686, "s": 16675, "text": " Add Notes" } ]
MySQLi - Like Clause
We have seen the SQL SELECT command to fetch data from the MySQL table. We can also use a conditional clause called as the WHERE clause to select the required records. A WHERE clause with the ‘equal to’ sign (=) works fine where we want to do an exact match. Like if "tutorial_author = 'Sanjay'". But there may be a requirement where we want to filter out all the results where tutorial_author name should contain "jay". This can be handled using SQL LIKE Clause along with the WHERE clause. If the SQL LIKE clause is used along with the % character, then it will work like a meta character (*) as in UNIX, while listing out all the files or directories at the command prompt. Without a % character, the LIKE clause is very same as the equal to sign along with the WHERE clause. The following code block has a generic SQL syntax of the SELECT command along with the LIKE clause to fetch data from a MySQL table. SELECT field1, field2,...fieldN table_name1, table_name2... WHERE field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue' You can specify any condition using the WHERE clause. You can specify any condition using the WHERE clause. You can use the LIKE clause along with the WHERE clause. You can use the LIKE clause along with the WHERE clause. You can use the LIKE clause in place of the equals to sign. You can use the LIKE clause in place of the equals to sign. When LIKE is used along with % sign then it will work like a meta character search. When LIKE is used along with % sign then it will work like a meta character search. You can specify more than one condition using AND or OR operators. You can specify more than one condition using AND or OR operators. A WHERE...LIKE clause can be used along with DELETE or UPDATE SQL command also to specify a condition. A WHERE...LIKE clause can be used along with DELETE or UPDATE SQL command also to specify a condition. This will use the SQL SELECT command with the WHERE...LIKE clause to fetch the selected data from the MySQL table – tutorials_tbl. The following example will return all the records from the tutorials_tbl table for which the author name ends with jay − root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from tutorials_tbl → WHERE tutorial_author LIKE '%jay'; +-------------+----------------+-----------------+-----------------+ | tutorial_id | tutorial_title | tutorial_author | submission_date | +-------------+----------------+-----------------+-----------------+ | 3 | JAVA Tutorial | Sanjay | 2007-05-21 | +-------------+----------------+-----------------+-----------------+ 1 rows in set (0.01 sec) mysql> PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using Like clause. This function takes two parameters and returns TRUE on success or FALSE on failure. $mysqli→query($sql,$resultmode) $sql Required - SQL query to select records in a MySQL table using Like Clause. $resultmode Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used. Try the following example to select a record using like clause in a table − Copy and paste the following example as mysql_example.php − <html> <head> <title>Using Like Clause</title> </head> <body> <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'root@123'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($mysqli→connect_errno ) { printf("Connect failed: %s<br />", $mysqli→connect_error); exit(); } printf('Connected successfully.<br />'); $sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl where tutorial_author like "Mah%"'; $result = $mysqli→query($sql); if ($result→num_rows > 0) { while($row = $result→fetch_assoc()) { printf("Id: %s, Title: %s, Author: %s, Date: %d <br />", $row["tutorial_id"], $row["tutorial_title"], $row["tutorial_author"], $row["submission_date"]); } } else { printf('No record found.<br />'); } mysqli_free_result($result); $mysqli→close(); ?> </body> </html> Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script. Connected successfully. Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021 Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021 Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021 14 Lectures 1.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2431, "s": 2263, "text": "We have seen the SQL SELECT command to fetch data from the MySQL table. We can also use a conditional clause called as the WHERE clause to select the required records." }, { "code": null, "e": 2755, "s": 2431, "text": "A WHERE clause with the ‘equal to’ sign (=) works fine where we want to do an exact match. Like if \"tutorial_author = 'Sanjay'\". But there may be a requirement where we want to filter out all the results where tutorial_author name should contain \"jay\". This can be handled using SQL LIKE Clause along with the WHERE clause." }, { "code": null, "e": 3042, "s": 2755, "text": "If the SQL LIKE clause is used along with the % character, then it will work like a meta character (*) as in UNIX, while listing out all the files or directories at the command prompt. Without a % character, the LIKE clause is very same as the equal to sign along with the WHERE clause." }, { "code": null, "e": 3175, "s": 3042, "text": "The following code block has a generic SQL syntax of the SELECT command along with the LIKE clause to fetch data from a MySQL table." }, { "code": null, "e": 3297, "s": 3175, "text": "SELECT field1, field2,...fieldN table_name1, table_name2...\nWHERE field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue'\n" }, { "code": null, "e": 3351, "s": 3297, "text": "You can specify any condition using the WHERE clause." }, { "code": null, "e": 3405, "s": 3351, "text": "You can specify any condition using the WHERE clause." }, { "code": null, "e": 3462, "s": 3405, "text": "You can use the LIKE clause along with the WHERE clause." }, { "code": null, "e": 3519, "s": 3462, "text": "You can use the LIKE clause along with the WHERE clause." }, { "code": null, "e": 3579, "s": 3519, "text": "You can use the LIKE clause in place of the equals to sign." }, { "code": null, "e": 3639, "s": 3579, "text": "You can use the LIKE clause in place of the equals to sign." }, { "code": null, "e": 3723, "s": 3639, "text": "When LIKE is used along with % sign then it will work like a meta character search." }, { "code": null, "e": 3807, "s": 3723, "text": "When LIKE is used along with % sign then it will work like a meta character search." }, { "code": null, "e": 3874, "s": 3807, "text": "You can specify more than one condition using AND or OR operators." }, { "code": null, "e": 3941, "s": 3874, "text": "You can specify more than one condition using AND or OR operators." }, { "code": null, "e": 4044, "s": 3941, "text": "A WHERE...LIKE clause can be used along with DELETE or UPDATE SQL command also to specify a condition." }, { "code": null, "e": 4147, "s": 4044, "text": "A WHERE...LIKE clause can be used along with DELETE or UPDATE SQL command also to specify a condition." }, { "code": null, "e": 4278, "s": 4147, "text": "This will use the SQL SELECT command with the WHERE...LIKE clause to fetch the selected data from the MySQL table – tutorials_tbl." }, { "code": null, "e": 4399, "s": 4278, "text": "The following example will return all the records from the tutorials_tbl table for which the author name ends with jay −" }, { "code": null, "e": 4956, "s": 4399, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT * from tutorials_tbl \n → WHERE tutorial_author LIKE '%jay';\n+-------------+----------------+-----------------+-----------------+\n| tutorial_id | tutorial_title | tutorial_author | submission_date |\n+-------------+----------------+-----------------+-----------------+\n| 3 | JAVA Tutorial | Sanjay | 2007-05-21 | \n+-------------+----------------+-----------------+-----------------+\n1 rows in set (0.01 sec)\n\nmysql>" }, { "code": null, "e": 5144, "s": 4956, "text": "PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using Like clause. This function takes two parameters and returns TRUE on success or FALSE on failure." }, { "code": null, "e": 5177, "s": 5144, "text": "$mysqli→query($sql,$resultmode)\n" }, { "code": null, "e": 5182, "s": 5177, "text": "$sql" }, { "code": null, "e": 5257, "s": 5182, "text": "Required - SQL query to select records in a MySQL table using Like Clause." }, { "code": null, "e": 5269, "s": 5257, "text": "$resultmode" }, { "code": null, "e": 5417, "s": 5269, "text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used." }, { "code": null, "e": 5493, "s": 5417, "text": "Try the following example to select a record using like clause in a table −" }, { "code": null, "e": 5553, "s": 5493, "text": "Copy and paste the following example as mysql_example.php −" }, { "code": null, "e": 6758, "s": 5553, "text": "<html>\n <head>\n <title>Using Like Clause</title>\n </head>\n <body>\n <?php\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqli→connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli→connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n \n $sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl where tutorial_author like \"Mah%\"';\n\t\t \n $result = $mysqli→query($sql);\n \n if ($result→num_rows > 0) {\n while($row = $result→fetch_assoc()) {\n printf(\"Id: %s, Title: %s, Author: %s, Date: %d <br />\", \n $row[\"tutorial_id\"], \n $row[\"tutorial_title\"], \n $row[\"tutorial_author\"],\n $row[\"submission_date\"]); \n }\n } else {\n printf('No record found.<br />');\n }\n mysqli_free_result($result);\n $mysqli→close();\n ?>\n </body>\n</html>" }, { "code": null, "e": 6923, "s": 6758, "text": "Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script." }, { "code": null, "e": 7116, "s": 6923, "text": "Connected successfully.\nId: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021\nId: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021\nId: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021\n" }, { "code": null, "e": 7151, "s": 7116, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7174, "s": 7151, "text": " Stone River ELearning" }, { "code": null, "e": 7181, "s": 7174, "text": " Print" }, { "code": null, "e": 7192, "s": 7181, "text": " Add Notes" } ]
Ruby | Array to_h() function - GeeksforGeeks
05 Dec, 2019 Array#to_h() : to_h() is a Array class method which returns the result of interpreting ary as an array of [key, value] pairs. Syntax: Array.to_h() Parameter: Array Return: the result of interpreting ary as an array of [key, value] pairs. Example #1 : # Ruby code for to_h() method # declaring arraya = [[:foo, :bar], [1, 2]] # to_h method exampleputs "to_h() method form : #{a.to_h()}\n\n" Output : to_h() method form : {:foo=>:bar, 1=>2} Example #2 : # Ruby code for to_h() method # declaring arraya = [[:geeks, :geeks], [1, 2]] # to_h method exampleputs "to_h() method form : #{a.to_h{|s| [s.ord, s]}}\n\n" Output : to_h() method form : {:geeks=>:geeks, 1=>2} Ruby Array-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Ruby | Array count() operation Ruby | Array select() function Ruby | Enumerator each_with_index function Global Variable in Ruby Ruby | Hash delete() function Ruby | String gsub! Method Include v/s Extend in Ruby Ruby | Case Statement Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1 Ruby | Data Types
[ { "code": null, "e": 23760, "s": 23732, "text": "\n05 Dec, 2019" }, { "code": null, "e": 23886, "s": 23760, "text": "Array#to_h() : to_h() is a Array class method which returns the result of interpreting ary as an array of [key, value] pairs." }, { "code": null, "e": 23907, "s": 23886, "text": "Syntax: Array.to_h()" }, { "code": null, "e": 23924, "s": 23907, "text": "Parameter: Array" }, { "code": null, "e": 23998, "s": 23924, "text": "Return: the result of interpreting ary as an array of [key, value] pairs." }, { "code": null, "e": 24011, "s": 23998, "text": "Example #1 :" }, { "code": "# Ruby code for to_h() method # declaring arraya = [[:foo, :bar], [1, 2]] # to_h method exampleputs \"to_h() method form : #{a.to_h()}\\n\\n\"", "e": 24152, "s": 24011, "text": null }, { "code": null, "e": 24161, "s": 24152, "text": "Output :" }, { "code": null, "e": 24203, "s": 24161, "text": "to_h() method form : {:foo=>:bar, 1=>2}\n\n" }, { "code": null, "e": 24216, "s": 24203, "text": "Example #2 :" }, { "code": "# Ruby code for to_h() method # declaring arraya = [[:geeks, :geeks], [1, 2]] # to_h method exampleputs \"to_h() method form : #{a.to_h{|s| [s.ord, s]}}\\n\\n\"", "e": 24375, "s": 24216, "text": null }, { "code": null, "e": 24384, "s": 24375, "text": "Output :" }, { "code": null, "e": 24430, "s": 24384, "text": "to_h() method form : {:geeks=>:geeks, 1=>2}\n\n" }, { "code": null, "e": 24447, "s": 24430, "text": "Ruby Array-class" }, { "code": null, "e": 24460, "s": 24447, "text": "Ruby-Methods" }, { "code": null, "e": 24465, "s": 24460, "text": "Ruby" }, { "code": null, "e": 24563, "s": 24465, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24572, "s": 24563, "text": "Comments" }, { "code": null, "e": 24585, "s": 24572, "text": "Old Comments" }, { "code": null, "e": 24616, "s": 24585, "text": "Ruby | Array count() operation" }, { "code": null, "e": 24647, "s": 24616, "text": "Ruby | Array select() function" }, { "code": null, "e": 24690, "s": 24647, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 24714, "s": 24690, "text": "Global Variable in Ruby" }, { "code": null, "e": 24744, "s": 24714, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 24771, "s": 24744, "text": "Ruby | String gsub! Method" }, { "code": null, "e": 24798, "s": 24771, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 24820, "s": 24798, "text": "Ruby | Case Statement" }, { "code": null, "e": 24888, "s": 24820, "text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1" } ]
Spring Boot Redis Cache Example | Redis @Cachable @Cacheput
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to see how to work with Spring Boot Redis Cache using Redis Server as backend. In our previous tutorials, we have seen how to work with Spring Boot Data Redis where we implemented all CRUD operations on Redis. If you are not familiar with Redis CRUD operations, I recommend you to go through once. This Redis Cache example goes on top of the CRUD operations. Spring Boot 2.1.4 Spring Boot Redis Cache Redis server 2.4.5 Jedis Java8 Maven <?xml version="1.0" encoding="UTF-8"?> <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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.onlinetutorialspoint</groupId> <artifactId>Spring-Boot-Redis-Cache-Example</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Spring-Boot-Redis-Cache-Example</name> <description>Spring Boot Redis Cache Example</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.3</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Making spring boot application server port as 8082 and defining spring cache type as redis. This is recommended because spring supports different cache implementations like EhCache, HazelCastCache, etc. spring.cache.type=redis server.port=8082 As part of this example, I am going to save data into my local redis server, and the data should be cached into redis cache whenever we get it from the server initially. To connect with redis server (for me it is in local, and it can be remote server also), we have to make the JedisTemplate (it is something similar like JdbcTemplate) through the JedisConnectionFactory object. package com.onlinetutorialspoint; import com.onlinetutorialspoint.model.Item; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; @SpringBootApplication @EnableCaching public class SpringBootRedisCacheExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRedisCacheExampleApplication.class, args); } @Bean JedisConnectionFactory jedisConnectionFactory(){ return new JedisConnectionFactory(); } @Bean RedisTemplate<String, Item> redisTemplate(){ RedisTemplate<String,Item> redisTemplate = new RedisTemplate<String, Item>(); redisTemplate.setConnectionFactory(jedisConnectionFactory()); return redisTemplate; } } Creating Item.class which will act as a JSON message to save in Redis server. package com.onlinetutorialspoint.model; import java.io.Serializable; public class Item implements Serializable { private int id; private String name; private String category; public Item() { } public Item(int id, String name, String category) { this.id = id; this.name = name; this.category = category; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } } Create ItemController.java it provides essential CRUD endpoints. There is nothing unusual in this class. package com.onlinetutorialspoint.controller; import com.onlinetutorialspoint.cache.ItemCache; import com.onlinetutorialspoint.model.Item; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; @RestController public class ItemController { @Autowired ItemCache itemCache; @GetMapping("/item/{itemId}") @ResponseBody public ResponseEntity<Item> getItem(@PathVariable int itemId){ Item item = itemCache.getItem(itemId); return new ResponseEntity<Item>(item, HttpStatus.OK); } @PostMapping(value = "/addItem",consumes = {"application/json"},produces = {"application/json"}) @ResponseBody public ResponseEntity<Item> addItem(@RequestBody Item item, UriComponentsBuilder builder){ itemCache.addItem(item); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/addItem/{id}").buildAndExpand(item.getId()).toUri()); return new ResponseEntity<Item>(headers, HttpStatus.CREATED); } @PutMapping("/updateItem") @ResponseBody public ResponseEntity<Item> updateItem(@RequestBody Item item){ if(item != null){ itemCache.updateItem(item); } return new ResponseEntity<Item>(item, HttpStatus.OK); } @DeleteMapping("/delete/{id}") @ResponseBody public ResponseEntity<Void> deleteItem(@PathVariable int id){ itemCache.deleteItem(id); return new ResponseEntity<Void>(HttpStatus.ACCEPTED); } } Creating ItemCache.java which has all the Spring cache components. For more details on Spring Cache Abstraction, please refer this document. package com.onlinetutorialspoint.cache; import com.onlinetutorialspoint.model.Item; import com.onlinetutorialspoint.repo.ItemRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; @Component public class ItemCache { @Autowired ItemRepository itemRepo; @Cacheable(value="itemCache", key="#id") public Item getItem(int id){ System.out.println("In getItem cache Component.."); Item item = null; try{ item = itemRepo.getItem(id); }catch(Exception e){ e.printStackTrace(); } return item; } @CacheEvict(value="itemCache",key = "#id") public void deleteItem(int id){ System.out.println("In deleteItem cache Component.."); itemRepo.deleteItem(id); } @CachePut(value="itemCache",key = "#id") public void addItem(Item item){ System.out.println("In addItem cache component.."); itemRepo.addItem(item); } @CachePut(value="itemCache",key = "#id",condition = "#result != null") public void updateItem(Item item){ System.out.println("In UpdateItem cache Component.."); itemRepo.updateItem(item); } } Creating spring boot data operations. Refer our previous tutorial on spring data CRUD operations example to get more details on this. package com.onlinetutorialspoint.repo; import com.onlinetutorialspoint.model.Item; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Repository; import java.util.Map; @Repository public class ItemRepository { public static final String KEY = "ITEM"; private RedisTemplate<String, Item> redisTemplate; private HashOperations hashOperations; public ItemRepository(RedisTemplate<String, Item> redisTemplate) { this.redisTemplate = redisTemplate; hashOperations = redisTemplate.opsForHash(); } /*Getting a specific item by item id from table*/ public Item getItem(int itemId){ return (Item) hashOperations.get(KEY,itemId); } /*Adding an item into redis database*/ public void addItem(Item item){ hashOperations.put(KEY,item.getId(),item); } /*delete an item from database*/ public void deleteItem(int id){ hashOperations.delete(KEY,id); } /*update an item from database*/ public void updateItem(Item item){ addItem(item); } } $mvn clean install $mvn spring-boot:run [INFO] --- spring-boot-maven-plugin:2.1.4.RELEASE:run (default-cli) @ Spring-Boot-Redis-Cache-Example --- . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.4.RELEASE) 2019-04-21 21:33:34.057 INFO 7372 --- [ main] o.SpringBootRedisCacheExampleApplication : Starting SpringBootRedisCacheExampleApplication on DESKTOP-RN4SMHT with PID 7372 (D:\w ork\Spring-Boot-Redis-Cache-Example\target\classes started by Lenovo in D:\work\Spring-Boot-Redis-Cache-Example) 2019-04-21 21:33:34.066 INFO 7372 --- [ main] o.SpringBootRedisCacheExampleApplication : No active profile set, falling back to default profiles: default 2019-04-21 21:33:35.645 INFO 7372 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode! 2019-04-21 21:33:35.650 INFO 7372 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode. 2019-04-21 21:33:35.712 INFO 7372 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 33ms. Found 0 repository interfaces. 2019-04-21 21:33:37.105 INFO 7372 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8082 (http) 2019-04-21 21:33:37.166 INFO 7372 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2019-04-21 21:33:37.167 INFO 7372 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17] 2019-04-21 21:33:37.448 INFO 7372 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2019-04-21 21:33:37.448 INFO 7372 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3197 ms 2019-04-21 21:33:38.772 INFO 7372 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2019-04-21 21:33:40.198 INFO 7372 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8082 (http) with context path '' 2019-04-21 21:33:40.204 INFO 7372 --- [ main] o.SpringBootRedisCacheExampleApplication : Started SpringBootRedisCacheExampleApplication in 7.09 seconds (JVM running for 14.688 Make sure you have to start the Redis server and run the redis-cli.exe file to monitor the requests. Adding an Item to Redis DB: Redis-cli.exe – Monitor We can see the logs while inserting an item into the redis server. Getting the same Item from redis server: This item should be taken from redis as this is a first time and this should be stored in redis cache For the next subsequent calls, this item should be taken from redis cache. So reread the same thing and let’s check the logs. This call should take the item from redis cache. On the above log statements, we can say that the data were coming from redis cache (As it is a simple GET operation). Spring Cache Reference Spring Boot Redis Data Happy Learning 🙂 Spring Boot Kafka Producer Example Spring Boot Kafka Consume JSON Messages Example How to set Spring Boot SetTimeZone Sending Spring Boot Kafka JSON Message to Kafka Topic Spring Boot RabbitMQ Message Publishing Example How To Change Spring Boot Context Path Spring Boot DataRest Example RepositoryRestResource Setup/Install Redis Server on Windows 10 Spring Boot Hazelcast Cache Example Spring Boot Redis Data Example CRUD Operations MicroServices Spring Boot Eureka Server Example Spring Boot How to change the Tomcat to Jetty Server Spring Boot EhCache Example Spring Boot MongoDB + Spring Data Example Spring Boot MVC Example Tutorials Spring Boot Kafka Producer Example Spring Boot Kafka Consume JSON Messages Example How to set Spring Boot SetTimeZone Sending Spring Boot Kafka JSON Message to Kafka Topic Spring Boot RabbitMQ Message Publishing Example How To Change Spring Boot Context Path Spring Boot DataRest Example RepositoryRestResource Setup/Install Redis Server on Windows 10 Spring Boot Hazelcast Cache Example Spring Boot Redis Data Example CRUD Operations MicroServices Spring Boot Eureka Server Example Spring Boot How to change the Tomcat to Jetty Server Spring Boot EhCache Example Spring Boot MongoDB + Spring Data Example Spring Boot MVC Example Tutorials Soleil September 13, 2019 at 1:54 pm - Reply Hi, could you give a tutorial or the CacheManager java config for cache a list to redis? Thanks Fernando October 17, 2019 at 8:56 am - Reply Hi, I’m testing the demo, but the getItem does not work. It seems like the ItemRepo was not injected. Soleil September 13, 2019 at 1:54 pm - Reply Hi, could you give a tutorial or the CacheManager java config for cache a list to redis? Thanks Hi, could you give a tutorial or the CacheManager java config for cache a list to redis? Thanks Fernando October 17, 2019 at 8:56 am - Reply Hi, I’m testing the demo, but the getItem does not work. It seems like the ItemRepo was not injected. Hi, I’m testing the demo, but the getItem does not work. It seems like the ItemRepo was not injected. Δ Spring Boot – Hello World Spring Boot – MVC Example Spring Boot- Change Context Path Spring Boot – Change Tomcat Port Number Spring Boot – Change Tomcat to Jetty Server Spring Boot – Tomcat session timeout Spring Boot – Enable Random Port Spring Boot – Properties File Spring Boot – Beans Lazy Loading Spring Boot – Set Favicon image Spring Boot – Set Custom Banner Spring Boot – Set Application TimeZone Spring Boot – Send Mail Spring Boot – FileUpload Ajax Spring Boot – Actuator Spring Boot – Actuator Database Health Check Spring Boot – Swagger Spring Boot – Enable CORS Spring Boot – External Apache ActiveMQ Setup Spring Boot – Inmemory Apache ActiveMq Spring Boot – Scheduler Job Spring Boot – Exception Handling Spring Boot – Hibernate CRUD Spring Boot – JPA Integration CRUD Spring Boot – JPA DataRest CRUD Spring Boot – JdbcTemplate CRUD Spring Boot – Multiple Data Sources Config Spring Boot – JNDI Configuration Spring Boot – H2 Database CRUD Spring Boot – MongoDB CRUD Spring Boot – Redis Data CRUD Spring Boot – MVC Login Form Validation Spring Boot – Custom Error Pages Spring Boot – iText PDF Spring Boot – Enable SSL (HTTPs) Spring Boot – Basic Authentication Spring Boot – In Memory Basic Authentication Spring Boot – Security MySQL Database Integration Spring Boot – Redis Cache – Redis Server Spring Boot – Hazelcast Cache Spring Boot – EhCache Spring Boot – Kafka Producer Spring Boot – Kafka Consumer Spring Boot – Kafka JSON Message to Kafka Topic Spring Boot – RabbitMQ Publisher Spring Boot – RabbitMQ Consumer Spring Boot – SOAP Consumer Spring Boot – Soap WebServices Spring Boot – Batch Csv to Database Spring Boot – Eureka Server Spring Boot – MockMvc JUnit Spring Boot – Docker Deployment
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 508, "s": 398, "text": "In this tutorial, we are going to see how to work with Spring Boot Redis Cache using Redis Server as backend." }, { "code": null, "e": 727, "s": 508, "text": "In our previous tutorials, we have seen how to work with Spring Boot Data Redis where we implemented all CRUD operations on Redis. If you are not familiar with Redis CRUD operations, I recommend you to go through once." }, { "code": null, "e": 788, "s": 727, "text": "This Redis Cache example goes on top of the CRUD operations." }, { "code": null, "e": 806, "s": 788, "text": "Spring Boot 2.1.4" }, { "code": null, "e": 830, "s": 806, "text": "Spring Boot Redis Cache" }, { "code": null, "e": 849, "s": 830, "text": "Redis server 2.4.5" }, { "code": null, "e": 855, "s": 849, "text": "Jedis" }, { "code": null, "e": 861, "s": 855, "text": "Java8" }, { "code": null, "e": 867, "s": 861, "text": "Maven" }, { "code": null, "e": 2357, "s": 867, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.1.4.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n <groupId>com.onlinetutorialspoint</groupId>\n <artifactId>Spring-Boot-Redis-Cache-Example</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <name>Spring-Boot-Redis-Cache-Example</name>\n <description>Spring Boot Redis Cache Example</description>\n <properties>\n <java.version>1.8</java.version>\n </properties>\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-data-redis</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>redis.clients</groupId>\n <artifactId>jedis</artifactId>\n <version>2.9.3</version>\n </dependency>\n </dependencies>\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n</project>\n" }, { "code": null, "e": 2560, "s": 2357, "text": "Making spring boot application server port as 8082 and defining spring cache type as redis. This is recommended because spring supports different cache implementations like EhCache, HazelCastCache, etc." }, { "code": null, "e": 2601, "s": 2560, "text": "spring.cache.type=redis\nserver.port=8082" }, { "code": null, "e": 2771, "s": 2601, "text": "As part of this example, I am going to save data into my local redis server, and the data should be cached into redis cache whenever we get it from the server initially." }, { "code": null, "e": 2980, "s": 2771, "text": "To connect with redis server (for me it is in local, and it can be remote server also), we have to make the JedisTemplate (it is something similar like JdbcTemplate) through the JedisConnectionFactory object." }, { "code": null, "e": 3988, "s": 2980, "text": "package com.onlinetutorialspoint;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cache.annotation.EnableCaching;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.data.redis.connection.jedis.JedisConnectionFactory;\nimport org.springframework.data.redis.core.RedisTemplate;\n\n@SpringBootApplication\n@EnableCaching\npublic class SpringBootRedisCacheExampleApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(SpringBootRedisCacheExampleApplication.class, args);\n }\n @Bean\n JedisConnectionFactory jedisConnectionFactory(){\n return new JedisConnectionFactory();\n }\n\n @Bean\n RedisTemplate<String, Item> redisTemplate(){\n RedisTemplate<String,Item> redisTemplate = new RedisTemplate<String, Item>();\n redisTemplate.setConnectionFactory(jedisConnectionFactory());\n return redisTemplate;\n }\n}\n" }, { "code": null, "e": 4066, "s": 3988, "text": "Creating Item.class which will act as a JSON message to save in Redis server." }, { "code": null, "e": 4826, "s": 4066, "text": "package com.onlinetutorialspoint.model;\n\nimport java.io.Serializable;\n\npublic class Item implements Serializable {\n private int id;\n private String name;\n private String category;\n\n public Item() {\n }\n\n public Item(int id, String name, String category) {\n this.id = id;\n this.name = name;\n this.category = category;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCategory() {\n return category;\n }\n\n public void setCategory(String category) {\n this.category = category;\n }\n}\n" }, { "code": null, "e": 4931, "s": 4826, "text": "Create ItemController.java it provides essential CRUD endpoints. There is nothing unusual in this class." }, { "code": null, "e": 6658, "s": 4931, "text": "package com.onlinetutorialspoint.controller;\n\nimport com.onlinetutorialspoint.cache.ItemCache;\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.util.UriComponentsBuilder;\n\n@RestController\npublic class ItemController {\n\n @Autowired\n ItemCache itemCache;\n\n @GetMapping(\"/item/{itemId}\")\n @ResponseBody\n public ResponseEntity<Item> getItem(@PathVariable int itemId){\n Item item = itemCache.getItem(itemId);\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @PostMapping(value = \"/addItem\",consumes = {\"application/json\"},produces = {\"application/json\"})\n @ResponseBody\n public ResponseEntity<Item> addItem(@RequestBody Item item, UriComponentsBuilder builder){\n itemCache.addItem(item);\n HttpHeaders headers = new HttpHeaders();\n headers.setLocation(builder.path(\"/addItem/{id}\").buildAndExpand(item.getId()).toUri());\n return new ResponseEntity<Item>(headers, HttpStatus.CREATED);\n }\n\n @PutMapping(\"/updateItem\")\n @ResponseBody\n public ResponseEntity<Item> updateItem(@RequestBody Item item){\n if(item != null){\n itemCache.updateItem(item);\n }\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @DeleteMapping(\"/delete/{id}\")\n @ResponseBody\n public ResponseEntity<Void> deleteItem(@PathVariable int id){\n itemCache.deleteItem(id);\n return new ResponseEntity<Void>(HttpStatus.ACCEPTED);\n }\n}\n" }, { "code": null, "e": 6799, "s": 6658, "text": "Creating ItemCache.java which has all the Spring cache components. For more details on Spring Cache Abstraction, please refer this document." }, { "code": null, "e": 8200, "s": 6799, "text": "package com.onlinetutorialspoint.cache;\n\nimport com.onlinetutorialspoint.model.Item;\nimport com.onlinetutorialspoint.repo.ItemRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.cache.annotation.CacheEvict;\nimport org.springframework.cache.annotation.CachePut;\nimport org.springframework.cache.annotation.Cacheable;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class ItemCache {\n @Autowired\n ItemRepository itemRepo;\n\n @Cacheable(value=\"itemCache\", key=\"#id\")\n public Item getItem(int id){\n System.out.println(\"In getItem cache Component..\");\n Item item = null;\n try{\n item = itemRepo.getItem(id);\n }catch(Exception e){\n e.printStackTrace();\n }\n return item;\n }\n @CacheEvict(value=\"itemCache\",key = \"#id\")\n public void deleteItem(int id){\n System.out.println(\"In deleteItem cache Component..\");\n itemRepo.deleteItem(id);\n }\n\n @CachePut(value=\"itemCache\",key = \"#id\")\n public void addItem(Item item){\n System.out.println(\"In addItem cache component..\");\n itemRepo.addItem(item);\n }\n\n @CachePut(value=\"itemCache\",key = \"#id\",condition = \"#result != null\")\n public void updateItem(Item item){\n System.out.println(\"In UpdateItem cache Component..\");\n itemRepo.updateItem(item);\n }\n}\n" }, { "code": null, "e": 8334, "s": 8200, "text": "Creating spring boot data operations. Refer our previous tutorial on spring data CRUD operations example to get more details on this." }, { "code": null, "e": 9486, "s": 8334, "text": "package com.onlinetutorialspoint.repo;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.data.redis.core.HashOperations;\nimport org.springframework.data.redis.core.RedisTemplate;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.Map;\n\n@Repository\npublic class ItemRepository {\n\n public static final String KEY = \"ITEM\";\n private RedisTemplate<String, Item> redisTemplate;\n private HashOperations hashOperations;\n\n public ItemRepository(RedisTemplate<String, Item> redisTemplate) {\n this.redisTemplate = redisTemplate;\n hashOperations = redisTemplate.opsForHash();\n }\n\n /*Getting a specific item by item id from table*/\n public Item getItem(int itemId){\n return (Item) hashOperations.get(KEY,itemId);\n }\n\n /*Adding an item into redis database*/\n public void addItem(Item item){\n hashOperations.put(KEY,item.getId(),item);\n }\n /*delete an item from database*/\n public void deleteItem(int id){\n hashOperations.delete(KEY,id);\n }\n\n /*update an item from database*/\n public void updateItem(Item item){\n addItem(item);\n }\n}\n" }, { "code": null, "e": 12147, "s": 9486, "text": "$mvn clean install\n$mvn spring-boot:run\n[INFO] --- spring-boot-maven-plugin:2.1.4.RELEASE:run (default-cli) @ Spring-Boot-Redis-Cache-Example ---\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.1.4.RELEASE)\n\n2019-04-21 21:33:34.057 INFO 7372 --- [ main] o.SpringBootRedisCacheExampleApplication : Starting SpringBootRedisCacheExampleApplication on DESKTOP-RN4SMHT with PID 7372 (D:\\w\nork\\Spring-Boot-Redis-Cache-Example\\target\\classes started by Lenovo in D:\\work\\Spring-Boot-Redis-Cache-Example)\n2019-04-21 21:33:34.066 INFO 7372 --- [ main] o.SpringBootRedisCacheExampleApplication : No active profile set, falling back to default profiles: default\n2019-04-21 21:33:35.645 INFO 7372 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!\n2019-04-21 21:33:35.650 INFO 7372 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.\n2019-04-21 21:33:35.712 INFO 7372 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 33ms. Found 0 repository interfaces.\n2019-04-21 21:33:37.105 INFO 7372 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8082 (http)\n2019-04-21 21:33:37.166 INFO 7372 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]\n2019-04-21 21:33:37.167 INFO 7372 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17]\n2019-04-21 21:33:37.448 INFO 7372 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext\n2019-04-21 21:33:37.448 INFO 7372 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3197 ms\n2019-04-21 21:33:38.772 INFO 7372 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'\n2019-04-21 21:33:40.198 INFO 7372 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8082 (http) with context path ''\n2019-04-21 21:33:40.204 INFO 7372 --- [ main] o.SpringBootRedisCacheExampleApplication : Started SpringBootRedisCacheExampleApplication in 7.09 seconds (JVM running for 14.688" }, { "code": null, "e": 12248, "s": 12147, "text": "Make sure you have to start the Redis server and run the redis-cli.exe file to monitor the requests." }, { "code": null, "e": 12276, "s": 12248, "text": "Adding an Item to Redis DB:" }, { "code": null, "e": 12300, "s": 12276, "text": "Redis-cli.exe – Monitor" }, { "code": null, "e": 12367, "s": 12300, "text": "We can see the logs while inserting an item into the redis server." }, { "code": null, "e": 12408, "s": 12367, "text": "Getting the same Item from redis server:" }, { "code": null, "e": 12510, "s": 12408, "text": "This item should be taken from redis as this is a first time and this should be stored in redis cache" }, { "code": null, "e": 12636, "s": 12510, "text": "For the next subsequent calls, this item should be taken from redis cache. So reread the same thing and let’s check the logs." }, { "code": null, "e": 12685, "s": 12636, "text": "This call should take the item from redis cache." }, { "code": null, "e": 12803, "s": 12685, "text": "On the above log statements, we can say that the data were coming from redis cache (As it is a simple GET operation)." }, { "code": null, "e": 12826, "s": 12803, "text": "Spring Cache Reference" }, { "code": null, "e": 12849, "s": 12826, "text": "Spring Boot Redis Data" }, { "code": null, "e": 12866, "s": 12849, "text": "Happy Learning 🙂" }, { "code": null, "e": 13508, "s": 12866, "text": "\nSpring Boot Kafka Producer Example\nSpring Boot Kafka Consume JSON Messages Example\nHow to set Spring Boot SetTimeZone\nSending Spring Boot Kafka JSON Message to Kafka Topic\nSpring Boot RabbitMQ Message Publishing Example\nHow To Change Spring Boot Context Path\nSpring Boot DataRest Example RepositoryRestResource\nSetup/Install Redis Server on Windows 10\nSpring Boot Hazelcast Cache Example\nSpring Boot Redis Data Example CRUD Operations\nMicroServices Spring Boot Eureka Server Example\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot EhCache Example\nSpring Boot MongoDB + Spring Data Example\nSpring Boot MVC Example Tutorials\n" }, { "code": null, "e": 13543, "s": 13508, "text": "Spring Boot Kafka Producer Example" }, { "code": null, "e": 13591, "s": 13543, "text": "Spring Boot Kafka Consume JSON Messages Example" }, { "code": null, "e": 13626, "s": 13591, "text": "How to set Spring Boot SetTimeZone" }, { "code": null, "e": 13680, "s": 13626, "text": "Sending Spring Boot Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 13728, "s": 13680, "text": "Spring Boot RabbitMQ Message Publishing Example" }, { "code": null, "e": 13767, "s": 13728, "text": "How To Change Spring Boot Context Path" }, { "code": null, "e": 13819, "s": 13767, "text": "Spring Boot DataRest Example RepositoryRestResource" }, { "code": null, "e": 13860, "s": 13819, "text": "Setup/Install Redis Server on Windows 10" }, { "code": null, "e": 13896, "s": 13860, "text": "Spring Boot Hazelcast Cache Example" }, { "code": null, "e": 13943, "s": 13896, "text": "Spring Boot Redis Data Example CRUD Operations" }, { "code": null, "e": 13991, "s": 13943, "text": "MicroServices Spring Boot Eureka Server Example" }, { "code": null, "e": 14044, "s": 13991, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 14072, "s": 14044, "text": "Spring Boot EhCache Example" }, { "code": null, "e": 14114, "s": 14072, "text": "Spring Boot MongoDB + Spring Data Example" }, { "code": null, "e": 14148, "s": 14114, "text": "Spring Boot MVC Example Tutorials" }, { "code": null, "e": 14460, "s": 14148, "text": "\n\n\n\n\n\nSoleil\nSeptember 13, 2019 at 1:54 pm - Reply \n\nHi, could you give a tutorial or the CacheManager java config for cache a list to redis? Thanks\n\n\n\n\n\n\n\n\n\nFernando\nOctober 17, 2019 at 8:56 am - Reply \n\nHi, I’m testing the demo, but the getItem does not work. It seems like the ItemRepo was not injected.\n\n\n\n\n" }, { "code": null, "e": 14612, "s": 14460, "text": "\n\n\n\n\nSoleil\nSeptember 13, 2019 at 1:54 pm - Reply \n\nHi, could you give a tutorial or the CacheManager java config for cache a list to redis? Thanks\n\n\n\n" }, { "code": null, "e": 14708, "s": 14612, "text": "Hi, could you give a tutorial or the CacheManager java config for cache a list to redis? Thanks" }, { "code": null, "e": 14866, "s": 14708, "text": "\n\n\n\n\nFernando\nOctober 17, 2019 at 8:56 am - Reply \n\nHi, I’m testing the demo, but the getItem does not work. It seems like the ItemRepo was not injected.\n\n\n\n" }, { "code": null, "e": 14968, "s": 14866, "text": "Hi, I’m testing the demo, but the getItem does not work. It seems like the ItemRepo was not injected." }, { "code": null, "e": 14974, "s": 14972, "text": "Δ" }, { "code": null, "e": 15001, "s": 14974, "text": " Spring Boot – Hello World" }, { "code": null, "e": 15028, "s": 15001, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 15062, "s": 15028, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 15103, "s": 15062, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 15148, "s": 15103, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 15186, "s": 15148, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 15220, "s": 15186, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 15251, "s": 15220, "text": " Spring Boot – Properties File" }, { "code": null, "e": 15285, "s": 15251, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 15318, "s": 15285, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 15351, "s": 15318, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 15391, "s": 15351, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 15416, "s": 15391, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 15447, "s": 15416, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 15471, "s": 15447, "text": " Spring Boot – Actuator" }, { "code": null, "e": 15517, "s": 15471, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 15540, "s": 15517, "text": " Spring Boot – Swagger" }, { "code": null, "e": 15567, "s": 15540, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 15613, "s": 15567, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 15653, "s": 15613, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 15682, "s": 15653, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 15716, "s": 15682, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 15746, "s": 15716, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 15782, "s": 15746, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 15815, "s": 15782, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 15848, "s": 15815, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 15892, "s": 15848, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 15926, "s": 15892, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 15958, "s": 15926, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 15986, "s": 15958, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 16017, "s": 15986, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 16058, "s": 16017, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 16092, "s": 16058, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 16117, "s": 16092, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 16151, "s": 16117, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 16187, "s": 16151, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 16233, "s": 16187, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 16284, "s": 16233, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 16326, "s": 16284, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 16357, "s": 16326, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 16380, "s": 16357, "text": " Spring Boot – EhCache" }, { "code": null, "e": 16410, "s": 16380, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 16440, "s": 16410, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 16489, "s": 16440, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 16523, "s": 16489, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 16556, "s": 16523, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 16585, "s": 16556, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 16617, "s": 16585, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 16654, "s": 16617, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 16683, "s": 16654, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 16712, "s": 16683, "text": " Spring Boot – MockMvc JUnit" } ]
D3.js - Animation
D3.js supports animation through transition. We can do animation with proper use of transition. Transitions are a limited form of Key Frame Animation with only two key frames – start and end. The starting key frame is typically the current state of the DOM, and the ending key frame is a set of attributes, styles and other properties you specify. Transitions are well suited for transitioning to a new view without a complicated code that depends on the starting view. Example − Let us consider the following code in “transition_color.html” page. <!DOCTYPE html> <html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <h3>Simple transitions</h3> <script> d3.select("body").style("background-color", "lightblue") // make the background-color lightblue.transition() .style("background-color", "gray"); // make the background-color gray </script> </body> </html> Here, the Background color of the document changed from white to light gray and then to gray. The duration() method allows property changes to occur smoothly over a specified duration rather than instantaneously. Let us make the transition which takes 5 seconds using the following code. <!DOCTYPE html> <html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <h3>Simple transitions</h3> <script> d3.selectAll("h3").transition().style("color","green").duration(5000); </script> </body> </html> Here, the transitions occurred smoothly and evenly. We can also assign RGB color code value directly using the following method. d3.selectAll("h3").transition().style("color","rgb(0,150,120)").duration(5000); Now, each color number slowly, smoothly and evenly goes from 0 to 150. To get the accurate blending of in-between frames from the start frame value to the end frame value, D3.js uses an internal interpolate method. The syntax is given below − d3.interpolate(a, b) D3 also supports the following interpolation types − interpolateNumber − support numerical values. interpolateNumber − support numerical values. interpolateRgb − support colors. interpolateRgb − support colors. interpolateString − support string. interpolateString − support string. D3.js takes care of using the proper interpolate method and in advanced cases, we can use the interpolate methods directly to get our desired result. We can even create a new interpolate method, if needed. The delay() method allows a transition to take place after a certain period of time. Consider the following code in “transition_delay.html”. <!DOCTYPE html> <html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <h3> Simple transitions </h3> <script> d3.selectAll("h3").transition() .style("font-size","28px").delay(2000).duration(2000); </script> </body> </html> Transition has a four-phased lifecycle − The transition is scheduled. The transition starts. The transition runs. The transition ends. Let us go through each of these one by one in detail. A transition is scheduled when it is created. When we call selection.transition, we are scheduling a transition. This is also when we call attr(), style() and other transition methods to define the ending key frame. A transition starts based on its delay, which was specified when the transition was scheduled. If no delay was specified, then the transition starts as soon as possible, which is typically after a few milliseconds. If the transition has a delay, then the starting value should be set only when the transition starts. We can do this by listening to the start event − d3.select("body") .transition() .delay(200) .each("start", function() { d3.select(this).style("color", "green"); }) .style("color", "red"); When the transition runs, it repeatedly invoked with values of transition ranging from 0 to 1. In addition to delay and duration, transitions have easing to control timing. Easing distorts time, such as for slow-in and slow-out. Some easing functions may temporarily give values of t greater than 1 or less than 0. The transition ending time is always exactly 1, so that the ending value is set exactly when the transition ends. A transition ends based on the sum of its delay and duration. When a transition ends, the end event is dispatched. Print Add Notes Bookmark this page
[ { "code": null, "e": 2600, "s": 2130, "text": "D3.js supports animation through transition. We can do animation with proper use of transition. Transitions are a limited form of Key Frame Animation with only two key frames – start and end. The starting key frame is typically the current state of the DOM, and the ending key frame is a set of attributes, styles and other properties you specify. Transitions are well suited for transitioning to a new view without a complicated code that depends on the starting view." }, { "code": null, "e": 2678, "s": 2600, "text": "Example − Let us consider the following code in “transition_color.html” page." }, { "code": null, "e": 3120, "s": 2678, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3>Simple transitions</h3>\n <script>\n d3.select(\"body\").style(\"background-color\", \"lightblue\") \n // make the background-color lightblue.transition()\n .style(\"background-color\", \"gray\");\n // make the background-color gray\n </script>\n </body>\n</html>" }, { "code": null, "e": 3214, "s": 3120, "text": "Here, the Background color of the document changed from white to light gray and then to gray." }, { "code": null, "e": 3408, "s": 3214, "text": "The duration() method allows property changes to occur smoothly over a specified duration rather than instantaneously. Let us make the transition which takes 5 seconds using the following code." }, { "code": null, "e": 3714, "s": 3408, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3>Simple transitions</h3>\n <script>\n d3.selectAll(\"h3\").transition().style(\"color\",\"green\").duration(5000);\n </script>\n </body>\n</html>" }, { "code": null, "e": 3843, "s": 3714, "text": "Here, the transitions occurred smoothly and evenly. We can also assign RGB color code value directly using the following method." }, { "code": null, "e": 3923, "s": 3843, "text": "d3.selectAll(\"h3\").transition().style(\"color\",\"rgb(0,150,120)\").duration(5000);" }, { "code": null, "e": 4166, "s": 3923, "text": "Now, each color number slowly, smoothly and evenly goes from 0 to 150. To get the accurate blending of in-between frames from the start frame value to the end frame value, D3.js uses an internal interpolate method. The syntax is given below −" }, { "code": null, "e": 4187, "s": 4166, "text": "d3.interpolate(a, b)" }, { "code": null, "e": 4240, "s": 4187, "text": "D3 also supports the following interpolation types −" }, { "code": null, "e": 4286, "s": 4240, "text": "interpolateNumber − support numerical values." }, { "code": null, "e": 4332, "s": 4286, "text": "interpolateNumber − support numerical values." }, { "code": null, "e": 4365, "s": 4332, "text": "interpolateRgb − support colors." }, { "code": null, "e": 4398, "s": 4365, "text": "interpolateRgb − support colors." }, { "code": null, "e": 4434, "s": 4398, "text": "interpolateString − support string." }, { "code": null, "e": 4470, "s": 4434, "text": "interpolateString − support string." }, { "code": null, "e": 4676, "s": 4470, "text": "D3.js takes care of using the proper interpolate method and in advanced cases, we can use the interpolate methods directly to get our desired result. We can even create a new interpolate method, if needed." }, { "code": null, "e": 4817, "s": 4676, "text": "The delay() method allows a transition to take place after a certain period of time. Consider the following code in “transition_delay.html”." }, { "code": null, "e": 5153, "s": 4817, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3> Simple transitions </h3>\n <script>\n d3.selectAll(\"h3\").transition()\n .style(\"font-size\",\"28px\").delay(2000).duration(2000);\n </script>\n </body>\n</html>" }, { "code": null, "e": 5194, "s": 5153, "text": "Transition has a four-phased lifecycle −" }, { "code": null, "e": 5223, "s": 5194, "text": "The transition is scheduled." }, { "code": null, "e": 5246, "s": 5223, "text": "The transition starts." }, { "code": null, "e": 5267, "s": 5246, "text": "The transition runs." }, { "code": null, "e": 5288, "s": 5267, "text": "The transition ends." }, { "code": null, "e": 5342, "s": 5288, "text": "Let us go through each of these one by one in detail." }, { "code": null, "e": 5558, "s": 5342, "text": "A transition is scheduled when it is created. When we call selection.transition, we are scheduling a transition. This is also when we call attr(), style() and other transition methods to define the ending key frame." }, { "code": null, "e": 5773, "s": 5558, "text": "A transition starts based on its delay, which was specified when the transition was scheduled. If no delay was specified, then the transition starts as soon as possible, which is typically after a few milliseconds." }, { "code": null, "e": 5924, "s": 5773, "text": "If the transition has a delay, then the starting value should be set only when the transition starts. We can do this by listening to the start event −" }, { "code": null, "e": 6076, "s": 5924, "text": "d3.select(\"body\")\n .transition()\n .delay(200)\n .each(\"start\", function() { d3.select(this).style(\"color\", \"green\"); })\n .style(\"color\", \"red\");" }, { "code": null, "e": 6391, "s": 6076, "text": "When the transition runs, it repeatedly invoked with values of transition ranging from 0 to 1. In addition to delay and duration, transitions have easing to control timing. Easing distorts time, such as for slow-in and slow-out. Some easing functions may temporarily give values of t greater than 1 or less than 0." }, { "code": null, "e": 6620, "s": 6391, "text": "The transition ending time is always exactly 1, so that the ending value is set exactly when the transition ends. A transition ends based on the sum of its delay and duration. When a transition ends, the end event is dispatched." }, { "code": null, "e": 6627, "s": 6620, "text": " Print" }, { "code": null, "e": 6638, "s": 6627, "text": " Add Notes" } ]
How to make border around all unordered list items that are children of a specified class using jQuery ? - GeeksforGeeks
22 Apr, 2021 In this article, we will see how to set a border around all list items that are children of a specified class of an unordered list using jQuery. This task can be done by using the children selector() method. children selector(“parent > child”) – As you notice from the name itself that it takes two arguments and then perform the task. It selects all children element specified by a child of elements specified by the “parent”. Here the parent is any selector and the child is a selector to filter the child elements. Example: Places a border around all list items that are children of <ul class=”GFG”>. HTML <!doctype html><html lang="en"> <head> <script src="https://code.jquery.com/jquery-3.5.0.js"> </script></head> <body> <ul class="GFG"> <h1 style="color: green; text-align: center;"> GeeksforGeeks </h1> <li>DataBase <ol> <li>oracle</li> <li>MySql</li> <li>DB2</li> </ol> </li> <li>Computer Networks <ol> <li>LAN</li> <li>MAN</li> <li>WAN</li> </ol> </li> <li>Operating system <ol> <li>Linux</li> <li>Mac</li> <li>Windows</li> </ol> </li> </ul> <script> $("ul.GFG > li") .css("border", "2px dashed green"); </script> </body> </html> Output – HTML-Tags jQuery-Methods jQuery-Questions Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method How to get the value in an input text box using jQuery ? Difference Between JavaScript and jQuery QR Code Generator using HTML, CSS and jQuery Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux 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 ?
[ { "code": null, "e": 25755, "s": 25727, "text": "\n22 Apr, 2021" }, { "code": null, "e": 25963, "s": 25755, "text": "In this article, we will see how to set a border around all list items that are children of a specified class of an unordered list using jQuery. This task can be done by using the children selector() method." }, { "code": null, "e": 26273, "s": 25963, "text": "children selector(“parent > child”) – As you notice from the name itself that it takes two arguments and then perform the task. It selects all children element specified by a child of elements specified by the “parent”. Here the parent is any selector and the child is a selector to filter the child elements." }, { "code": null, "e": 26359, "s": 26273, "text": "Example: Places a border around all list items that are children of <ul class=”GFG”>." }, { "code": null, "e": 26364, "s": 26359, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <script src=\"https://code.jquery.com/jquery-3.5.0.js\"> </script></head> <body> <ul class=\"GFG\"> <h1 style=\"color: green; text-align: center;\"> GeeksforGeeks </h1> <li>DataBase <ol> <li>oracle</li> <li>MySql</li> <li>DB2</li> </ol> </li> <li>Computer Networks <ol> <li>LAN</li> <li>MAN</li> <li>WAN</li> </ol> </li> <li>Operating system <ol> <li>Linux</li> <li>Mac</li> <li>Windows</li> </ol> </li> </ul> <script> $(\"ul.GFG > li\") .css(\"border\", \"2px dashed green\"); </script> </body> </html>", "e": 27223, "s": 26364, "text": null }, { "code": null, "e": 27233, "s": 27223, "text": "Output – " }, { "code": null, "e": 27243, "s": 27233, "text": "HTML-Tags" }, { "code": null, "e": 27258, "s": 27243, "text": "jQuery-Methods" }, { "code": null, "e": 27275, "s": 27258, "text": "jQuery-Questions" }, { "code": null, "e": 27282, "s": 27275, "text": "Picked" }, { "code": null, "e": 27289, "s": 27282, "text": "JQuery" }, { "code": null, "e": 27306, "s": 27289, "text": "Web Technologies" }, { "code": null, "e": 27404, "s": 27306, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27413, "s": 27404, "text": "Comments" }, { "code": null, "e": 27426, "s": 27413, "text": "Old Comments" }, { "code": null, "e": 27499, "s": 27426, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 27522, "s": 27499, "text": "jQuery | ajax() Method" }, { "code": null, "e": 27579, "s": 27522, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 27620, "s": 27579, "text": "Difference Between JavaScript and jQuery" }, { "code": null, "e": 27665, "s": 27620, "text": "QR Code Generator using HTML, CSS and jQuery" }, { "code": null, "e": 27707, "s": 27665, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27740, "s": 27707, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27790, "s": 27740, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27852, "s": 27790, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
C++ Null Pointers
It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant with a value of zero defined in several standard libraries, including iostream. Consider the following program − #include <iostream> using namespace std; int main () { int *ptr = NULL; cout << "The value of ptr is " << ptr ; return 0; } When the above code is compiled and executed, it produces the following result − The value of ptr is 0 On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing. To check for a null pointer you can use an if statement as follows − if(ptr) // succeeds if p is not null if(!ptr) // succeeds if p is null Thus, if all unused pointers are given the null value and you avoid the use of a null pointer, you can avoid the accidental misuse of an uninitialized pointer. Many times, uninitialized variables hold some junk values and it becomes difficult to debug the program. 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2558, "s": 2318, "text": "It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer." }, { "code": null, "e": 2702, "s": 2558, "text": "The NULL pointer is a constant with a value of zero defined in several standard libraries, including iostream. Consider the following program −" }, { "code": null, "e": 2839, "s": 2702, "text": "#include <iostream>\n\nusing namespace std;\nint main () {\n int *ptr = NULL;\n cout << \"The value of ptr is \" << ptr ;\n \n return 0;\n}" }, { "code": null, "e": 2920, "s": 2839, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 2943, "s": 2920, "text": "The value of ptr is 0\n" }, { "code": null, "e": 3333, "s": 2943, "text": "On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing." }, { "code": null, "e": 3402, "s": 3333, "text": "To check for a null pointer you can use an if statement as follows −" }, { "code": null, "e": 3481, "s": 3402, "text": "if(ptr) // succeeds if p is not null\nif(!ptr) // succeeds if p is null\n" }, { "code": null, "e": 3746, "s": 3481, "text": "Thus, if all unused pointers are given the null value and you avoid the use of a null pointer, you can avoid the accidental misuse of an uninitialized pointer. Many times, uninitialized variables hold some junk values and it becomes difficult to debug the program." }, { "code": null, "e": 3783, "s": 3746, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 3802, "s": 3783, "text": " Arnab Chakraborty" }, { "code": null, "e": 3834, "s": 3802, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 3857, "s": 3834, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 3893, "s": 3857, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 3910, "s": 3893, "text": " Frahaan Hussain" }, { "code": null, "e": 3945, "s": 3910, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3962, "s": 3945, "text": " Frahaan Hussain" }, { "code": null, "e": 3997, "s": 3962, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4014, "s": 3997, "text": " Frahaan Hussain" }, { "code": null, "e": 4049, "s": 4014, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4066, "s": 4049, "text": " Frahaan Hussain" }, { "code": null, "e": 4073, "s": 4066, "text": " Print" }, { "code": null, "e": 4084, "s": 4073, "text": " Add Notes" } ]
Angular CLI - ng xi18n Command
This chapter explains the syntax, arguments and options of ng xi18n command along with an example. The syntax for ng xi18n command is as follows − ng xi18n <project> [options] ng i18n-extract <project> [options] ng xi18n command extracts i18n messages from source code. The argument for ng xi18n command is as follows − Options are optional parameters. A named build target, as specified in the "configurations" section of angular.json. Each named target is accompanied by a configuration of option defaults for that target. Setting this explicitly overrides the "--prod" flag. Aliases: -c Create source control commits for updates and migrations. Default: false Aliases: -C Output format for the generated file. Default: xlf Shows a help message for this command in the console. Default: false Log progress to the console. Default: true First move to an angular project updated using ng build command. The chapter is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm. Update the app.component.html as follows − app.component.spec.ts <div class="content" role="main"> <span i18n>app is running!</span> </div> <app-goals></app-goals> <router-outlet></router-outlet> Now run the xi18n command. An example for ng xi18n command is given below − \>Node\>TutorialsPoint> ng xi18n Add localization support. \>Node\>TutorialsPoint> ng add @angular/localize Installing packages for tooling via npm. Installed packages for tooling via npm. UPDATE src/polyfills.ts (3064 bytes) Now ng will create a messages.xlf file in root folder which is a industry standard translation file. messages.xlf <?xml version="1.0" encoding="UTF-8" ?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en-US" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="6226cbeebaffaec0342459915ef7d9b0e9e92977" datatype="html"> <source>app is running!</source> <context-group purpose="location"> <context context-type="sourcefile">src/app/app.component.html</context> <context context-type="linenumber">2</context> </context-group> </trans-unit> </body> </file> </xliff> 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2174, "s": 2075, "text": "This chapter explains the syntax, arguments and options of ng xi18n command along with an example." }, { "code": null, "e": 2222, "s": 2174, "text": "The syntax for ng xi18n command is as follows −" }, { "code": null, "e": 2288, "s": 2222, "text": "ng xi18n <project> [options]\nng i18n-extract <project> [options]\n" }, { "code": null, "e": 2347, "s": 2288, "text": "ng xi18n command extracts i18n messages from source code. " }, { "code": null, "e": 2397, "s": 2347, "text": "The argument for ng xi18n command is as follows −" }, { "code": null, "e": 2430, "s": 2397, "text": "Options are optional parameters." }, { "code": null, "e": 2655, "s": 2430, "text": "A named build target, as specified in the \"configurations\" section of angular.json. Each named target is accompanied by a configuration of option defaults for that target. Setting this explicitly overrides the \"--prod\" flag." }, { "code": null, "e": 2667, "s": 2655, "text": "Aliases: -c" }, { "code": null, "e": 2725, "s": 2667, "text": "Create source control commits for updates and migrations." }, { "code": null, "e": 2740, "s": 2725, "text": "Default: false" }, { "code": null, "e": 2752, "s": 2740, "text": "Aliases: -C" }, { "code": null, "e": 2790, "s": 2752, "text": "Output format for the generated file." }, { "code": null, "e": 2803, "s": 2790, "text": "Default: xlf" }, { "code": null, "e": 2857, "s": 2803, "text": "Shows a help message for this command in the console." }, { "code": null, "e": 2872, "s": 2857, "text": "Default: false" }, { "code": null, "e": 2901, "s": 2872, "text": "Log progress to the console." }, { "code": null, "e": 2915, "s": 2901, "text": "Default: true" }, { "code": null, "e": 3077, "s": 2915, "text": "First move to an angular project updated using ng build command. The chapter is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm." }, { "code": null, "e": 3120, "s": 3077, "text": "Update the app.component.html as follows −" }, { "code": null, "e": 3142, "s": 3120, "text": "app.component.spec.ts" }, { "code": null, "e": 3276, "s": 3142, "text": "<div class=\"content\" role=\"main\">\n <span i18n>app is running!</span>\n</div>\n<app-goals></app-goals>\n<router-outlet></router-outlet>" }, { "code": null, "e": 3303, "s": 3276, "text": "Now run the xi18n command." }, { "code": null, "e": 3352, "s": 3303, "text": "An example for ng xi18n command is given below −" }, { "code": null, "e": 3386, "s": 3352, "text": "\\>Node\\>TutorialsPoint> ng xi18n\n" }, { "code": null, "e": 3412, "s": 3386, "text": "Add localization support." }, { "code": null, "e": 3580, "s": 3412, "text": "\\>Node\\>TutorialsPoint> ng add @angular/localize\nInstalling packages for tooling via npm.\nInstalled packages for tooling via npm.\nUPDATE src/polyfills.ts (3064 bytes)\n" }, { "code": null, "e": 3681, "s": 3580, "text": "Now ng will create a messages.xlf file in root folder which is a industry standard translation file." }, { "code": null, "e": 3694, "s": 3681, "text": "messages.xlf" }, { "code": null, "e": 4305, "s": 3694, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\">\n <file source-language=\"en-US\" datatype=\"plaintext\" original=\"ng2.template\">\n <body>\n <trans-unit id=\"6226cbeebaffaec0342459915ef7d9b0e9e92977\" datatype=\"html\">\n <source>app is running!</source>\n <context-group purpose=\"location\">\n <context context-type=\"sourcefile\">src/app/app.component.html</context>\n <context context-type=\"linenumber\">2</context>\n </context-group>\n </trans-unit>\n </body>\n </file>\n</xliff>" }, { "code": null, "e": 4340, "s": 4305, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4354, "s": 4340, "text": " Anadi Sharma" }, { "code": null, "e": 4389, "s": 4354, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4403, "s": 4389, "text": " Anadi Sharma" }, { "code": null, "e": 4438, "s": 4403, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4458, "s": 4438, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4493, "s": 4458, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4510, "s": 4493, "text": " Frahaan Hussain" }, { "code": null, "e": 4543, "s": 4510, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4555, "s": 4543, "text": " Senol Atac" }, { "code": null, "e": 4590, "s": 4555, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4602, "s": 4590, "text": " Senol Atac" }, { "code": null, "e": 4609, "s": 4602, "text": " Print" }, { "code": null, "e": 4620, "s": 4609, "text": " Add Notes" } ]
Linear Time vs. Logarithmic Time — Big O Notation | by Jhantelle Belleza | Towards Data Science
Hello there! I’m finally back after more than 2 months of not writing/touching code. I got caught up with the all the wedding preparation and planning. It’s hard pulling off an overseas wedding without a wedding planner. But it was all worth it since our wedding was one for the books! Wedding fever’s over and now it’s time to recollect my thoughts and get back to coding (still in Swift). It was hard to decide what to review first before I start job hunting. I figured I should start with the classics — algorithms and data structures, the core of programming. In any system, as data grows, performance shouldn’t be an issue if the correct algorithm has been used. Today, I’m writing a quick blog about 2 types of Big O Notations, Linear and Logarithmic algorithms. A little background on Big O Notation first. Asymptotic analysis is based on mathematical computations that basically measures the efficiency of an algorithm as input dataset grows (thanks Wikipedia!). There are other types of asymptotic analysis depending on where it is applied, but in Computer Science, it’s commonly formatted as Big O Notation. To easily understand Big O Notation, we’ll compare these two algorithms: Linear — O(n) and Logarithmic — O(log n). As an example, we’ll try to look for a number in a sorted array. let numberList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In Linear or “brute force” technique, performance is dependent on the input size. For our example, we’ll read through each item in the array and search for the number we need. Easy peasy! //Logarithmic Time - O(n)func linear(key: Int) {for (index, number) in numberList.enumerated() { if number == key { print("Value found in index \(index)") break } }} Of course that’s going to work for our small dataset, but it’s not very efficient once you have thousands, even millions of data. Using binary search — which is a form of logarithmic algorithm, finds the median in the array and compares it to the target value. The algorithm will traverse either upwards or downwards depending on the target value being higher than, lower than or equal to the median. func binarySearch(key: Int, iminIndex: Int, imaxIndex: Int) {let midIndex = round(Double(iminIndex + imaxIndex)/2)let midNumber = numberList[Int(midIndex)]var result = ""//using recursion, we can go up or down the array and reduce the rangeif midNumber > key { //target is less than the median so traverse downwards binarySearch(key: key, iminIndex: iminIndex, imaxIndex: Int(midIndex) - 1) } else if midNumber < key { //target is greater than the median so traverse upwards binarySearch(key: key, iminIndex: Int(midIndex) + 1, imaxIndex: imaxIndex) } else if midNumber == key { //Found it! print("Found it at index \(midIndex)")} else { print("Value \(key) not found")}} The bulk of this algorithm is at the beginning, but it slowly flattens out as we discard the irrelevant range from the array and continue halving until we find the target value. Through the graph below, we can easily compare how most algorithms have similar performance with smaller datasets but continuously differs as data grows. As you can see there are other types of Big O Notation which I’ll discuss in the next days. Ciao for now! References: Swift Algorithms and Data Structures by Wayne Bishop Beginner’s Guide to Big O Notation
[ { "code": null, "e": 563, "s": 172, "text": "Hello there! I’m finally back after more than 2 months of not writing/touching code. I got caught up with the all the wedding preparation and planning. It’s hard pulling off an overseas wedding without a wedding planner. But it was all worth it since our wedding was one for the books! Wedding fever’s over and now it’s time to recollect my thoughts and get back to coding (still in Swift)." }, { "code": null, "e": 840, "s": 563, "text": "It was hard to decide what to review first before I start job hunting. I figured I should start with the classics — algorithms and data structures, the core of programming. In any system, as data grows, performance shouldn’t be an issue if the correct algorithm has been used." }, { "code": null, "e": 941, "s": 840, "text": "Today, I’m writing a quick blog about 2 types of Big O Notations, Linear and Logarithmic algorithms." }, { "code": null, "e": 986, "s": 941, "text": "A little background on Big O Notation first." }, { "code": null, "e": 1290, "s": 986, "text": "Asymptotic analysis is based on mathematical computations that basically measures the efficiency of an algorithm as input dataset grows (thanks Wikipedia!). There are other types of asymptotic analysis depending on where it is applied, but in Computer Science, it’s commonly formatted as Big O Notation." }, { "code": null, "e": 1405, "s": 1290, "text": "To easily understand Big O Notation, we’ll compare these two algorithms: Linear — O(n) and Logarithmic — O(log n)." }, { "code": null, "e": 1470, "s": 1405, "text": "As an example, we’ll try to look for a number in a sorted array." }, { "code": null, "e": 1519, "s": 1470, "text": "let numberList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" }, { "code": null, "e": 1707, "s": 1519, "text": "In Linear or “brute force” technique, performance is dependent on the input size. For our example, we’ll read through each item in the array and search for the number we need. Easy peasy!" }, { "code": null, "e": 1893, "s": 1707, "text": "//Logarithmic Time - O(n)func linear(key: Int) {for (index, number) in numberList.enumerated() { if number == key { print(\"Value found in index \\(index)\") break } }}" }, { "code": null, "e": 2023, "s": 1893, "text": "Of course that’s going to work for our small dataset, but it’s not very efficient once you have thousands, even millions of data." }, { "code": null, "e": 2294, "s": 2023, "text": "Using binary search — which is a form of logarithmic algorithm, finds the median in the array and compares it to the target value. The algorithm will traverse either upwards or downwards depending on the target value being higher than, lower than or equal to the median." }, { "code": null, "e": 2977, "s": 2294, "text": "func binarySearch(key: Int, iminIndex: Int, imaxIndex: Int) {let midIndex = round(Double(iminIndex + imaxIndex)/2)let midNumber = numberList[Int(midIndex)]var result = \"\"//using recursion, we can go up or down the array and reduce the rangeif midNumber > key { //target is less than the median so traverse downwards binarySearch(key: key, iminIndex: iminIndex, imaxIndex: Int(midIndex) - 1) } else if midNumber < key { //target is greater than the median so traverse upwards binarySearch(key: key, iminIndex: Int(midIndex) + 1, imaxIndex: imaxIndex) } else if midNumber == key { //Found it! print(\"Found it at index \\(midIndex)\")} else { print(\"Value \\(key) not found\")}}" }, { "code": null, "e": 3155, "s": 2977, "text": "The bulk of this algorithm is at the beginning, but it slowly flattens out as we discard the irrelevant range from the array and continue halving until we find the target value." }, { "code": null, "e": 3309, "s": 3155, "text": "Through the graph below, we can easily compare how most algorithms have similar performance with smaller datasets but continuously differs as data grows." }, { "code": null, "e": 3415, "s": 3309, "text": "As you can see there are other types of Big O Notation which I’ll discuss in the next days. Ciao for now!" }, { "code": null, "e": 3427, "s": 3415, "text": "References:" }, { "code": null, "e": 3480, "s": 3427, "text": "Swift Algorithms and Data Structures by Wayne Bishop" } ]
Find and display duplicate values only once from a column in MySQL
Let us first create a table − mysql> create table DemoTable -> ( -> value int -> ); Query OK, 0 rows affected (0.82 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.07 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-------+ | value | +-------+ | 10 | | 100 | | 20 | | 10 | | 30 | | 40 | | 20 | +-------+ 7 rows in set (0.00 sec) Following is the query to find the duplicate values and display them once − mysql> select *from DemoTable group by value having count(*) > 1; This will produce the following output − +-------+ | value | +-------+ | 10 | | 20 | +-------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1183, "s": 1092, "text": "mysql> create table DemoTable\n-> (\n-> value int\n-> );\nQuery OK, 0 rows affected (0.82 sec)" }, { "code": null, "e": 1239, "s": 1183, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1785, "s": 1239, "text": "mysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DemoTable values(100);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DemoTable values(20);\nQuery OK, 1 row affected (0.28 sec)\n\nmysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.34 sec)\n\nmysql> insert into DemoTable values(30);\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into DemoTable values(40);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DemoTable values(20);\nQuery OK, 1 row affected (0.07 sec)" }, { "code": null, "e": 1845, "s": 1785, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1876, "s": 1845, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1917, "s": 1876, "text": "This will produce the following output −" }, { "code": null, "e": 2053, "s": 1917, "text": "+-------+\n| value |\n+-------+\n| 10 |\n| 100 |\n| 20 |\n| 10 |\n| 30 | \n| 40 |\n| 20 |\n+-------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 2129, "s": 2053, "text": "Following is the query to find the duplicate values and display them once −" }, { "code": null, "e": 2195, "s": 2129, "text": "mysql> select *from DemoTable group by value having count(*) > 1;" }, { "code": null, "e": 2236, "s": 2195, "text": "This will produce the following output −" }, { "code": null, "e": 2321, "s": 2236, "text": "+-------+\n| value |\n+-------+\n| 10 |\n| 20 |\n+-------+\n2 rows in set (0.00 sec)" } ]
Wand arc() function in Python - GeeksforGeeks
16 Oct, 2021 arc() is a function present in wand.drawing module. arc() function draws an arc in the image. You’ll need to define three pairs of (x, y) coordinates. First & second pair of coordinates will be the minimum bounding rectangle, and the last pair define the starting & ending degree. Syntax : wand.drawing.arc(start, end, degree) Parameters : Example #1: Python3 # Import required objects from wand modulesfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color # generate object for wand.drawingwith Drawing() as draw: # set stroke color draw.stroke_color = Color('black') # set width for stroke draw.stroke_width = 1 # fill white color in arc draw.fill_color = Color('white') draw.arc(( 50, 50), # Stating point ( 150, 150), # Ending point (135, -45)) # From bottom left around to top right with Image(width = 100, height = 100, background = Color('green')) as img: # draw shape on image using draw() function draw.draw(img) img.save(filename ='arc.png') Output: Example #2:Source Image: Python3 # Import required objects from wand modulesfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color # generate object for wand.drawingwith Drawing() as draw:' # set stroke color draw.stroke_color = Color('black') # set width for stroke draw.stroke_width = 1 # fill white color in arc draw.fill_color = Color('white') draw.arc(( 50, 50), # Starting point ( 150, 150), # Ending point (135, -45)) # From bottom left around to top right with Image(filename ="gog.png") as img: # draw shape on image using draw() function draw.draw(img) img.save(filename ='arc.png') Output: akshaysingh98088 Python-wand Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24214, "s": 24186, "text": "\n16 Oct, 2021" }, { "code": null, "e": 24496, "s": 24214, "text": "arc() is a function present in wand.drawing module. arc() function draws an arc in the image. You’ll need to define three pairs of (x, y) coordinates. First & second pair of coordinates will be the minimum bounding rectangle, and the last pair define the starting & ending degree. " }, { "code": null, "e": 24507, "s": 24496, "text": "Syntax : " }, { "code": null, "e": 24544, "s": 24507, "text": "wand.drawing.arc(start, end, degree)" }, { "code": null, "e": 24558, "s": 24544, "text": "Parameters : " }, { "code": null, "e": 24574, "s": 24560, "text": "Example #1: " }, { "code": null, "e": 24582, "s": 24574, "text": "Python3" }, { "code": "# Import required objects from wand modulesfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color # generate object for wand.drawingwith Drawing() as draw: # set stroke color draw.stroke_color = Color('black') # set width for stroke draw.stroke_width = 1 # fill white color in arc draw.fill_color = Color('white') draw.arc(( 50, 50), # Stating point ( 150, 150), # Ending point (135, -45)) # From bottom left around to top right with Image(width = 100, height = 100, background = Color('green')) as img: # draw shape on image using draw() function draw.draw(img) img.save(filename ='arc.png')", "e": 25309, "s": 24582, "text": null }, { "code": null, "e": 25319, "s": 25309, "text": "Output: " }, { "code": null, "e": 25346, "s": 25319, "text": "Example #2:Source Image: " }, { "code": null, "e": 25356, "s": 25348, "text": "Python3" }, { "code": "# Import required objects from wand modulesfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color # generate object for wand.drawingwith Drawing() as draw:' # set stroke color draw.stroke_color = Color('black') # set width for stroke draw.stroke_width = 1 # fill white color in arc draw.fill_color = Color('white') draw.arc(( 50, 50), # Starting point ( 150, 150), # Ending point (135, -45)) # From bottom left around to top right with Image(filename =\"gog.png\") as img: # draw shape on image using draw() function draw.draw(img) img.save(filename ='arc.png')", "e": 26022, "s": 25356, "text": null }, { "code": null, "e": 26032, "s": 26022, "text": "Output: " }, { "code": null, "e": 26051, "s": 26034, "text": "akshaysingh98088" }, { "code": null, "e": 26063, "s": 26051, "text": "Python-wand" }, { "code": null, "e": 26070, "s": 26063, "text": "Python" }, { "code": null, "e": 26168, "s": 26070, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26177, "s": 26168, "text": "Comments" }, { "code": null, "e": 26190, "s": 26177, "text": "Old Comments" }, { "code": null, "e": 26208, "s": 26190, "text": "Python Dictionary" }, { "code": null, "e": 26240, "s": 26208, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26262, "s": 26240, "text": "Enumerate() in Python" }, { "code": null, "e": 26292, "s": 26262, "text": "Iterate over a list in Python" }, { "code": null, "e": 26334, "s": 26292, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26377, "s": 26334, "text": "Python program to convert a list to string" }, { "code": null, "e": 26414, "s": 26377, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26440, "s": 26414, "text": "Python String | replace()" }, { "code": null, "e": 26469, "s": 26440, "text": "*args and **kwargs in Python" } ]
How to use search functionality in custom listview in Android using kotlin?
This example demonstrates how to use search functionality in custom listview in Android using kotlin Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" tools:context=".MainActivity"> <EditText android:id="@+id/etSearch" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Search here" /> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/etSearch" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.widget.ArrayAdapter import android.widget.EditText import android.widget.ListView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var listView: ListView var months: ArrayList<String> = ArrayList() var arrayAdapter: ArrayAdapter<String>? = null lateinit var etSearch: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" listView = findViewById(R.id.listView) etSearch = findViewById(R.id.etSearch) months.add("January") months.add("February") months.add("March") months.add("April") months.add("May") months.add("June") months.add("July") months.add("August") months.add("September") months.add("October") months.add("November") months.add("December") arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, months) listView.adapter = arrayAdapter etSearch.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { arrayAdapter!!.filter.filter(s) } override fun afterTextChanged(s: Editable) {} }) } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
[ { "code": null, "e": 1163, "s": 1062, "text": "This example demonstrates how to use search functionality in custom listview in Android using kotlin" }, { "code": null, "e": 1292, "s": 1163, "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": 1357, "s": 1292, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2020, "s": 1357, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/etSearch\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Search here\" />\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_below=\"@id/etSearch\" />\n</RelativeLayout>" }, { "code": null, "e": 2075, "s": 2020, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3618, "s": 2075, "text": "import android.os.Bundle\nimport android.text.Editable\nimport android.text.TextWatcher\nimport android.widget.ArrayAdapter\nimport android.widget.EditText\nimport android.widget.ListView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var listView: ListView\n var months: ArrayList<String> = ArrayList()\n var arrayAdapter: ArrayAdapter<String>? = null\n lateinit var etSearch: EditText\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n listView = findViewById(R.id.listView)\n etSearch = findViewById(R.id.etSearch)\n months.add(\"January\")\n months.add(\"February\")\n months.add(\"March\")\n months.add(\"April\")\n months.add(\"May\")\n months.add(\"June\")\n months.add(\"July\")\n months.add(\"August\")\n months.add(\"September\")\n months.add(\"October\")\n months.add(\"November\")\n months.add(\"December\")\n arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, months)\n listView.adapter = arrayAdapter\n etSearch.addTextChangedListener(object : TextWatcher {\n override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}\n override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {\n arrayAdapter!!.filter.filter(s)\n }\n override fun afterTextChanged(s: Editable) {}\n })\n }\n}" }, { "code": null, "e": 3673, "s": 3618, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4347, "s": 3673, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4697, "s": 4347, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." } ]
Matplotlib.pyplot.axis() in Python - GeeksforGeeks
12 Apr, 2020 Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python and the advantage of being free and open-source. This function is used to set some axis properties to the graph. Syntax: matplotlib.pyplot.axis(*args, emit=True, **kwargs) Parameters:xmin, xmax, ymin, ymax:These parameters can be used toset the axis limits on the graphemit:Its a bool value used to notify observers of the axis limit change Example #1: import matplotlib.pyplot as plt x =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10] # Plotting the graphplt.plot(x, y) # Setting the x-axis to 1-10# and y-axis to 1-15plt.axis([0, 10, 1, 15]) # Showing the graph with updated axisplt.show() Output: Example #2: import matplotlib.pyplot as plt x =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10] plt.plot(x, y) # we can turn off the axis and display# only the line by passing the # optional parameter 'off' to itplt.axis('off') plt.show() Output: Python-matplotlib 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 Iterate over a list in Python Python OOPs Concepts Different ways to create Pandas Dataframe How to Install PIP on Windows ? sum() function in Python Stack in Python Reading and Writing to text files in Python
[ { "code": null, "e": 24824, "s": 24796, "text": "\n12 Apr, 2020" }, { "code": null, "e": 25130, "s": 24824, "text": "Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python and the advantage of being free and open-source." }, { "code": null, "e": 25194, "s": 25130, "text": "This function is used to set some axis properties to the graph." }, { "code": null, "e": 25253, "s": 25194, "text": "Syntax: matplotlib.pyplot.axis(*args, emit=True, **kwargs)" }, { "code": null, "e": 25422, "s": 25253, "text": "Parameters:xmin, xmax, ymin, ymax:These parameters can be used toset the axis limits on the graphemit:Its a bool value used to notify observers of the axis limit change" }, { "code": null, "e": 25434, "s": 25422, "text": "Example #1:" }, { "code": "import matplotlib.pyplot as plt x =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10] # Plotting the graphplt.plot(x, y) # Setting the x-axis to 1-10# and y-axis to 1-15plt.axis([0, 10, 1, 15]) # Showing the graph with updated axisplt.show()", "e": 25666, "s": 25434, "text": null }, { "code": null, "e": 25674, "s": 25666, "text": "Output:" }, { "code": null, "e": 25686, "s": 25674, "text": "Example #2:" }, { "code": "import matplotlib.pyplot as plt x =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10] plt.plot(x, y) # we can turn off the axis and display# only the line by passing the # optional parameter 'off' to itplt.axis('off') plt.show()", "e": 25903, "s": 25686, "text": null }, { "code": null, "e": 25911, "s": 25903, "text": "Output:" }, { "code": null, "e": 25929, "s": 25911, "text": "Python-matplotlib" }, { "code": null, "e": 25936, "s": 25929, "text": "Python" }, { "code": null, "e": 26034, "s": 25936, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26043, "s": 26034, "text": "Comments" }, { "code": null, "e": 26056, "s": 26043, "text": "Old Comments" }, { "code": null, "e": 26074, "s": 26056, "text": "Python Dictionary" }, { "code": null, "e": 26096, "s": 26074, "text": "Enumerate() in Python" }, { "code": null, "e": 26131, "s": 26096, "text": "Read a file line by line in Python" }, { "code": null, "e": 26161, "s": 26131, "text": "Iterate over a list in Python" }, { "code": null, "e": 26182, "s": 26161, "text": "Python OOPs Concepts" }, { "code": null, "e": 26224, "s": 26182, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26256, "s": 26224, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26281, "s": 26256, "text": "sum() function in Python" }, { "code": null, "e": 26297, "s": 26281, "text": "Stack in Python" } ]
Difference between C-SCAN and SSTF Disk Scheduling Algorithm - GeeksforGeeks
12 Jun, 2020 1. C-SCAN Disk Scheduling Algorithm :C-SCAN algorithm, also known as Circular Elevator algorithm is the modified version of SCAN algorithm. In this algorithm, the head pointer starts from one end of disk and moves towards the other end, serving all requests in between. After reaching the other end, the head reverse its direction and go to the starting point. It then satisfies the remaining requests, in same direction as before. Unlike SSTF, it can handle requests only in one direction. Example –Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: 98, 183, 40, 122, 10, 124, 65 Current head position of the Read/Write head is 53 and will move in Right direction . Calculate the total number of track movements of Read/Write head using C-SCAN algorithm. Total head movements, = (65-53)+(98-65)+(122-98)+(124-122)+(183-124) +(199-183)+(199-0)+(10-0)+(40-10) = 395 2. SSTF Disk Scheduling Algorithm :SSTF stands for Shortest Seek Time First, as the the name suggests it serves the request which is closest to the current position of head or pointer. In this algorithm, direction of the the head pointer matters a lot. If there occurs a tie between requests, then the head will serve the request in its ongoing direction. Unlike C-SCAN, SSTF algorithm is very efficient in total seek time. Example –Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: 98, 183, 40, 122, 10, 124, 65 Current head position of the Read/Write head is 53 and will move in Right direction. Calculate the total number of track movements of Read/Write head using SSTF algorithm. Total head movements, = (65-53)+(65-40)+(40-10) +(98-10)+(122-98)+(124-122)+(183-124) = 240 Difference between C-SCAN and SSTF Disk Scheduling Algorithm : File & Disk Management Difference Between GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Informed and Uninformed Search in AI Difference between Internal and External fragmentation Difference between HashMap and HashSet Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 24467, "s": 24439, "text": "\n12 Jun, 2020" }, { "code": null, "e": 24958, "s": 24467, "text": "1. C-SCAN Disk Scheduling Algorithm :C-SCAN algorithm, also known as Circular Elevator algorithm is the modified version of SCAN algorithm. In this algorithm, the head pointer starts from one end of disk and moves towards the other end, serving all requests in between. After reaching the other end, the head reverse its direction and go to the starting point. It then satisfies the remaining requests, in same direction as before. Unlike SSTF, it can handle requests only in one direction." }, { "code": null, "e": 25081, "s": 24958, "text": "Example –Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows:" }, { "code": null, "e": 25112, "s": 25081, "text": "98, 183, 40, 122, 10, 124, 65 " }, { "code": null, "e": 25287, "s": 25112, "text": "Current head position of the Read/Write head is 53 and will move in Right direction . Calculate the total number of track movements of Read/Write head using C-SCAN algorithm." }, { "code": null, "e": 25309, "s": 25287, "text": "Total head movements," }, { "code": null, "e": 25412, "s": 25309, "text": "= (65-53)+(98-65)+(122-98)+(124-122)+(183-124)\n +(199-183)+(199-0)+(10-0)+(40-10)\n= 395 " }, { "code": null, "e": 25836, "s": 25412, "text": "2. SSTF Disk Scheduling Algorithm :SSTF stands for Shortest Seek Time First, as the the name suggests it serves the request which is closest to the current position of head or pointer. In this algorithm, direction of the the head pointer matters a lot. If there occurs a tie between requests, then the head will serve the request in its ongoing direction. Unlike C-SCAN, SSTF algorithm is very efficient in total seek time." }, { "code": null, "e": 25959, "s": 25836, "text": "Example –Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows:" }, { "code": null, "e": 25990, "s": 25959, "text": "98, 183, 40, 122, 10, 124, 65 " }, { "code": null, "e": 26162, "s": 25990, "text": "Current head position of the Read/Write head is 53 and will move in Right direction. Calculate the total number of track movements of Read/Write head using SSTF algorithm." }, { "code": null, "e": 26184, "s": 26162, "text": "Total head movements," }, { "code": null, "e": 26266, "s": 26184, "text": "= (65-53)+(65-40)+(40-10)\n +(98-10)+(122-98)+(124-122)+(183-124)\n= 240 " }, { "code": null, "e": 26329, "s": 26266, "text": "Difference between C-SCAN and SSTF Disk Scheduling Algorithm :" }, { "code": null, "e": 26352, "s": 26329, "text": "File & Disk Management" }, { "code": null, "e": 26371, "s": 26352, "text": "Difference Between" }, { "code": null, "e": 26379, "s": 26371, "text": "GATE CS" }, { "code": null, "e": 26397, "s": 26379, "text": "Operating Systems" }, { "code": null, "e": 26415, "s": 26397, "text": "Operating Systems" }, { "code": null, "e": 26513, "s": 26415, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26522, "s": 26513, "text": "Comments" }, { "code": null, "e": 26535, "s": 26522, "text": "Old Comments" }, { "code": null, "e": 26596, "s": 26535, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26664, "s": 26596, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 26720, "s": 26664, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 26775, "s": 26720, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 26814, "s": 26775, "text": "Difference between HashMap and HashSet" }, { "code": null, "e": 26834, "s": 26814, "text": "Layers of OSI Model" }, { "code": null, "e": 26858, "s": 26834, "text": "ACID Properties in DBMS" }, { "code": null, "e": 26885, "s": 26858, "text": "Types of Operating Systems" }, { "code": null, "e": 26898, "s": 26885, "text": "TCP/IP Model" } ]
Data Access Object Pattern - GeeksforGeeks
02 Dec, 2021 Data Access Object Pattern or DAO pattern is used to separate low-level data accessing API or operations from high-level business services. Following are the participants in Data Access Object Pattern. UML Diagram Data Access Object Pattern Advantages 1. The advantage of using data access objects is the relatively simple and rigorous separation between two important parts of an application that can but should not know anything of each other, and which can be expected to evolve frequently and independently. 2. If we need to change the underlying persistence mechanism we only have to change the DAO layer and not all the places in the domain logic where the DAO layer is used from. Disadvantages 1. Potential disadvantages of using DAO is a leaky abstraction, code duplication, and abstraction inversion. Design components BusinessObject: The BusinessObject represents the data client. It is the object that requires access to the data source to obtain and store data. A BusinessObject may be implemented as a session bean, entity bean, or some other Java object in addition to a servlet or helper bean that accesses the data source. DataAccessObject: The DataAccessObject is the primary object of this pattern. The DataAccessObject abstracts the underlying data access implementation for the BusinessObject to enable transparent access to the data source. DataSource: This represents a data source implementation. A data source could be a database such as an RDBMS, OODBMS, XML repository, flat file system, and so forth. A data source can also be another system service or some kind of repository. TransferObject: This represents a Transfer Object used as a data carrier. The DataAccessObject may use a Transfer Object to return data to the client. The DataAccessObject may also receive the data from the client in a Transfer Object to update the data in the data source. Example: Java // Java program to illustrate Data Access Object Pattern // Importing required classesimport java.util.ArrayList;import java.util.List; // Class 1// Helper classclass Developer { private String name; private int DeveloperId; // Constructor of Developer class Developer(String name, int DeveloperId) { // This keyword refers to current instance itself this.name = name; this.DeveloperId = DeveloperId; } // Method 1 public String getName() { return name; } // Method 2 public void setName(String name) { this.name = name; } // Method 3 public int getDeveloperId() { return DeveloperId; } // Method 4 public void setDeveloperId(int DeveloperId) { this.DeveloperId = DeveloperId; }} // Interfaceinterface DeveloperDao { public List<Developer> getAllDevelopers(); public Developer getDeveloper(int DeveloperId); public void updateDeveloper(Developer Developer); public void deleteDeveloper(Developer Developer);} // Class 2// Implementing above defined interfaceclass DeveloperDaoImpl implements DeveloperDao { List<Developer> Developers; // Method 1 public DeveloperDaoImpl() { Developers = new ArrayList<Developer>(); Developer Developer1 = new Developer("Kushagra", 0); Developer Developer2 = new Developer("Vikram", 1); Developers.add(Developer1); Developers.add(Developer2); } // Method 2 @Override public void deleteDeveloper(Developer Developer) { Developers.remove(Developer.getDeveloperId()); System.out.println("DeveloperId " + Developer.getDeveloperId() + ", deleted from database"); } // Method 3 @Override public List<Developer> getAllDevelopers() { return Developers; } // Method 4 @Override public Developer getDeveloper(int DeveloperId) { return Developers.get(DeveloperId); } // Method 5 @Override public void updateDeveloper(Developer Developer) { Developers.get(Developer.getDeveloperId()) .setName(Developer.getName()); System.out.println("DeveloperId " + Developer.getDeveloperId() + ", updated in the database"); }} // Class 3// DaoPatternDemoclass GFG { // Main driver method public static void main(String[] args) { DeveloperDao DeveloperDao = new DeveloperDaoImpl(); for (Developer Developer : DeveloperDao.getAllDevelopers()) { System.out.println("DeveloperId : " + Developer.getDeveloperId() + ", Name : " + Developer.getName()); } Developer Developer = DeveloperDao.getAllDevelopers().get(0); Developer.setName("Lokesh"); DeveloperDao.updateDeveloper(Developer); DeveloperDao.getDeveloper(0); System.out.println( "DeveloperId : " + Developer.getDeveloperId() + ", Name : " + Developer.getName()); }} DeveloperId : 0, Name : Kushagra DeveloperId : 1, Name : Vikram DeveloperId 0, updated in the database DeveloperId : 0, Name : Lokesh This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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. solankimayank rkbhola5 Design Pattern Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Command Pattern Difference between Sequence diagram and Collaboration diagram Observer Pattern | Set 2 (Implementation) Template Method Design Pattern Strategy Pattern | Set 1 (Introduction) State Design Pattern Difference between Sequence Diagram and Activity Diagram Memento design pattern Iterator Pattern JDBC Using Model Object and Singleton Class
[ { "code": null, "e": 24558, "s": 24530, "text": "\n02 Dec, 2021" }, { "code": null, "e": 24761, "s": 24558, "text": "Data Access Object Pattern or DAO pattern is used to separate low-level data accessing API or operations from high-level business services. Following are the participants in Data Access Object Pattern. " }, { "code": null, "e": 24800, "s": 24761, "text": "UML Diagram Data Access Object Pattern" }, { "code": null, "e": 24811, "s": 24800, "text": "Advantages" }, { "code": null, "e": 25071, "s": 24811, "text": "1. The advantage of using data access objects is the relatively simple and rigorous separation between two important parts of an application that can but should not know anything of each other, and which can be expected to evolve frequently and independently." }, { "code": null, "e": 25246, "s": 25071, "text": "2. If we need to change the underlying persistence mechanism we only have to change the DAO layer and not all the places in the domain logic where the DAO layer is used from." }, { "code": null, "e": 25261, "s": 25246, "text": "Disadvantages " }, { "code": null, "e": 25370, "s": 25261, "text": "1. Potential disadvantages of using DAO is a leaky abstraction, code duplication, and abstraction inversion." }, { "code": null, "e": 25388, "s": 25370, "text": "Design components" }, { "code": null, "e": 25699, "s": 25388, "text": "BusinessObject: The BusinessObject represents the data client. It is the object that requires access to the data source to obtain and store data. A BusinessObject may be implemented as a session bean, entity bean, or some other Java object in addition to a servlet or helper bean that accesses the data source." }, { "code": null, "e": 25922, "s": 25699, "text": "DataAccessObject: The DataAccessObject is the primary object of this pattern. The DataAccessObject abstracts the underlying data access implementation for the BusinessObject to enable transparent access to the data source." }, { "code": null, "e": 26165, "s": 25922, "text": "DataSource: This represents a data source implementation. A data source could be a database such as an RDBMS, OODBMS, XML repository, flat file system, and so forth. A data source can also be another system service or some kind of repository." }, { "code": null, "e": 26439, "s": 26165, "text": "TransferObject: This represents a Transfer Object used as a data carrier. The DataAccessObject may use a Transfer Object to return data to the client. The DataAccessObject may also receive the data from the client in a Transfer Object to update the data in the data source." }, { "code": null, "e": 26448, "s": 26439, "text": "Example:" }, { "code": null, "e": 26453, "s": 26448, "text": "Java" }, { "code": "// Java program to illustrate Data Access Object Pattern // Importing required classesimport java.util.ArrayList;import java.util.List; // Class 1// Helper classclass Developer { private String name; private int DeveloperId; // Constructor of Developer class Developer(String name, int DeveloperId) { // This keyword refers to current instance itself this.name = name; this.DeveloperId = DeveloperId; } // Method 1 public String getName() { return name; } // Method 2 public void setName(String name) { this.name = name; } // Method 3 public int getDeveloperId() { return DeveloperId; } // Method 4 public void setDeveloperId(int DeveloperId) { this.DeveloperId = DeveloperId; }} // Interfaceinterface DeveloperDao { public List<Developer> getAllDevelopers(); public Developer getDeveloper(int DeveloperId); public void updateDeveloper(Developer Developer); public void deleteDeveloper(Developer Developer);} // Class 2// Implementing above defined interfaceclass DeveloperDaoImpl implements DeveloperDao { List<Developer> Developers; // Method 1 public DeveloperDaoImpl() { Developers = new ArrayList<Developer>(); Developer Developer1 = new Developer(\"Kushagra\", 0); Developer Developer2 = new Developer(\"Vikram\", 1); Developers.add(Developer1); Developers.add(Developer2); } // Method 2 @Override public void deleteDeveloper(Developer Developer) { Developers.remove(Developer.getDeveloperId()); System.out.println(\"DeveloperId \" + Developer.getDeveloperId() + \", deleted from database\"); } // Method 3 @Override public List<Developer> getAllDevelopers() { return Developers; } // Method 4 @Override public Developer getDeveloper(int DeveloperId) { return Developers.get(DeveloperId); } // Method 5 @Override public void updateDeveloper(Developer Developer) { Developers.get(Developer.getDeveloperId()) .setName(Developer.getName()); System.out.println(\"DeveloperId \" + Developer.getDeveloperId() + \", updated in the database\"); }} // Class 3// DaoPatternDemoclass GFG { // Main driver method public static void main(String[] args) { DeveloperDao DeveloperDao = new DeveloperDaoImpl(); for (Developer Developer : DeveloperDao.getAllDevelopers()) { System.out.println(\"DeveloperId : \" + Developer.getDeveloperId() + \", Name : \" + Developer.getName()); } Developer Developer = DeveloperDao.getAllDevelopers().get(0); Developer.setName(\"Lokesh\"); DeveloperDao.updateDeveloper(Developer); DeveloperDao.getDeveloper(0); System.out.println( \"DeveloperId : \" + Developer.getDeveloperId() + \", Name : \" + Developer.getName()); }}", "e": 29559, "s": 26453, "text": null }, { "code": null, "e": 29693, "s": 29559, "text": "DeveloperId : 0, Name : Kushagra\nDeveloperId : 1, Name : Vikram\nDeveloperId 0, updated in the database\nDeveloperId : 0, Name : Lokesh" }, { "code": null, "e": 30113, "s": 29693, "text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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": 30127, "s": 30113, "text": "solankimayank" }, { "code": null, "e": 30136, "s": 30127, "text": "rkbhola5" }, { "code": null, "e": 30151, "s": 30136, "text": "Design Pattern" }, { "code": null, "e": 30249, "s": 30151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30258, "s": 30249, "text": "Comments" }, { "code": null, "e": 30271, "s": 30258, "text": "Old Comments" }, { "code": null, "e": 30287, "s": 30271, "text": "Command Pattern" }, { "code": null, "e": 30349, "s": 30287, "text": "Difference between Sequence diagram and Collaboration diagram" }, { "code": null, "e": 30391, "s": 30349, "text": "Observer Pattern | Set 2 (Implementation)" }, { "code": null, "e": 30422, "s": 30391, "text": "Template Method Design Pattern" }, { "code": null, "e": 30462, "s": 30422, "text": "Strategy Pattern | Set 1 (Introduction)" }, { "code": null, "e": 30483, "s": 30462, "text": "State Design Pattern" }, { "code": null, "e": 30540, "s": 30483, "text": "Difference between Sequence Diagram and Activity Diagram" }, { "code": null, "e": 30563, "s": 30540, "text": "Memento design pattern" }, { "code": null, "e": 30580, "s": 30563, "text": "Iterator Pattern" } ]
Text Classification on Disaster Tweets with LSTM and Word Embedding | by Emmanuella Anggi | Towards Data Science
This was my first Kaggle notebook and I thought why not write it on Medium too? Full code on my Github. In this post, I will elaborate on how to use fastText and GloVe as word embedding on LSTM model for text classification. I got interested in Word Embedding while doing my paper on Natural Language Generation. It showed that embedding matrix for the weight on embedding layer improved the performance of the model. But since it was NLG, the measurement was subjective. And I only used fastText too. So in this article, I want to see how each method (with fastText and GloVe and without) affects to the prediction. On my Github code, I also compare the result with CNN. The dataset that i use here is from one of competition on Kaggle, consisted of tweets and labelled with whether the tweet is using disastrous words to inform a real disaster or merely just used it metaphorically. Honestly, on first seeing this dataset, I immediately thought about BERT and its ability to understand way better than what I proposed on this article (further reading on BERT). But anyway, in this article I will focus on fastText and GloVe. Let’s go? The data consisted of 7613 tweets (columns Text) with label (column Target) whether they were talking about a real disaster or not. With 3271 rows informing real disaster and 4342 rows informing not real disaster. The data shared on kaggle competition, and if you want to learn more about the data you can read it here. Example of real disaster word in a text : “ Forest fire near La Ronge Sask. Canada “ Example of the use of disaster word but not about disaster: “These boxes are ready to explode! Exploding Kittens finally arrived! gameofkittens #explodingkittens” The data will be divided for training (6090 rows) and testing (1523 rows) then proceed to pre-processing. We will only be using the text and target columns. from sklearn.model_selection import train_test_splitdata = pd.read_csv('train.csv', sep=',', header=0)train_df, test_df = train_test_split(data, test_size=0.2, random_state=42, shuffle=True) Pre-processing steps that used here: Case FoldingCleaning Stop WordsTokenizing Case Folding Cleaning Stop Words Tokenizing from sklearn.utils import shuffleraw_docs_train = train_df['text'].tolist()raw_docs_test = test_df['text'].tolist()num_classes = len(label_names)processed_docs_train = []for doc in tqdm(raw_docs_train): tokens = word_tokenize(doc) filtered = [word for word in tokens if word not in stop_words] processed_docs_train.append(" ".join(filtered))processed_docs_test = []for doc in tqdm(raw_docs_test): tokens = word_tokenize(doc) filtered = [word for word in tokens if word not in stop_words] processed_docs_test.append(" ".join(filtered))tokenizer = Tokenizer(num_words=MAX_NB_WORDS, lower=True, char_level=False)tokenizer.fit_on_texts(processed_docs_train + processed_docs_test) word_seq_train = tokenizer.texts_to_sequences(processed_docs_train)word_seq_test = tokenizer.texts_to_sequences(processed_docs_test)word_index = tokenizer.word_indexword_seq_train = sequence.pad_sequences(word_seq_train, maxlen=max_seq_len)word_seq_test = sequence.pad_sequences(word_seq_test, maxlen=max_seq_len) Step 1. Download Pre-trained model The first step on working both with fastText and Glove is downloading each of pre-trained model. I used Google Colab to prevent the use of big memory on my laptop, so I downloaded it with request library and unzip it directly on the notebook. I used the biggest pre-trained model from both word embedding. fastText model gave 2 million word vectors (600B tokens) and GloVe gave 2.2 million word vectors (840B tokens), both trained on Common Crawl. fastText pre-trained download import requests, zipfile, iozip_file_url = “https://dl.fbaipublicfiles.com/fasttext/vectors-english/wiki-news-300d-1M.vec.zip"r = requests.get(zip_file_url)z = zipfile.ZipFile(io.BytesIO(r.content))z.extractall() GloVe pre-trained download import requests, zipfile, iozip_file_url = “http://nlp.stanford.edu/data/glove.840B.300d.zip"r = requests.get(zip_file_url)z = zipfile.ZipFile(io.BytesIO(r.content))z.extractall() Step 2. Load Pre-trained model to Word Vectors FastText gave the format to load the word vectors and so I used that to load both models. embeddings_index = {}f = codecs.open(‘crawl-300d-2M.vec’, encoding=’utf-8')# for Glove# f = codecs.open(‘glove.840B.300d.txt’, encoding=’utf-8')for line in tqdm(f):values = line.rstrip().rsplit(‘ ‘)word = values[0]coefs = np.asarray(values[1:], dtype=’float32')embeddings_index[word] = coefsf.close() Step 3. Embedding Matrix Embedding matrix will be used in embedding layer for the weight of each word in training data. It’s made by enumerating each unique word in the training dataset that existed in tokenized word index and locate the embedding weight with the weight from fastText orGloVe (more about embedding matrix). But there is a possibility that there are words that aren’t in the vectors such as typos or abbreviation or usernames. Those words will be stored in a list and we can compare the performance of handling words from fastText and GloVe words_not_found = []nb_words = min(MAX_NB_WORDS, len(word_index)+1)embedding_matrix = np.zeros((nb_words, embed_dim))for word, i in word_index.items(): if i >= nb_words: continue embedding_vector = embeddings_index.get(word) if (embedding_vector is not None) and len(embedding_vector) > 0: embedding_matrix[i] = embedding_vector else: words_not_found.append(word)print('number of null word embeddings: %d' % np.sum(np.sum(embedding_matrix, axis=1) == 0)) Number of null word embeddings on fastText is 9175 and on GloVe is 9186. Can be assumed that fastText handle more words even when the pre-trained was trained on fewer words. You can do fine-tuning on hyper-parameters or architecture, but I’m going to use the very simple one with Embedding Layer, LSTM layer, Dense layer, and Drop out Layer. from keras.layers import BatchNormalizationimport tensorflow as tfmodel = tf.keras.Sequential()model.add(Embedding(nb_words, embed_dim, input_length=max_seq_len, weights=[embedding_matrix],trainable=False))model.add(Bidirectional(LSTM(32, return_sequences= True)))model.add(Dense(32,activation=’relu’))model.add(Dropout(0.3))model.add(Dense(1,activation=’sigmoid’))model.summary() from keras.optimizers import RMSpropfrom keras.callbacks import ModelCheckpointfrom tensorflow.keras.callbacks import EarlyStoppingmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])es_callback = EarlyStopping(monitor='val_loss', patience=3)history = model.fit(word_seq_train, y_train, batch_size=256, epochs=30, validation_split=0.3, callbacks=[es_callback], shuffle=False) fastText gave the best performance with accuracy for about 83% while GloVe gave 81% accuracy. The difference on the performance isn’t so significant but to compare it with the performance of model without word embedding (68%), we can see the significant use of Word Embedding on embedding layer weight. For more about the training performance, detail code, and if you want to apply it on a different dataset, you can see the full code on my GitHub. Thank you for reading!
[ { "code": null, "e": 251, "s": 171, "text": "This was my first Kaggle notebook and I thought why not write it on Medium too?" }, { "code": null, "e": 275, "s": 251, "text": "Full code on my Github." }, { "code": null, "e": 1234, "s": 275, "text": "In this post, I will elaborate on how to use fastText and GloVe as word embedding on LSTM model for text classification. I got interested in Word Embedding while doing my paper on Natural Language Generation. It showed that embedding matrix for the weight on embedding layer improved the performance of the model. But since it was NLG, the measurement was subjective. And I only used fastText too. So in this article, I want to see how each method (with fastText and GloVe and without) affects to the prediction. On my Github code, I also compare the result with CNN. The dataset that i use here is from one of competition on Kaggle, consisted of tweets and labelled with whether the tweet is using disastrous words to inform a real disaster or merely just used it metaphorically. Honestly, on first seeing this dataset, I immediately thought about BERT and its ability to understand way better than what I proposed on this article (further reading on BERT)." }, { "code": null, "e": 1298, "s": 1234, "text": "But anyway, in this article I will focus on fastText and GloVe." }, { "code": null, "e": 1308, "s": 1298, "text": "Let’s go?" }, { "code": null, "e": 1628, "s": 1308, "text": "The data consisted of 7613 tweets (columns Text) with label (column Target) whether they were talking about a real disaster or not. With 3271 rows informing real disaster and 4342 rows informing not real disaster. The data shared on kaggle competition, and if you want to learn more about the data you can read it here." }, { "code": null, "e": 1670, "s": 1628, "text": "Example of real disaster word in a text :" }, { "code": null, "e": 1713, "s": 1670, "text": "“ Forest fire near La Ronge Sask. Canada “" }, { "code": null, "e": 1773, "s": 1713, "text": "Example of the use of disaster word but not about disaster:" }, { "code": null, "e": 1876, "s": 1773, "text": "“These boxes are ready to explode! Exploding Kittens finally arrived! gameofkittens #explodingkittens”" }, { "code": null, "e": 2033, "s": 1876, "text": "The data will be divided for training (6090 rows) and testing (1523 rows) then proceed to pre-processing. We will only be using the text and target columns." }, { "code": null, "e": 2224, "s": 2033, "text": "from sklearn.model_selection import train_test_splitdata = pd.read_csv('train.csv', sep=',', header=0)train_df, test_df = train_test_split(data, test_size=0.2, random_state=42, shuffle=True)" }, { "code": null, "e": 2261, "s": 2224, "text": "Pre-processing steps that used here:" }, { "code": null, "e": 2303, "s": 2261, "text": "Case FoldingCleaning Stop WordsTokenizing" }, { "code": null, "e": 2316, "s": 2303, "text": "Case Folding" }, { "code": null, "e": 2336, "s": 2316, "text": "Cleaning Stop Words" }, { "code": null, "e": 2347, "s": 2336, "text": "Tokenizing" }, { "code": null, "e": 3344, "s": 2347, "text": "from sklearn.utils import shuffleraw_docs_train = train_df['text'].tolist()raw_docs_test = test_df['text'].tolist()num_classes = len(label_names)processed_docs_train = []for doc in tqdm(raw_docs_train): tokens = word_tokenize(doc) filtered = [word for word in tokens if word not in stop_words] processed_docs_train.append(\" \".join(filtered))processed_docs_test = []for doc in tqdm(raw_docs_test): tokens = word_tokenize(doc) filtered = [word for word in tokens if word not in stop_words] processed_docs_test.append(\" \".join(filtered))tokenizer = Tokenizer(num_words=MAX_NB_WORDS, lower=True, char_level=False)tokenizer.fit_on_texts(processed_docs_train + processed_docs_test) word_seq_train = tokenizer.texts_to_sequences(processed_docs_train)word_seq_test = tokenizer.texts_to_sequences(processed_docs_test)word_index = tokenizer.word_indexword_seq_train = sequence.pad_sequences(word_seq_train, maxlen=max_seq_len)word_seq_test = sequence.pad_sequences(word_seq_test, maxlen=max_seq_len)" }, { "code": null, "e": 3379, "s": 3344, "text": "Step 1. Download Pre-trained model" }, { "code": null, "e": 3622, "s": 3379, "text": "The first step on working both with fastText and Glove is downloading each of pre-trained model. I used Google Colab to prevent the use of big memory on my laptop, so I downloaded it with request library and unzip it directly on the notebook." }, { "code": null, "e": 3827, "s": 3622, "text": "I used the biggest pre-trained model from both word embedding. fastText model gave 2 million word vectors (600B tokens) and GloVe gave 2.2 million word vectors (840B tokens), both trained on Common Crawl." }, { "code": null, "e": 3857, "s": 3827, "text": "fastText pre-trained download" }, { "code": null, "e": 4070, "s": 3857, "text": "import requests, zipfile, iozip_file_url = “https://dl.fbaipublicfiles.com/fasttext/vectors-english/wiki-news-300d-1M.vec.zip\"r = requests.get(zip_file_url)z = zipfile.ZipFile(io.BytesIO(r.content))z.extractall()" }, { "code": null, "e": 4097, "s": 4070, "text": "GloVe pre-trained download" }, { "code": null, "e": 4277, "s": 4097, "text": "import requests, zipfile, iozip_file_url = “http://nlp.stanford.edu/data/glove.840B.300d.zip\"r = requests.get(zip_file_url)z = zipfile.ZipFile(io.BytesIO(r.content))z.extractall()" }, { "code": null, "e": 4324, "s": 4277, "text": "Step 2. Load Pre-trained model to Word Vectors" }, { "code": null, "e": 4414, "s": 4324, "text": "FastText gave the format to load the word vectors and so I used that to load both models." }, { "code": null, "e": 4715, "s": 4414, "text": "embeddings_index = {}f = codecs.open(‘crawl-300d-2M.vec’, encoding=’utf-8')# for Glove# f = codecs.open(‘glove.840B.300d.txt’, encoding=’utf-8')for line in tqdm(f):values = line.rstrip().rsplit(‘ ‘)word = values[0]coefs = np.asarray(values[1:], dtype=’float32')embeddings_index[word] = coefsf.close()" }, { "code": null, "e": 4740, "s": 4715, "text": "Step 3. Embedding Matrix" }, { "code": null, "e": 5039, "s": 4740, "text": "Embedding matrix will be used in embedding layer for the weight of each word in training data. It’s made by enumerating each unique word in the training dataset that existed in tokenized word index and locate the embedding weight with the weight from fastText orGloVe (more about embedding matrix)." }, { "code": null, "e": 5272, "s": 5039, "text": "But there is a possibility that there are words that aren’t in the vectors such as typos or abbreviation or usernames. Those words will be stored in a list and we can compare the performance of handling words from fastText and GloVe" }, { "code": null, "e": 5745, "s": 5272, "text": "words_not_found = []nb_words = min(MAX_NB_WORDS, len(word_index)+1)embedding_matrix = np.zeros((nb_words, embed_dim))for word, i in word_index.items(): if i >= nb_words: continue embedding_vector = embeddings_index.get(word) if (embedding_vector is not None) and len(embedding_vector) > 0: embedding_matrix[i] = embedding_vector else: words_not_found.append(word)print('number of null word embeddings: %d' % np.sum(np.sum(embedding_matrix, axis=1) == 0))" }, { "code": null, "e": 5919, "s": 5745, "text": "Number of null word embeddings on fastText is 9175 and on GloVe is 9186. Can be assumed that fastText handle more words even when the pre-trained was trained on fewer words." }, { "code": null, "e": 6087, "s": 5919, "text": "You can do fine-tuning on hyper-parameters or architecture, but I’m going to use the very simple one with Embedding Layer, LSTM layer, Dense layer, and Drop out Layer." }, { "code": null, "e": 6468, "s": 6087, "text": "from keras.layers import BatchNormalizationimport tensorflow as tfmodel = tf.keras.Sequential()model.add(Embedding(nb_words, embed_dim, input_length=max_seq_len, weights=[embedding_matrix],trainable=False))model.add(Bidirectional(LSTM(32, return_sequences= True)))model.add(Dense(32,activation=’relu’))model.add(Dropout(0.3))model.add(Dense(1,activation=’sigmoid’))model.summary()" }, { "code": null, "e": 6873, "s": 6468, "text": "from keras.optimizers import RMSpropfrom keras.callbacks import ModelCheckpointfrom tensorflow.keras.callbacks import EarlyStoppingmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])es_callback = EarlyStopping(monitor='val_loss', patience=3)history = model.fit(word_seq_train, y_train, batch_size=256, epochs=30, validation_split=0.3, callbacks=[es_callback], shuffle=False)" }, { "code": null, "e": 7176, "s": 6873, "text": "fastText gave the best performance with accuracy for about 83% while GloVe gave 81% accuracy. The difference on the performance isn’t so significant but to compare it with the performance of model without word embedding (68%), we can see the significant use of Word Embedding on embedding layer weight." }, { "code": null, "e": 7322, "s": 7176, "text": "For more about the training performance, detail code, and if you want to apply it on a different dataset, you can see the full code on my GitHub." } ]
How to create a stacked bar plot with vertical bars in R using ggplot2?
Traditionally, the stacked bar plot has multiple bars for each level of categories lying upon each other. But this visual can be changed by creating vertical bars for each level of categories, this will help us to read the stacked bar easily as compared to traditional stacked bar plot because people have a habit to read vertical bars. Consider the below data frame − Live Demo set.seed(999) Class<-sample(c("I","II","III","IV"),20,replace=TRUE) Category<-sample(LETTERS[1:4],20,replace=TRUE) Score<-sample(41:100,20) df<-data.frame(Class,Category,Score) df Class Category Score 1 II D 47 2 III C 88 3 I C 83 4 IV B 67 5 IV D 61 6 I D 56 7 III C 74 8 I C 54 9 II D 100 10 III B 43 11 II A 77 12 III A 72 13 I C 92 14 IV C 81 15 I C 49 16 IV D 97 17 I D 91 18 IV D 73 19 I A 59 20 I B 75 Loading ggplot2 and creating a stacked bar chart with bars on top of each other − library(ggplot2) ggplot(df,aes(Class,Score,fill=Category))+geom_bar(stat="identity") Creating a stacked bar chart with vertical bars − ggplot(df,aes(Class,Score,fill=Category))+geom_bar(stat="identity",position="dodge")
[ { "code": null, "e": 1399, "s": 1062, "text": "Traditionally, the stacked bar plot has multiple bars for each level of categories lying upon each other. But this visual can be changed by creating vertical bars for each level of categories, this will help us to read the stacked bar easily as compared to traditional stacked bar plot because people have a habit to read vertical bars." }, { "code": null, "e": 1431, "s": 1399, "text": "Consider the below data frame −" }, { "code": null, "e": 1442, "s": 1431, "text": " Live Demo" }, { "code": null, "e": 1622, "s": 1442, "text": "set.seed(999)\nClass<-sample(c(\"I\",\"II\",\"III\",\"IV\"),20,replace=TRUE)\nCategory<-sample(LETTERS[1:4],20,replace=TRUE)\nScore<-sample(41:100,20)\ndf<-data.frame(Class,Category,Score)\ndf" }, { "code": null, "e": 2086, "s": 1622, "text": " Class Category Score\n1 II D 47\n2 III C 88\n3 I C 83\n4 IV B 67\n5 IV D 61\n6 I D 56\n7 III C 74\n8 I C 54\n9 II D 100\n10 III B 43\n11 II A 77\n12 III A 72\n13 I C 92\n14 IV C 81\n15 I C 49\n16 IV D 97\n17 I D 91\n18 IV D 73\n19 I A 59\n20 I B 75" }, { "code": null, "e": 2168, "s": 2086, "text": "Loading ggplot2 and creating a stacked bar chart with bars on top of each other −" }, { "code": null, "e": 2253, "s": 2168, "text": "library(ggplot2) ggplot(df,aes(Class,Score,fill=Category))+geom_bar(stat=\"identity\")" }, { "code": null, "e": 2303, "s": 2253, "text": "Creating a stacked bar chart with vertical bars −" }, { "code": null, "e": 2388, "s": 2303, "text": "ggplot(df,aes(Class,Score,fill=Category))+geom_bar(stat=\"identity\",position=\"dodge\")" } ]
Read List of Dictionaries from File in Python - GeeksforGeeks
26 Jul, 2020 A dictionary in Python is a collection where every value is mapped to a key. Since they are unordered and there is no constraint on the data type of values and keys stored in the dictionary, it is tricky to read dictionaries from files in Python. The problem statement mentions a list of dictionaries that have to be read from a file. There can be two ways of doing this: 1. Reading from Text File We can read data from a text file as a string and convert that data into a dictionary in Python. Assuming our data is stored in a text file in the following format – {'geek': 10, 'geeky': True} {'GeeksforGeeks': 'Education', 'geekgod': 101.0, 3: 'gfg'} {'supergeek': 5} The approach would include the following steps: Open the text file in read mode and read the content Parse every line in the content into a dictionary. 2. Reading using Pickle Module The pickle module in Python is mostly used in fields like Data Science where data persistence is critical. The pickle module stores the given data as a serialized byte sequence into files which can be easily retrieved at a later time. Pickle module supports various Python objects and dictionaries are one among them. This method would include the following steps: Importing the pickle module Opening the file in read binary mode Loading the data into a variable using pickle module’s dump method list_dictionary = pickle.load(filehandler) Below are the examples of the above-discussed approaches. 1. Reading from Text File: Input File: Python3 def parse(d): dictionary = dict() # Removes curly braces and splits the pairs into a list pairs = d.strip('{}').split(', ') for i in pairs: pair = i.split(': ') # Other symbols from the key-value pair should be stripped. dictionary[pair[0].strip('\'\'\"\"')] = pair[1].strip('\'\'\"\"') return dictionarytry: geeky_file = open('geeky_file.txt', 'rt') lines = geeky_file.read().split('\n') for l in lines: if l != '': dictionary = parse(l) print(dictionary) geeky_file.close()except: print("Something unexpected occurred!") Output: {'geek': '10', 'geeky': 'True'} {'GeeksforGeeks': 'Education', 'geekgod': '101.0', '3': 'gfg'} {'supergeek': '5'} 2. Reading using Pickle Python3 import pickle try: geeky_file = open('GFG.txt', 'r') dictionary_list = pickle.load(geeky_file) for d in dictionary_list: print(d) geeky_file.close() except: print("Something unexpected occurred!") Output: Python dictionary-programs python-dict python-file-handling Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python OOPs Concepts Create a Pandas DataFrame from Lists *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24272, "s": 24244, "text": "\n26 Jul, 2020" }, { "code": null, "e": 24519, "s": 24272, "text": "A dictionary in Python is a collection where every value is mapped to a key. Since they are unordered and there is no constraint on the data type of values and keys stored in the dictionary, it is tricky to read dictionaries from files in Python." }, { "code": null, "e": 24644, "s": 24519, "text": "The problem statement mentions a list of dictionaries that have to be read from a file. There can be two ways of doing this:" }, { "code": null, "e": 24670, "s": 24644, "text": "1. Reading from Text File" }, { "code": null, "e": 24837, "s": 24670, "text": "We can read data from a text file as a string and convert that data into a dictionary in Python. Assuming our data is stored in a text file in the following format – " }, { "code": null, "e": 24942, "s": 24837, "text": "{'geek': 10, 'geeky': True}\n{'GeeksforGeeks': 'Education', 'geekgod': 101.0, 3: 'gfg'}\n{'supergeek': 5}\n" }, { "code": null, "e": 24990, "s": 24942, "text": "The approach would include the following steps:" }, { "code": null, "e": 25043, "s": 24990, "text": "Open the text file in read mode and read the content" }, { "code": null, "e": 25094, "s": 25043, "text": "Parse every line in the content into a dictionary." }, { "code": null, "e": 25125, "s": 25094, "text": "2. Reading using Pickle Module" }, { "code": null, "e": 25490, "s": 25125, "text": "The pickle module in Python is mostly used in fields like Data Science where data persistence is critical. The pickle module stores the given data as a serialized byte sequence into files which can be easily retrieved at a later time. Pickle module supports various Python objects and dictionaries are one among them. This method would include the following steps:" }, { "code": null, "e": 25518, "s": 25490, "text": "Importing the pickle module" }, { "code": null, "e": 25555, "s": 25518, "text": "Opening the file in read binary mode" }, { "code": null, "e": 25622, "s": 25555, "text": "Loading the data into a variable using pickle module’s dump method" }, { "code": null, "e": 25666, "s": 25622, "text": "list_dictionary = pickle.load(filehandler)\n" }, { "code": null, "e": 25724, "s": 25666, "text": "Below are the examples of the above-discussed approaches." }, { "code": null, "e": 25751, "s": 25724, "text": "1. Reading from Text File:" }, { "code": null, "e": 25763, "s": 25751, "text": "Input File:" }, { "code": null, "e": 25771, "s": 25763, "text": "Python3" }, { "code": "def parse(d): dictionary = dict() # Removes curly braces and splits the pairs into a list pairs = d.strip('{}').split(', ') for i in pairs: pair = i.split(': ') # Other symbols from the key-value pair should be stripped. dictionary[pair[0].strip('\\'\\'\\\"\\\"')] = pair[1].strip('\\'\\'\\\"\\\"') return dictionarytry: geeky_file = open('geeky_file.txt', 'rt') lines = geeky_file.read().split('\\n') for l in lines: if l != '': dictionary = parse(l) print(dictionary) geeky_file.close()except: print(\"Something unexpected occurred!\")", "e": 26374, "s": 25771, "text": null }, { "code": null, "e": 26382, "s": 26374, "text": "Output:" }, { "code": null, "e": 26496, "s": 26382, "text": "{'geek': '10', 'geeky': 'True'}\n{'GeeksforGeeks': 'Education', 'geekgod': '101.0', '3': 'gfg'}\n{'supergeek': '5'}" }, { "code": null, "e": 26520, "s": 26496, "text": "2. Reading using Pickle" }, { "code": null, "e": 26528, "s": 26520, "text": "Python3" }, { "code": "import pickle try: geeky_file = open('GFG.txt', 'r') dictionary_list = pickle.load(geeky_file) for d in dictionary_list: print(d) geeky_file.close() except: print(\"Something unexpected occurred!\")", "e": 26757, "s": 26528, "text": null }, { "code": null, "e": 26765, "s": 26757, "text": "Output:" }, { "code": null, "e": 26792, "s": 26765, "text": "Python dictionary-programs" }, { "code": null, "e": 26804, "s": 26792, "text": "python-dict" }, { "code": null, "e": 26825, "s": 26804, "text": "python-file-handling" }, { "code": null, "e": 26832, "s": 26825, "text": "Python" }, { "code": null, "e": 26844, "s": 26832, "text": "python-dict" }, { "code": null, "e": 26942, "s": 26844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26951, "s": 26942, "text": "Comments" }, { "code": null, "e": 26964, "s": 26951, "text": "Old Comments" }, { "code": null, "e": 26982, "s": 26964, "text": "Python Dictionary" }, { "code": null, "e": 27014, "s": 26982, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27036, "s": 27014, "text": "Enumerate() in Python" }, { "code": null, "e": 27066, "s": 27036, "text": "Iterate over a list in Python" }, { "code": null, "e": 27108, "s": 27066, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27151, "s": 27108, "text": "Python program to convert a list to string" }, { "code": null, "e": 27172, "s": 27151, "text": "Python OOPs Concepts" }, { "code": null, "e": 27209, "s": 27172, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27238, "s": 27209, "text": "*args and **kwargs in Python" } ]
Introduction to NLP - Part 3: TF-IDF explained | by Zolzaya Luvsandorj | Towards Data Science
Term frequency-inverse document frequency, also known as tf-idf... 💤 Does this sound gibberish to you? But you wish it doesn’t? In this post, I will first demonstrate how to vectorise text data to tf-idf using sklearn and then show a step-by-step process on how do it ourselves without any software. I hope tf-idf will be clearer to you by the end of this post! 🎓 First things first, let’s familiarise with some definitions to ensure that we are aligned on what each concept means: * tf and tf-idf were broken into two variations: one based on count (_raw) and the other on percentage to make things clear. ** A more generic definition for idf would be a weight that upweights less frequent terms and downweights more frequent terms. However, I have chosen a simple definition because the lowest weight a term can have is 1 based on the formulas being used. Either way, less frequent terms are upweighted and more frequent terms are downweighted in tf-idf compared to tf. The examples in brackets show references to the dataset used in this post. To keep things manageable, we will create 2 small documents from these sentences which will allow us to monitor inputs and outputs for each step: d1 = 'I thought, I thought of thinking of thanking you for the gift'd2 = 'She was thinking of going to go and get you a GIFT!' If you are wondering why I have chosen these two sentences, I had to think of the smallest example that translated into my ideal end vector after they are preproccesed and think backwards. A tongue twister came in handy! This section assumes that you have access to and are familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started. I have used and tested the scripts in Python 3.7.1. Let’s make sure you have the right tools before using the code. We will use the following powerful third party packages: pandas: Data analysis library, nltk: Natural Language Tool Kit library and sklearn: Machine Learning library. The script below can help you download these corpora. If you have already downloaded, running this will notify you that it is up-to-date: import nltknltk.download('stopwords')nltk.download('wordnet') Firstly, let’s prepare the environment with packages and data: # Import packages and modulesimport pandas as pdfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import RegexpTokenizerfrom nltk.corpus import stopwordsfrom sklearn.feature_extraction.text import TfidfVectorizer# Create a dataframeX_train = pd.DataFrame({'text': [d1, d2]}) From now on, we will refer ‘X_train’ as our corpus (despite its size) and two sentences as documents. Second, we will need a text processing function to pass it on to TfidfVectorizer: def preprocess_text(text): # Tokenise words while ignoring punctuation tokeniser = RegexpTokenizer(r'\w+') tokens = tokeniser.tokenize(text) # Lowercase and lemmatise lemmatiser = WordNetLemmatizer() lemmas = [lemmatiser.lemmatize(token.lower(), pos='v') for token in tokens] # Remove stopwords keywords= [lemma for lemma in lemmas if lemma not in stopwords.words('english')] return keywords 🔗 I have explained this function in detail in the first part of the series if you need explanation. This preprocessor will transform the documents to: d1 = [‘think’, ‘think’, ‘think’, ‘thank’, ‘gift’]d2 = [‘think’, ‘go’, ‘go’, ‘get’, ‘gift’] Lastly, preprocess the corpus: # Create an instance of TfidfVectorizervectoriser = TfidfVectorizer(analyzer=preprocess_text)# Fit to the data and transform to feature matrixX_train = vectoriser.fit_transform(X_train['text'])# Convert sparse matrix to dataframeX_train = pd.DataFrame.sparse.from_spmatrix(X_train)# Save mapping on which index refers to which wordscol_map = {v:k for k, v in vectoriser.vocabulary_.items()}# Rename each column using the mappingfor col in X_train.columns: X_train.rename(columns={col: col_map[col]}, inplace=True)X_train Once the script is run, you will get this output: Tada❕ We have vectorised the corpus to tf-idf! The data is now in a format that is acceptable for a machine learning model. Let’s see how test documents with or without unseen terms get transformed: d3 = “He thinks he will go!”d4 = “They don’t know what to buy!”# Create dataframeX_test = pd.DataFrame({‘text’: [d3, d4]})# Transform to feature matrixX_test = vectoriser.transform(X_test['text'])# Convert sparse matrix to dataframeX_test = pd.DataFrame.sparse.from_spmatrix(X_test)# Add column names to make it more readiblefor col in X_test.columns: X_test.rename(columns={col: col_map[col]}, inplace=True)X_test When preprocess_text is applied, the test documents will transform into: d3 = [‘think’, 'go'] # vectoritiser is familiar with these termsd4 = [‘know’, ‘buy’] # vectoritiser is not familiar with these terms Is this what you expected to see when X_test is transformed? Although we have one occurrence of ‘go’ and ‘think’ in d3, do you notice how ‘go’ have been weighted up relative to ‘think’? Does the fact that d4 takes all 0 values make sense to you? Do you notice the number of terms in the matrix is dependent on training data much like any other sklearn transformers in general? I think things get more interesting when we start looking under the hood. In this section, we will do the transformation manually, isn’t that fun? 😍 If you enjoy math, I encourage you to manually calculate problems alongside this guide, or better yet, try to calculate it on your own before proceeding to the answers that follow. In the examples below, rows represent either document or corpus and columns represent terms. 🔒 Problem: Count raw term frequency for each term by document. 💭 Hint: Look at preprocessed d1 and d2 and definition of tf_raw. 🔑 Answer: This table summarises the number of times each term occurs in a document. For instance: We see 3 occurrences of ‘think’ in document 1 but only once in document 2. The number of columns are determined by the number of unique terms in the corpus. This step is actually what sklearn’s CountVectoriser does. (This step is only to compare the final output against.) 🔒 Problem: Calculate term frequency for each term by document. 💭 Hint: What proportion does a term represent in a document? (Row %) 🔑 Answer: The term ‘think’ takes 60% of the terms in document 1. 🔒 Problem: Count document frequency for each term. 💭 Hint: How many documents contain the particular term? 🔑 Answer: The term ‘get’ is present in document 1 only while the term ‘think’ is in both documents. Now, this is where the first calculation happens. ➗ Formula: In this formula, n stands for number of documents. 🔒 Problem: Calculate idf for each term. 🔑 Answer: Doesn’t idf look somewhat inverse to the df? In sklearn, you can access idf_ attribute from the fitted TfidfVectorizer. 🔍 Example calculation: Below, I have provided an example calculation. You can use it as a guide for the remaining terms by replicating the same logic: ➗ Formula: 🔒 Problem: Calculate raw tf-idf (i.e. weighted counts) for each term by document. 🔑 Answer: 🔍 Example calculation: ➗ Formula: 🔒 Problem: Calculate tf-idf for each term by document. 🔑 Answer: 🔍 Example calculation: Yay❕ We have obtained the exact same results! Of note, if you had rounded off anywhere in the interim steps, your final answer may not match precisely with that provided above due to rounding error. 📌 Exercise: See if you can calculate tf-idf for d3 and d4, and match it to the output from sklearn in previous section. 💭 Hint: (1) Count tf_raw - terms refer to the terms from training data, (2) Calculate tf-idf_raw using the idf we have built, (3) Calculate tf-idf. Do these steps only for the terms from training. This method replicates output when smooth_idf=True for TfidfVectorizer or TfidfTransformer in sklearn. If you change this parameter to False, you will have to adjust the idf formula slightly by taking out +1 from both numerator and denominator. Before we wrap up, let’s compare tf vs tf-idf for document 1: Since ‘gift’ and ‘think’ are present in all documents, their relative weight is identical in both tables. However, ‘thank’ is only in document 1, so its relative frequency is higher in tf-idf when compared to ‘gift’ or ‘think’. As such, this demonstrates how tf-idf upweights terms that are in fewer documents and downweights those that are in more. 📌 Exercise: Analyse document 2 on your own. Obviously, manual calculation is more prone to error and not likely to scale well to real corpus with hundreds, thousands or even millions of documents. Many thanks to sklearn contributors for providing such an efficient way to transform text to tf-idf in a just few lines of code. The manual calculations shown here was only to exemplify the underlying implementation when using a software. If you want to replicate outputs yourself from tools other than sklearn, an adjustment to the formulas may be necessary, but the overall idea should be similar. I hope these explanations have been useful and insightful. Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me. Thank you for taking the time to go through this post. I hope that you learned something from reading it. Links to the rest of the posts are collated below:◼️ Part 1: Preprocessing text in Python◼️ Part 2: Difference between lemmatisation and stemming◼️ Part 3: TF-IDF explained◼️ Part 4: Supervised text classification model in Python◼️ Part 5A: Unsupervised topic model in Python (sklearn)◼️ Part 5B: Unsupervised topic model in Python (gensim) Happy transforming! Bye for now 🏃💨 Bird, Steven, Edward Loper and Ewan Klein, Natural Language Processing with Python. O’Reilly Media Inc, 2009 Feature Extraction, sklearn documentation
[ { "code": null, "e": 240, "s": 171, "text": "Term frequency-inverse document frequency, also known as tf-idf... 💤" }, { "code": null, "e": 535, "s": 240, "text": "Does this sound gibberish to you? But you wish it doesn’t? In this post, I will first demonstrate how to vectorise text data to tf-idf using sklearn and then show a step-by-step process on how do it ourselves without any software. I hope tf-idf will be clearer to you by the end of this post! 🎓" }, { "code": null, "e": 653, "s": 535, "text": "First things first, let’s familiarise with some definitions to ensure that we are aligned on what each concept means:" }, { "code": null, "e": 778, "s": 653, "text": "* tf and tf-idf were broken into two variations: one based on count (_raw) and the other on percentage to make things clear." }, { "code": null, "e": 1143, "s": 778, "text": "** A more generic definition for idf would be a weight that upweights less frequent terms and downweights more frequent terms. However, I have chosen a simple definition because the lowest weight a term can have is 1 based on the formulas being used. Either way, less frequent terms are upweighted and more frequent terms are downweighted in tf-idf compared to tf." }, { "code": null, "e": 1218, "s": 1143, "text": "The examples in brackets show references to the dataset used in this post." }, { "code": null, "e": 1364, "s": 1218, "text": "To keep things manageable, we will create 2 small documents from these sentences which will allow us to monitor inputs and outputs for each step:" }, { "code": null, "e": 1491, "s": 1364, "text": "d1 = 'I thought, I thought of thinking of thanking you for the gift'd2 = 'She was thinking of going to go and get you a GIFT!'" }, { "code": null, "e": 1712, "s": 1491, "text": "If you are wondering why I have chosen these two sentences, I had to think of the smallest example that translated into my ideal end vector after they are preproccesed and think backwards. A tongue twister came in handy!" }, { "code": null, "e": 1922, "s": 1712, "text": "This section assumes that you have access to and are familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started." }, { "code": null, "e": 2038, "s": 1922, "text": "I have used and tested the scripts in Python 3.7.1. Let’s make sure you have the right tools before using the code." }, { "code": null, "e": 2095, "s": 2038, "text": "We will use the following powerful third party packages:" }, { "code": null, "e": 2126, "s": 2095, "text": "pandas: Data analysis library," }, { "code": null, "e": 2170, "s": 2126, "text": "nltk: Natural Language Tool Kit library and" }, { "code": null, "e": 2205, "s": 2170, "text": "sklearn: Machine Learning library." }, { "code": null, "e": 2343, "s": 2205, "text": "The script below can help you download these corpora. If you have already downloaded, running this will notify you that it is up-to-date:" }, { "code": null, "e": 2405, "s": 2343, "text": "import nltknltk.download('stopwords')nltk.download('wordnet')" }, { "code": null, "e": 2468, "s": 2405, "text": "Firstly, let’s prepare the environment with packages and data:" }, { "code": null, "e": 2751, "s": 2468, "text": "# Import packages and modulesimport pandas as pdfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import RegexpTokenizerfrom nltk.corpus import stopwordsfrom sklearn.feature_extraction.text import TfidfVectorizer# Create a dataframeX_train = pd.DataFrame({'text': [d1, d2]})" }, { "code": null, "e": 2935, "s": 2751, "text": "From now on, we will refer ‘X_train’ as our corpus (despite its size) and two sentences as documents. Second, we will need a text processing function to pass it on to TfidfVectorizer:" }, { "code": null, "e": 3363, "s": 2935, "text": "def preprocess_text(text): # Tokenise words while ignoring punctuation tokeniser = RegexpTokenizer(r'\\w+') tokens = tokeniser.tokenize(text) # Lowercase and lemmatise lemmatiser = WordNetLemmatizer() lemmas = [lemmatiser.lemmatize(token.lower(), pos='v') for token in tokens] # Remove stopwords keywords= [lemma for lemma in lemmas if lemma not in stopwords.words('english')] return keywords" }, { "code": null, "e": 3514, "s": 3363, "text": "🔗 I have explained this function in detail in the first part of the series if you need explanation. This preprocessor will transform the documents to:" }, { "code": null, "e": 3605, "s": 3514, "text": "d1 = [‘think’, ‘think’, ‘think’, ‘thank’, ‘gift’]d2 = [‘think’, ‘go’, ‘go’, ‘get’, ‘gift’]" }, { "code": null, "e": 3636, "s": 3605, "text": "Lastly, preprocess the corpus:" }, { "code": null, "e": 4160, "s": 3636, "text": "# Create an instance of TfidfVectorizervectoriser = TfidfVectorizer(analyzer=preprocess_text)# Fit to the data and transform to feature matrixX_train = vectoriser.fit_transform(X_train['text'])# Convert sparse matrix to dataframeX_train = pd.DataFrame.sparse.from_spmatrix(X_train)# Save mapping on which index refers to which wordscol_map = {v:k for k, v in vectoriser.vocabulary_.items()}# Rename each column using the mappingfor col in X_train.columns: X_train.rename(columns={col: col_map[col]}, inplace=True)X_train" }, { "code": null, "e": 4210, "s": 4160, "text": "Once the script is run, you will get this output:" }, { "code": null, "e": 4334, "s": 4210, "text": "Tada❕ We have vectorised the corpus to tf-idf! The data is now in a format that is acceptable for a machine learning model." }, { "code": null, "e": 4409, "s": 4334, "text": "Let’s see how test documents with or without unseen terms get transformed:" }, { "code": null, "e": 4827, "s": 4409, "text": "d3 = “He thinks he will go!”d4 = “They don’t know what to buy!”# Create dataframeX_test = pd.DataFrame({‘text’: [d3, d4]})# Transform to feature matrixX_test = vectoriser.transform(X_test['text'])# Convert sparse matrix to dataframeX_test = pd.DataFrame.sparse.from_spmatrix(X_test)# Add column names to make it more readiblefor col in X_test.columns: X_test.rename(columns={col: col_map[col]}, inplace=True)X_test" }, { "code": null, "e": 4900, "s": 4827, "text": "When preprocess_text is applied, the test documents will transform into:" }, { "code": null, "e": 5033, "s": 4900, "text": "d3 = [‘think’, 'go'] # vectoritiser is familiar with these termsd4 = [‘know’, ‘buy’] # vectoritiser is not familiar with these terms" }, { "code": null, "e": 5410, "s": 5033, "text": "Is this what you expected to see when X_test is transformed? Although we have one occurrence of ‘go’ and ‘think’ in d3, do you notice how ‘go’ have been weighted up relative to ‘think’? Does the fact that d4 takes all 0 values make sense to you? Do you notice the number of terms in the matrix is dependent on training data much like any other sklearn transformers in general?" }, { "code": null, "e": 5559, "s": 5410, "text": "I think things get more interesting when we start looking under the hood. In this section, we will do the transformation manually, isn’t that fun? 😍" }, { "code": null, "e": 5833, "s": 5559, "text": "If you enjoy math, I encourage you to manually calculate problems alongside this guide, or better yet, try to calculate it on your own before proceeding to the answers that follow. In the examples below, rows represent either document or corpus and columns represent terms." }, { "code": null, "e": 5896, "s": 5833, "text": "🔒 Problem: Count raw term frequency for each term by document." }, { "code": null, "e": 5961, "s": 5896, "text": "💭 Hint: Look at preprocessed d1 and d2 and definition of tf_raw." }, { "code": null, "e": 5971, "s": 5961, "text": "🔑 Answer:" }, { "code": null, "e": 6275, "s": 5971, "text": "This table summarises the number of times each term occurs in a document. For instance: We see 3 occurrences of ‘think’ in document 1 but only once in document 2. The number of columns are determined by the number of unique terms in the corpus. This step is actually what sklearn’s CountVectoriser does." }, { "code": null, "e": 6332, "s": 6275, "text": "(This step is only to compare the final output against.)" }, { "code": null, "e": 6395, "s": 6332, "text": "🔒 Problem: Calculate term frequency for each term by document." }, { "code": null, "e": 6464, "s": 6395, "text": "💭 Hint: What proportion does a term represent in a document? (Row %)" }, { "code": null, "e": 6474, "s": 6464, "text": "🔑 Answer:" }, { "code": null, "e": 6529, "s": 6474, "text": "The term ‘think’ takes 60% of the terms in document 1." }, { "code": null, "e": 6580, "s": 6529, "text": "🔒 Problem: Count document frequency for each term." }, { "code": null, "e": 6636, "s": 6580, "text": "💭 Hint: How many documents contain the particular term?" }, { "code": null, "e": 6646, "s": 6636, "text": "🔑 Answer:" }, { "code": null, "e": 6736, "s": 6646, "text": "The term ‘get’ is present in document 1 only while the term ‘think’ is in both documents." }, { "code": null, "e": 6848, "s": 6736, "text": "Now, this is where the first calculation happens. ➗ Formula: In this formula, n stands for number of documents." }, { "code": null, "e": 6888, "s": 6848, "text": "🔒 Problem: Calculate idf for each term." }, { "code": null, "e": 6943, "s": 6888, "text": "🔑 Answer: Doesn’t idf look somewhat inverse to the df?" }, { "code": null, "e": 7018, "s": 6943, "text": "In sklearn, you can access idf_ attribute from the fitted TfidfVectorizer." }, { "code": null, "e": 7169, "s": 7018, "text": "🔍 Example calculation: Below, I have provided an example calculation. You can use it as a guide for the remaining terms by replicating the same logic:" }, { "code": null, "e": 7180, "s": 7169, "text": "➗ Formula:" }, { "code": null, "e": 7262, "s": 7180, "text": "🔒 Problem: Calculate raw tf-idf (i.e. weighted counts) for each term by document." }, { "code": null, "e": 7272, "s": 7262, "text": "🔑 Answer:" }, { "code": null, "e": 7295, "s": 7272, "text": "🔍 Example calculation:" }, { "code": null, "e": 7306, "s": 7295, "text": "➗ Formula:" }, { "code": null, "e": 7361, "s": 7306, "text": "🔒 Problem: Calculate tf-idf for each term by document." }, { "code": null, "e": 7371, "s": 7361, "text": "🔑 Answer:" }, { "code": null, "e": 7394, "s": 7371, "text": "🔍 Example calculation:" }, { "code": null, "e": 7593, "s": 7394, "text": "Yay❕ We have obtained the exact same results! Of note, if you had rounded off anywhere in the interim steps, your final answer may not match precisely with that provided above due to rounding error." }, { "code": null, "e": 7713, "s": 7593, "text": "📌 Exercise: See if you can calculate tf-idf for d3 and d4, and match it to the output from sklearn in previous section." }, { "code": null, "e": 7910, "s": 7713, "text": "💭 Hint: (1) Count tf_raw - terms refer to the terms from training data, (2) Calculate tf-idf_raw using the idf we have built, (3) Calculate tf-idf. Do these steps only for the terms from training." }, { "code": null, "e": 8155, "s": 7910, "text": "This method replicates output when smooth_idf=True for TfidfVectorizer or TfidfTransformer in sklearn. If you change this parameter to False, you will have to adjust the idf formula slightly by taking out +1 from both numerator and denominator." }, { "code": null, "e": 8217, "s": 8155, "text": "Before we wrap up, let’s compare tf vs tf-idf for document 1:" }, { "code": null, "e": 8567, "s": 8217, "text": "Since ‘gift’ and ‘think’ are present in all documents, their relative weight is identical in both tables. However, ‘thank’ is only in document 1, so its relative frequency is higher in tf-idf when compared to ‘gift’ or ‘think’. As such, this demonstrates how tf-idf upweights terms that are in fewer documents and downweights those that are in more." }, { "code": null, "e": 8611, "s": 8567, "text": "📌 Exercise: Analyse document 2 on your own." }, { "code": null, "e": 9223, "s": 8611, "text": "Obviously, manual calculation is more prone to error and not likely to scale well to real corpus with hundreds, thousands or even millions of documents. Many thanks to sklearn contributors for providing such an efficient way to transform text to tf-idf in a just few lines of code. The manual calculations shown here was only to exemplify the underlying implementation when using a software. If you want to replicate outputs yourself from tools other than sklearn, an adjustment to the formulas may be necessary, but the overall idea should be similar. I hope these explanations have been useful and insightful." }, { "code": null, "e": 9447, "s": 9223, "text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me." }, { "code": null, "e": 9894, "s": 9447, "text": "Thank you for taking the time to go through this post. I hope that you learned something from reading it. Links to the rest of the posts are collated below:◼️ Part 1: Preprocessing text in Python◼️ Part 2: Difference between lemmatisation and stemming◼️ Part 3: TF-IDF explained◼️ Part 4: Supervised text classification model in Python◼️ Part 5A: Unsupervised topic model in Python (sklearn)◼️ Part 5B: Unsupervised topic model in Python (gensim)" }, { "code": null, "e": 9929, "s": 9894, "text": "Happy transforming! Bye for now 🏃💨" }, { "code": null, "e": 10038, "s": 9929, "text": "Bird, Steven, Edward Loper and Ewan Klein, Natural Language Processing with Python. O’Reilly Media Inc, 2009" } ]
C# program to convert string to long
To convert a string to a long, use the Long.parse method in C# − Firstly, set a string − string str = "6987646475767"; Now, convert it to long − long.Parse(str); Here is the complete code − Live Demo using System; using System.Linq; class Demo { static void Main() { string str = "6987646475767"; long res = long.Parse(str); Console.WriteLine(res); } } 6987646475767
[ { "code": null, "e": 1127, "s": 1062, "text": "To convert a string to a long, use the Long.parse method in C# −" }, { "code": null, "e": 1151, "s": 1127, "text": "Firstly, set a string −" }, { "code": null, "e": 1181, "s": 1151, "text": "string str = \"6987646475767\";" }, { "code": null, "e": 1207, "s": 1181, "text": "Now, convert it to long −" }, { "code": null, "e": 1224, "s": 1207, "text": "long.Parse(str);" }, { "code": null, "e": 1252, "s": 1224, "text": "Here is the complete code −" }, { "code": null, "e": 1263, "s": 1252, "text": " Live Demo" }, { "code": null, "e": 1440, "s": 1263, "text": "using System;\nusing System.Linq;\nclass Demo {\n static void Main() {\n string str = \"6987646475767\";\n long res = long.Parse(str);\n Console.WriteLine(res);\n }\n}" }, { "code": null, "e": 1454, "s": 1440, "text": "6987646475767" } ]
Basics of Discrete Event Simulation using SimPy in Python
SimPy (rhymes with “Blimpie”) is a python package for process-oriented discrete-event simulation. The easiest way to install SimPy is via pip: pip install simpy And the output you may get will be something like, At the time of writing, simpy-3.0.11 is the most recent version of SimPy, and we will use it for all the below examples. In case, SimPy is already installed, use the –U option for pip to upgrade. pip install –U simpy Note: You need to have python 2.7 or above version and for Linux/Unix/MacOS you may need root privileges to install SimPy. To check if SimPy was successfully installed, open a python shell and import simpy. SimPy, which is a discrete-event simulation library. The active components of simpy (like messages, vehicles or customers) are modeled with processes. In SimPy, active entities are known as processes. A process is a Python generator that yields discrete events. Please note, I’m not returning anything but I’m a yield(ing), that is the difference between a normal function and a generator. This allows us to create events and yield them in order to wait for them to be triggered. When a process yields an event, the process gets suspended. SimPy allows us to resume the suspended process whenever the event is triggered. In case, multiple processes wait for the same event, SimPy resumes them in the same order in which they yielded that event. def gen(x): y = yield x+1 return y >>> g = gen(1) >>> next(g) 2 >>> next(g) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> next(g) StopIteration Above Iteration stops after variable x first yield. Events of Timeout type are triggered after a certain amount of (simulated) time has passed. Timeout event allows a process to hold or sleep for a certain amount of time. All the events including Timeout can be created by calling the appropriate method of the Environment that the process lives in. #Import important library from random import randint import simpy #Config TALKS_PER_SESSION = 3 TALK_LENGTH = 30 BREAK_LENGTH = 15 ATTENDEES = 1 def attendee(env, name, knowledge=0, hunger=0): talks =0 breaks =0 #Repeat sessions while True: # Visit talks for i in range(TALKS_PER_SESSION): print('Talk {0} begins at {1}'.format(talks+1, env.now)) knowledge += randint(0, 3) / (1 + hunger) hunger += randint(1, 4) talks += 1 yield env.timeout(TALK_LENGTH) print(f'Talk {talks} ends at {env.now}') print('Attendee %s finished talks with knowledge %.2f and hunger ' '%.2f' %( name, knowledge, hunger)) #Take a break, Go to buffet food = randint(3, 12) hunger -= min(food, hunger) yield env.timeout(BREAK_LENGTH) print('Attendee %s finished eating with hunger %.2f ' %(name, hunger)) # Run Simulation env = simpy.Environment() for i in range(ATTENDEES): env.process(attendee(env, i)) env.run(until=250) If we run the above program, we’ll see the output something like, Above we try to replicate the conference hall scenario, where there is a random number of speakers with talks per session of 4 with talk length of 40 min and break the length of 30 min. Our attendee process requires a reference to an Environment (env), name, knowledge, and hunger in order to create new events. Sessions will go in an infinite loop till it becomes False. The attendee() function is a generator which will not terminate but will pass the control flow back to the simulation once a yield statement is reached. At last, we run a demo simulation 'conference attendee" until a set value of 250 is not reached (includes- 3 talks, 1 break, 3 talks, 1 break, 1 talk).
[ { "code": null, "e": 1160, "s": 1062, "text": "SimPy (rhymes with “Blimpie”) is a python package for process-oriented discrete-event simulation." }, { "code": null, "e": 1205, "s": 1160, "text": "The easiest way to install SimPy is via pip:" }, { "code": null, "e": 1223, "s": 1205, "text": "pip install simpy" }, { "code": null, "e": 1274, "s": 1223, "text": "And the output you may get will be something like," }, { "code": null, "e": 1395, "s": 1274, "text": "At the time of writing, simpy-3.0.11 is the most recent version of SimPy, and we will use it for all the below examples." }, { "code": null, "e": 1470, "s": 1395, "text": "In case, SimPy is already installed, use the –U option for pip to upgrade." }, { "code": null, "e": 1491, "s": 1470, "text": "pip install –U simpy" }, { "code": null, "e": 1614, "s": 1491, "text": "Note: You need to have python 2.7 or above version and for Linux/Unix/MacOS you may need root privileges to install SimPy." }, { "code": null, "e": 1698, "s": 1614, "text": "To check if SimPy was successfully installed, open a python shell and import simpy." }, { "code": null, "e": 2178, "s": 1698, "text": "SimPy, which is a discrete-event simulation library. The active components of simpy (like messages, vehicles or customers) are modeled with processes. In SimPy, active entities are known as processes. A process is a Python generator that yields discrete events. Please note, I’m not returning anything but I’m a yield(ing), that is the difference between a normal function and a generator. This allows us to create events and yield them in order to wait for them to be triggered." }, { "code": null, "e": 2443, "s": 2178, "text": "When a process yields an event, the process gets suspended. SimPy allows us to resume the suspended process whenever the event is triggered. In case, multiple processes wait for the same event, SimPy resumes them in the same order in which they yielded that event." }, { "code": null, "e": 2478, "s": 2443, "text": "def gen(x):\ny = yield x+1\nreturn y" }, { "code": null, "e": 2616, "s": 2478, "text": ">>> g = gen(1)\n>>> next(g)\n2\n>>> next(g)\nTraceback (most recent call last):\nFile \"<pyshell#2>\", line 1, in <module>\nnext(g)\nStopIteration" }, { "code": null, "e": 2668, "s": 2616, "text": "Above Iteration stops after variable x first yield." }, { "code": null, "e": 2966, "s": 2668, "text": "Events of Timeout type are triggered after a certain amount of (simulated) time has passed. Timeout event allows a process to hold or sleep for a certain amount of time. All the events including Timeout can be created by calling the appropriate method of the Environment that the process lives in." }, { "code": null, "e": 3946, "s": 2966, "text": "#Import important library\nfrom random import randint\nimport simpy\n#Config\nTALKS_PER_SESSION = 3\nTALK_LENGTH = 30\nBREAK_LENGTH = 15\nATTENDEES = 1\ndef attendee(env, name, knowledge=0, hunger=0):\n talks =0\n breaks =0\n #Repeat sessions\n while True:\n # Visit talks\n for i in range(TALKS_PER_SESSION):\n print('Talk {0} begins at {1}'.format(talks+1, env.now))\n knowledge += randint(0, 3) / (1 + hunger)\n hunger += randint(1, 4)\n talks += 1\n yield env.timeout(TALK_LENGTH)\n print(f'Talk {talks} ends at {env.now}')\n print('Attendee %s finished talks with knowledge %.2f and hunger ' '%.2f' %( name, knowledge, hunger))\n #Take a break, Go to buffet\n food = randint(3, 12)\n hunger -= min(food, hunger)\n yield env.timeout(BREAK_LENGTH)\n print('Attendee %s finished eating with hunger %.2f ' %(name, hunger))\n# Run Simulation\nenv = simpy.Environment()\nfor i in range(ATTENDEES):\n env.process(attendee(env, i))\nenv.run(until=250)" }, { "code": null, "e": 4012, "s": 3946, "text": "If we run the above program, we’ll see the output something like," }, { "code": null, "e": 4198, "s": 4012, "text": "Above we try to replicate the conference hall scenario, where there is a random number of speakers with talks per session of 4 with talk length of 40 min and break the length of 30 min." }, { "code": null, "e": 4537, "s": 4198, "text": "Our attendee process requires a reference to an Environment (env), name, knowledge, and hunger in order to create new events. Sessions will go in an infinite loop till it becomes False. The attendee() function is a generator which will not terminate but will pass the control flow back to the simulation once a yield statement is reached." }, { "code": null, "e": 4689, "s": 4537, "text": "At last, we run a demo simulation 'conference attendee\" until a set value of 250 is not reached (includes- 3 talks, 1 break, 3 talks, 1 break, 1 talk)." } ]
Cocke–Younger–Kasami (CYK) Algorithm
22 Jun, 2022 Grammar denotes the syntactical rules for conversation in natural language. But in the theory of formal language, grammar is defined as a set of rules that can generate strings. The set of all strings that can be generated from a grammar is called the language of the grammar. Context Free Grammar: We are given a Context Free Grammar G = (V, X, R, S) and a string w, where: V is a finite set of variables or non-terminal symbols, X is a finite set of terminal symbols, R is a finite set of rules, S is the start symbol, a distinct element of V, and V and X are assumed to be disjoint sets. The Membership problem is defined as: Grammar G generates a language L(G). Is the given string a member of L(G)? Chomsky Normal Form: A Context Free Grammar G is in Chomsky Normal Form (CNF) if each rule if each rule of G is of the form: A –> BC, [ with at most two non-terminal symbols on the RHS ] A –> a, or [ one terminal symbol on the RHS ] S –> nullstring, [ null string ] Cocke-Younger-Kasami Algorithm It is used to solves the membership problem using a dynamic programming approach. The algorithm is based on the principle that the solution to problem [i, j] can constructed from solution to subproblem [i, k] and solution to sub problem [k, j]. The algorithm requires the Grammar G to be in Chomsky Normal Form (CNF). Note that any Context-Free Grammar can be systematically converted to CNF. This restriction is employed so that each problem can only be divided into two subproblems and not more – to bound the time complexity. How does the CYK Algorithm work? For a string of length N, construct a table T of size N x N. Each cell in the table T[i, j] is the set of all constituents that can produce the substring spanning from position i to j. The process involves filling the table with the solutions to the subproblems encountered in the bottom-up parsing process. Therefore, cells will be filled from left to right and bottom to top. 1 2 3 4 5 In T[i, j], the row number i denotes the start index and the column number j denotes the end index. The algorithm considers every possible subsequence of letters and adds K to T[i, j] if the sequence of letters starting from i to j can be generated from the non-terminal K. For subsequences of length 2 and greater, it considers every possible partition of the subsequence into two parts, and checks if there is a rule of the form A ? BC in the grammar where B and C can generate the two parts respectively, based on already existing entries in T. The sentence can be produced by the grammar only if the entire string is matched by the start symbol, i.e, if S is a member of T[1, n]. Consider a sample grammar in Chomsky Normal Form: NP --> Det | Nom Nom --> AP | Nom AP --> Adv | A Det --> a | an Adv --> very | extremely AP --> heavy | orange | tall A --> heavy | orange | tall | muscular Nom --> book | orange | man Now consider the phrase, “a very heavy orange book“: a(1) very(2) heavy (3) orange(4) book(5) Let us start filling up the table from left to right and bottom to top, according to the rules described above: 1a 2very 3heavy 4orange 5book 1a Det – – NP NP 2very Adv AP Nom Nom 3heavy A, AP Nom Nom 4orange Nom 5book Nom The table is filled in the following manner: T[1, 1] = {Det} as Det –> a is one of the rules of the grammar.T[2, 2] = {Adv} as Adv –> very is one of the rules of the grammar.T[1, 2] = {} as no matching rule is observed.T[3, 3] = {A, AP} as A –> very and AP –> very are rules of the grammar.T[2, 3] = {AP} as AP –> Adv (T[2, 2]) A (T[3, 3]) is a rule of the grammar.T[1, 3] = {} as no matching rule is observed.T[4, 4] = {Nom, A, AP} as Nom –> orange and A –> orange and AP –> orange are rules of the grammar.T[3, 4] = {Nom} as Nom –> AP (T[3, 3]) Nom (T[3, 4]) is a rule of the grammar.T[2, 4] = {Nom} as Nom –> AP (T[2, 3]) Nom (T[4, 4]) is a rule of the grammar.T[1, 4] = {NP} as NP –> Det (T[1, 1]) Nom (T[2, 4]) is a rule of the grammar.T[5, 5] = {Nom} as Nom –> book is a rule of the grammar.T[4, 5] = {Nom} as Nom –> AP (T[4, 4]) Nom (T[5, 5]) is a rule of the grammar.T[3, 5] = {Nom} as Nom –> AP (T[3, 3]) Nom (T[4, 5]) is a rule of the grammar.T[2, 5] = {Nom} as Nom –> AP (T[2, 3]) Nom (T[4, 5]) is a rule of the grammar.T[1, 5] = {NP} as NP –> Det (T[1, 1]) Nom (T[2, 5]) is a rule of the grammar. T[1, 1] = {Det} as Det –> a is one of the rules of the grammar. T[2, 2] = {Adv} as Adv –> very is one of the rules of the grammar. T[1, 2] = {} as no matching rule is observed. T[3, 3] = {A, AP} as A –> very and AP –> very are rules of the grammar. T[2, 3] = {AP} as AP –> Adv (T[2, 2]) A (T[3, 3]) is a rule of the grammar. T[1, 3] = {} as no matching rule is observed. T[4, 4] = {Nom, A, AP} as Nom –> orange and A –> orange and AP –> orange are rules of the grammar. T[3, 4] = {Nom} as Nom –> AP (T[3, 3]) Nom (T[3, 4]) is a rule of the grammar. T[2, 4] = {Nom} as Nom –> AP (T[2, 3]) Nom (T[4, 4]) is a rule of the grammar. T[1, 4] = {NP} as NP –> Det (T[1, 1]) Nom (T[2, 4]) is a rule of the grammar. T[5, 5] = {Nom} as Nom –> book is a rule of the grammar. T[4, 5] = {Nom} as Nom –> AP (T[4, 4]) Nom (T[5, 5]) is a rule of the grammar. T[3, 5] = {Nom} as Nom –> AP (T[3, 3]) Nom (T[4, 5]) is a rule of the grammar. T[2, 5] = {Nom} as Nom –> AP (T[2, 3]) Nom (T[4, 5]) is a rule of the grammar. T[1, 5] = {NP} as NP –> Det (T[1, 1]) Nom (T[2, 5]) is a rule of the grammar. We see that T[1][5] has NP, the start symbol, which means that this phrase is a member of the language of the grammar G. The parse tree of this phrase would look like this: Let us look at another example phrase, “a very tall extremely muscular man”: a(1) very(2) tall(3) extremely(4) muscular(5) man(6) We will now use the CYK algorithm to find if this string is a member of the grammar G: 1a 2very 3tall 4extremely 5muscular 6man 1a Det – – – – 2very Adv AP – – 3tall AP, A – – Nom 4extremely Adv AP Nom 5muscular A – 6man Nom We see that T[1][6] has NP, the start symbol, which means that this phrase is a member of the language of the grammar G. Below is the implementation of the above algorithm: C++ Python3 C# // C++ implementation for the// CYK Algorithm #include<bits/stdc++.h>using namespace std; // Non-terminals symbolsvector<string> terminals,non_terminals; // Rules of the grammarunordered_map<string,vector<vector<string>>> R; // function to perform the CYK Algorithmvoid cykParse(vector<string> w){ int n = (int)w.size(); // Initialize the table map<int,map<int,set<string>>> T; // Filling in the table for(int j=0;j<n;j++) { // Iterate over the rules for(auto x:R) { string lhs = x.first; vector<vector<string>> rule = x.second; for(auto rhs:rule) { // If a terminal is found if(rhs.size() == 1 && rhs[0] == w[j]) T[j][j].insert(lhs); } } for(int i=j;i>=0;i--) { // Iterate over the range from i to j for(int k = i;k<=j;k++) { // Iterate over the rules for(auto x:R) { string lhs = x.first; vector<vector<string>> rule = x.second; for(auto rhs:rule) { // If a terminal is found if(rhs.size()==2 && T[i][k].find(rhs[0])!=T[i][k].end() && T[k+1][j].find(rhs[1])!=T[k+1][j].end()) T[i][j].insert(lhs); } } } } } // If word can be formed by rules // of given grammar if(T[0][n-1].size()!=0) cout << "True\n"; else cout << "False\n";} // Driver Codeint main(){ // terminal symbols terminals = {"book", "orange", "man", "tall", "heavy", "very", "muscular"}; // non terminal symbols non_terminals = {"NP", "Nom", "Det", "AP", "Adv", "A"}; // Rules R["NP"]={{"Det", "Nom"}}; R["Nom"]= {{"AP", "Nom"}, {"book"}, {"orange"}, {"man"}}; R["AP"] = {{"Adv", "A"}, {"heavy"}, {"orange"}, {"tall"}}; R["Det"] = {{"a"}}; R["Adv"] = {{"very"}, {"extremely"}}; R["A"] = {{"heavy"}, {"orange"}, {"tall"}, {"muscular"}}; // Given String vector<string> w = {"a", "very", "heavy", "orange", "book"}; // Function Call cykParse(w); return 0;} # Python implementation for the# CYK Algorithm # Non-terminal symbolsnon_terminals = ["NP", "Nom", "Det", "AP", "Adv", "A"]terminals = ["book", "orange", "man", "tall", "heavy", "very", "muscular"] # Rules of the grammarR = { "NP": [["Det", "Nom"]], "Nom": [["AP", "Nom"], ["book"], ["orange"], ["man"]], "AP": [["Adv", "A"], ["heavy"], ["orange"], ["tall"]], "Det": [["a"]], "Adv": [["very"], ["extremely"]], "A": [["heavy"], ["orange"], ["tall"], ["muscular"]] } # Function to perform the CYK Algorithmdef cykParse(w): n = len(w) # Initialize the table T = [[set([]) for j in range(n)] for i in range(n)] # Filling in the table for j in range(0, n): # Iterate over the rules for lhs, rule in R.items(): for rhs in rule: # If a terminal is found if len(rhs) == 1 and \ rhs[0] == w[j]: T[j][j].add(lhs) for i in range(j, -1, -1): # Iterate over the range i to j + 1 for k in range(i, j + 1): # Iterate over the rules for lhs, rule in R.items(): for rhs in rule: # If a terminal is found if len(rhs) == 2 and \ rhs[0] in T[i][k] and \ rhs[1] in T[k + 1][j]: T[i][j].add(lhs) # If word can be formed by rules # of given grammar if len(T[0][n-1]) != 0: print("True") else: print("False") # Driver Code # Given stringw = "a very heavy orange book".split() # Function CallcykParse(w) // C# program to implement above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // terminal and Non-terminals symbols // static List<string> terminals = new List<string>(); // static List<string> non_terminals = new List<string>(); // Rules of the grammar static Dictionary<string,List<List<string>>> R = new Dictionary<string,List<List<string>>>(); // function to perform the CYK Algorithm static void cykParse(List<string> w) { int n = w.Count; // Initialize the table SortedDictionary<int, SortedDictionary<int, SortedSet<string>>> T = new SortedDictionary<int, SortedDictionary<int, SortedSet<string>>>(); // Filling in the table for (int j = 0 ; j < n ; j++) { // Iterate over the rules foreach (KeyValuePair<string,List<List<string>>> x in R) { string lhs = x.Key; List<List<string>> rule = x.Value; foreach (List<string> rhs in rule) { // If a terminal is found if(rhs.Count == 1 && rhs[0] == w[j]){ if(!T.ContainsKey(j)){ T.Add(j, new SortedDictionary<int, SortedSet<string>>()); } if(!T[j].ContainsKey(j)){ T[j].Add(j, new SortedSet<string>()); } T[j][j].Add(lhs); } } } for(int i = j ; i >= 0 ; i--) { // Iterate over the range from i to j for(int k = i ; k <= j ; k++) { // Iterate over the rules foreach (KeyValuePair<string,List<List<string>>> x in R) { string lhs = x.Key; List<List<string>> rule = x.Value; foreach (List<string> rhs in rule) { // If a terminal is found if(rhs.Count == 2 && T.ContainsKey(i) && T[i].ContainsKey(k) && T[i][k].Contains(rhs[0]) && T.ContainsKey(k + 1) && T[k + 1].ContainsKey(j) && T[k + 1][j].Contains(rhs[1])) { if(!T.ContainsKey(i)){ T.Add(i, new SortedDictionary<int, SortedSet<string>>()); } if(!T[i].ContainsKey(j)){ T[i].Add(j, new SortedSet<string>()); } T[i][j].Add(lhs); } } } } } } // If word can be formed by rules // of given grammar if(T.ContainsKey(0) && T[0].ContainsKey(n - 1) && T[0][n - 1].Count != 0){ Console.Write("True\n"); }else{ Console.Write("False\n"); } } // Driver code public static void Main(string[] args){ // terminal symbols // terminals = new List<string>{ // "book", // "orange", "man", // "tall", "heavy", // "very", "muscular" // }; // non terminal symbols // non_terminals = new List<string>{ // "NP", "Nom", "Det", // "AP", "Adv", "A" // }; // Rules R.Add("NP", new List<List<string>>{ new List<string>{"Det", "Nom"} }); R["Nom"]= new List<List<string>>{ new List<string>{"AP", "Nom"}, new List<string>{"book"}, new List<string>{"orange"}, new List<string>{"man"} }; R["AP"] = new List<List<string>>{ new List<string>{"Adv", "A"}, new List<string>{"heavy"}, new List<string>{"orange"}, new List<string>{"tall"} }; R["Det"] = new List<List<string>>{ new List<string>{"a"} }; R["Adv"] = new List<List<string>>{ new List<string>{"very"}, new List<string>{"extremely"} }; R["A"] = new List<List<string>>{ new List<string>{"heavy"}, new List<string>{"orange"}, new List<string>{"tall"}, new List<string>{"muscular"} }; // Given String List<string> w = new List<string>{"a", "very", "heavy", "orange", "book"}; // Function Call cykParse(w); }} // This code is contributed by subhamgoyal2014. True Time Complexity: O(N3) Auxiliary Space:O(N2) ashutoshsinghgeeksforgeeks subhamgoyal2014 Algorithms Compiler Design Dynamic Programming Dynamic Programming Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 305, "s": 28, "text": "Grammar denotes the syntactical rules for conversation in natural language. But in the theory of formal language, grammar is defined as a set of rules that can generate strings. The set of all strings that can be generated from a grammar is called the language of the grammar." }, { "code": null, "e": 403, "s": 305, "text": "Context Free Grammar: We are given a Context Free Grammar G = (V, X, R, S) and a string w, where:" }, { "code": null, "e": 459, "s": 403, "text": "V is a finite set of variables or non-terminal symbols," }, { "code": null, "e": 498, "s": 459, "text": "X is a finite set of terminal symbols," }, { "code": null, "e": 526, "s": 498, "text": "R is a finite set of rules," }, { "code": null, "e": 578, "s": 526, "text": "S is the start symbol, a distinct element of V, and" }, { "code": null, "e": 619, "s": 578, "text": "V and X are assumed to be disjoint sets." }, { "code": null, "e": 732, "s": 619, "text": "The Membership problem is defined as: Grammar G generates a language L(G). Is the given string a member of L(G)?" }, { "code": null, "e": 857, "s": 732, "text": "Chomsky Normal Form: A Context Free Grammar G is in Chomsky Normal Form (CNF) if each rule if each rule of G is of the form:" }, { "code": null, "e": 926, "s": 857, "text": "A –> BC, [ with at most two non-terminal symbols on the RHS ]" }, { "code": null, "e": 977, "s": 926, "text": "A –> a, or [ one terminal symbol on the RHS ]" }, { "code": null, "e": 1022, "s": 977, "text": "S –> nullstring, [ null string ]" }, { "code": null, "e": 1583, "s": 1022, "text": "Cocke-Younger-Kasami Algorithm It is used to solves the membership problem using a dynamic programming approach. The algorithm is based on the principle that the solution to problem [i, j] can constructed from solution to subproblem [i, k] and solution to sub problem [k, j]. The algorithm requires the Grammar G to be in Chomsky Normal Form (CNF). Note that any Context-Free Grammar can be systematically converted to CNF. This restriction is employed so that each problem can only be divided into two subproblems and not more – to bound the time complexity. " }, { "code": null, "e": 1616, "s": 1583, "text": "How does the CYK Algorithm work?" }, { "code": null, "e": 1994, "s": 1616, "text": "For a string of length N, construct a table T of size N x N. Each cell in the table T[i, j] is the set of all constituents that can produce the substring spanning from position i to j. The process involves filling the table with the solutions to the subproblems encountered in the bottom-up parsing process. Therefore, cells will be filled from left to right and bottom to top." }, { "code": null, "e": 1996, "s": 1994, "text": "1" }, { "code": null, "e": 1998, "s": 1996, "text": "2" }, { "code": null, "e": 2000, "s": 1998, "text": "3" }, { "code": null, "e": 2002, "s": 2000, "text": "4" }, { "code": null, "e": 2004, "s": 2002, "text": "5" }, { "code": null, "e": 2104, "s": 2004, "text": "In T[i, j], the row number i denotes the start index and the column number j denotes the end index." }, { "code": null, "e": 2691, "s": 2106, "text": "The algorithm considers every possible subsequence of letters and adds K to T[i, j] if the sequence of letters starting from i to j can be generated from the non-terminal K. For subsequences of length 2 and greater, it considers every possible partition of the subsequence into two parts, and checks if there is a rule of the form A ? BC in the grammar where B and C can generate the two parts respectively, based on already existing entries in T. The sentence can be produced by the grammar only if the entire string is matched by the start symbol, i.e, if S is a member of T[1, n]." }, { "code": null, "e": 2743, "s": 2693, "text": "Consider a sample grammar in Chomsky Normal Form:" }, { "code": null, "e": 2948, "s": 2745, "text": "NP --> Det | Nom\nNom --> AP | Nom\nAP --> Adv | A\nDet --> a | an\nAdv --> very | extremely\nAP --> heavy | orange | tall\nA --> heavy | orange | tall | muscular\nNom --> book | orange | man" }, { "code": null, "e": 3003, "s": 2950, "text": "Now consider the phrase, “a very heavy orange book“:" }, { "code": null, "e": 3046, "s": 3005, "text": "a(1) very(2) heavy (3) orange(4) book(5)" }, { "code": null, "e": 3160, "s": 3048, "text": "Let us start filling up the table from left to right and bottom to top, according to the rules described above:" }, { "code": null, "e": 3165, "s": 3162, "text": "1a" }, { "code": null, "e": 3171, "s": 3165, "text": "2very" }, { "code": null, "e": 3178, "s": 3171, "text": "3heavy" }, { "code": null, "e": 3186, "s": 3178, "text": "4orange" }, { "code": null, "e": 3192, "s": 3186, "text": "5book" }, { "code": null, "e": 3195, "s": 3192, "text": "1a" }, { "code": null, "e": 3199, "s": 3195, "text": "Det" }, { "code": null, "e": 3201, "s": 3199, "text": "–" }, { "code": null, "e": 3203, "s": 3201, "text": "–" }, { "code": null, "e": 3206, "s": 3203, "text": "NP" }, { "code": null, "e": 3209, "s": 3206, "text": "NP" }, { "code": null, "e": 3215, "s": 3209, "text": "2very" }, { "code": null, "e": 3219, "s": 3215, "text": "Adv" }, { "code": null, "e": 3222, "s": 3219, "text": "AP" }, { "code": null, "e": 3226, "s": 3222, "text": "Nom" }, { "code": null, "e": 3230, "s": 3226, "text": "Nom" }, { "code": null, "e": 3237, "s": 3230, "text": "3heavy" }, { "code": null, "e": 3243, "s": 3237, "text": "A, AP" }, { "code": null, "e": 3247, "s": 3243, "text": "Nom" }, { "code": null, "e": 3251, "s": 3247, "text": "Nom" }, { "code": null, "e": 3259, "s": 3251, "text": "4orange" }, { "code": null, "e": 3263, "s": 3259, "text": "Nom" }, { "code": null, "e": 3269, "s": 3263, "text": "5book" }, { "code": null, "e": 3273, "s": 3269, "text": "Nom" }, { "code": null, "e": 3320, "s": 3275, "text": "The table is filled in the following manner:" }, { "code": null, "e": 4386, "s": 3322, "text": "T[1, 1] = {Det} as Det –> a is one of the rules of the grammar.T[2, 2] = {Adv} as Adv –> very is one of the rules of the grammar.T[1, 2] = {} as no matching rule is observed.T[3, 3] = {A, AP} as A –> very and AP –> very are rules of the grammar.T[2, 3] = {AP} as AP –> Adv (T[2, 2]) A (T[3, 3]) is a rule of the grammar.T[1, 3] = {} as no matching rule is observed.T[4, 4] = {Nom, A, AP} as Nom –> orange and A –> orange and AP –> orange are rules of the grammar.T[3, 4] = {Nom} as Nom –> AP (T[3, 3]) Nom (T[3, 4]) is a rule of the grammar.T[2, 4] = {Nom} as Nom –> AP (T[2, 3]) Nom (T[4, 4]) is a rule of the grammar.T[1, 4] = {NP} as NP –> Det (T[1, 1]) Nom (T[2, 4]) is a rule of the grammar.T[5, 5] = {Nom} as Nom –> book is a rule of the grammar.T[4, 5] = {Nom} as Nom –> AP (T[4, 4]) Nom (T[5, 5]) is a rule of the grammar.T[3, 5] = {Nom} as Nom –> AP (T[3, 3]) Nom (T[4, 5]) is a rule of the grammar.T[2, 5] = {Nom} as Nom –> AP (T[2, 3]) Nom (T[4, 5]) is a rule of the grammar.T[1, 5] = {NP} as NP –> Det (T[1, 1]) Nom (T[2, 5]) is a rule of the grammar." }, { "code": null, "e": 4450, "s": 4386, "text": "T[1, 1] = {Det} as Det –> a is one of the rules of the grammar." }, { "code": null, "e": 4517, "s": 4450, "text": "T[2, 2] = {Adv} as Adv –> very is one of the rules of the grammar." }, { "code": null, "e": 4563, "s": 4517, "text": "T[1, 2] = {} as no matching rule is observed." }, { "code": null, "e": 4635, "s": 4563, "text": "T[3, 3] = {A, AP} as A –> very and AP –> very are rules of the grammar." }, { "code": null, "e": 4711, "s": 4635, "text": "T[2, 3] = {AP} as AP –> Adv (T[2, 2]) A (T[3, 3]) is a rule of the grammar." }, { "code": null, "e": 4757, "s": 4711, "text": "T[1, 3] = {} as no matching rule is observed." }, { "code": null, "e": 4856, "s": 4757, "text": "T[4, 4] = {Nom, A, AP} as Nom –> orange and A –> orange and AP –> orange are rules of the grammar." }, { "code": null, "e": 4935, "s": 4856, "text": "T[3, 4] = {Nom} as Nom –> AP (T[3, 3]) Nom (T[3, 4]) is a rule of the grammar." }, { "code": null, "e": 5014, "s": 4935, "text": "T[2, 4] = {Nom} as Nom –> AP (T[2, 3]) Nom (T[4, 4]) is a rule of the grammar." }, { "code": null, "e": 5092, "s": 5014, "text": "T[1, 4] = {NP} as NP –> Det (T[1, 1]) Nom (T[2, 4]) is a rule of the grammar." }, { "code": null, "e": 5149, "s": 5092, "text": "T[5, 5] = {Nom} as Nom –> book is a rule of the grammar." }, { "code": null, "e": 5228, "s": 5149, "text": "T[4, 5] = {Nom} as Nom –> AP (T[4, 4]) Nom (T[5, 5]) is a rule of the grammar." }, { "code": null, "e": 5307, "s": 5228, "text": "T[3, 5] = {Nom} as Nom –> AP (T[3, 3]) Nom (T[4, 5]) is a rule of the grammar." }, { "code": null, "e": 5386, "s": 5307, "text": "T[2, 5] = {Nom} as Nom –> AP (T[2, 3]) Nom (T[4, 5]) is a rule of the grammar." }, { "code": null, "e": 5464, "s": 5386, "text": "T[1, 5] = {NP} as NP –> Det (T[1, 1]) Nom (T[2, 5]) is a rule of the grammar." }, { "code": null, "e": 5588, "s": 5466, "text": "We see that T[1][5] has NP, the start symbol, which means that this phrase is a member of the language of the grammar G. " }, { "code": null, "e": 5642, "s": 5590, "text": "The parse tree of this phrase would look like this:" }, { "code": null, "e": 5723, "s": 5646, "text": "Let us look at another example phrase, “a very tall extremely muscular man”:" }, { "code": null, "e": 5778, "s": 5725, "text": "a(1) very(2) tall(3) extremely(4) muscular(5) man(6)" }, { "code": null, "e": 5867, "s": 5780, "text": "We will now use the CYK algorithm to find if this string is a member of the grammar G:" }, { "code": null, "e": 5872, "s": 5869, "text": "1a" }, { "code": null, "e": 5878, "s": 5872, "text": "2very" }, { "code": null, "e": 5884, "s": 5878, "text": "3tall" }, { "code": null, "e": 5895, "s": 5884, "text": "4extremely" }, { "code": null, "e": 5905, "s": 5895, "text": "5muscular" }, { "code": null, "e": 5910, "s": 5905, "text": "6man" }, { "code": null, "e": 5913, "s": 5910, "text": "1a" }, { "code": null, "e": 5917, "s": 5913, "text": "Det" }, { "code": null, "e": 5919, "s": 5917, "text": "–" }, { "code": null, "e": 5921, "s": 5919, "text": "–" }, { "code": null, "e": 5923, "s": 5921, "text": "–" }, { "code": null, "e": 5925, "s": 5923, "text": "–" }, { "code": null, "e": 5931, "s": 5925, "text": "2very" }, { "code": null, "e": 5935, "s": 5931, "text": "Adv" }, { "code": null, "e": 5938, "s": 5935, "text": "AP" }, { "code": null, "e": 5940, "s": 5938, "text": "–" }, { "code": null, "e": 5942, "s": 5940, "text": "–" }, { "code": null, "e": 5948, "s": 5942, "text": "3tall" }, { "code": null, "e": 5954, "s": 5948, "text": "AP, A" }, { "code": null, "e": 5956, "s": 5954, "text": "–" }, { "code": null, "e": 5958, "s": 5956, "text": "–" }, { "code": null, "e": 5962, "s": 5958, "text": "Nom" }, { "code": null, "e": 5973, "s": 5962, "text": "4extremely" }, { "code": null, "e": 5977, "s": 5973, "text": "Adv" }, { "code": null, "e": 5980, "s": 5977, "text": "AP" }, { "code": null, "e": 5984, "s": 5980, "text": "Nom" }, { "code": null, "e": 5994, "s": 5984, "text": "5muscular" }, { "code": null, "e": 5996, "s": 5994, "text": "A" }, { "code": null, "e": 5998, "s": 5996, "text": "–" }, { "code": null, "e": 6003, "s": 5998, "text": "6man" }, { "code": null, "e": 6007, "s": 6003, "text": "Nom" }, { "code": null, "e": 6130, "s": 6009, "text": "We see that T[1][6] has NP, the start symbol, which means that this phrase is a member of the language of the grammar G." }, { "code": null, "e": 6183, "s": 6130, "text": "Below is the implementation of the above algorithm: " }, { "code": null, "e": 6187, "s": 6183, "text": "C++" }, { "code": null, "e": 6195, "s": 6187, "text": "Python3" }, { "code": null, "e": 6198, "s": 6195, "text": "C#" }, { "code": "// C++ implementation for the// CYK Algorithm #include<bits/stdc++.h>using namespace std; // Non-terminals symbolsvector<string> terminals,non_terminals; // Rules of the grammarunordered_map<string,vector<vector<string>>> R; // function to perform the CYK Algorithmvoid cykParse(vector<string> w){ int n = (int)w.size(); // Initialize the table map<int,map<int,set<string>>> T; // Filling in the table for(int j=0;j<n;j++) { // Iterate over the rules for(auto x:R) { string lhs = x.first; vector<vector<string>> rule = x.second; for(auto rhs:rule) { // If a terminal is found if(rhs.size() == 1 && rhs[0] == w[j]) T[j][j].insert(lhs); } } for(int i=j;i>=0;i--) { // Iterate over the range from i to j for(int k = i;k<=j;k++) { // Iterate over the rules for(auto x:R) { string lhs = x.first; vector<vector<string>> rule = x.second; for(auto rhs:rule) { // If a terminal is found if(rhs.size()==2 && T[i][k].find(rhs[0])!=T[i][k].end() && T[k+1][j].find(rhs[1])!=T[k+1][j].end()) T[i][j].insert(lhs); } } } } } // If word can be formed by rules // of given grammar if(T[0][n-1].size()!=0) cout << \"True\\n\"; else cout << \"False\\n\";} // Driver Codeint main(){ // terminal symbols terminals = {\"book\", \"orange\", \"man\", \"tall\", \"heavy\", \"very\", \"muscular\"}; // non terminal symbols non_terminals = {\"NP\", \"Nom\", \"Det\", \"AP\", \"Adv\", \"A\"}; // Rules R[\"NP\"]={{\"Det\", \"Nom\"}}; R[\"Nom\"]= {{\"AP\", \"Nom\"}, {\"book\"}, {\"orange\"}, {\"man\"}}; R[\"AP\"] = {{\"Adv\", \"A\"}, {\"heavy\"}, {\"orange\"}, {\"tall\"}}; R[\"Det\"] = {{\"a\"}}; R[\"Adv\"] = {{\"very\"}, {\"extremely\"}}; R[\"A\"] = {{\"heavy\"}, {\"orange\"}, {\"tall\"}, {\"muscular\"}}; // Given String vector<string> w = {\"a\", \"very\", \"heavy\", \"orange\", \"book\"}; // Function Call cykParse(w); return 0;}", "e": 8248, "s": 6198, "text": null }, { "code": "# Python implementation for the# CYK Algorithm # Non-terminal symbolsnon_terminals = [\"NP\", \"Nom\", \"Det\", \"AP\", \"Adv\", \"A\"]terminals = [\"book\", \"orange\", \"man\", \"tall\", \"heavy\", \"very\", \"muscular\"] # Rules of the grammarR = { \"NP\": [[\"Det\", \"Nom\"]], \"Nom\": [[\"AP\", \"Nom\"], [\"book\"], [\"orange\"], [\"man\"]], \"AP\": [[\"Adv\", \"A\"], [\"heavy\"], [\"orange\"], [\"tall\"]], \"Det\": [[\"a\"]], \"Adv\": [[\"very\"], [\"extremely\"]], \"A\": [[\"heavy\"], [\"orange\"], [\"tall\"], [\"muscular\"]] } # Function to perform the CYK Algorithmdef cykParse(w): n = len(w) # Initialize the table T = [[set([]) for j in range(n)] for i in range(n)] # Filling in the table for j in range(0, n): # Iterate over the rules for lhs, rule in R.items(): for rhs in rule: # If a terminal is found if len(rhs) == 1 and \\ rhs[0] == w[j]: T[j][j].add(lhs) for i in range(j, -1, -1): # Iterate over the range i to j + 1 for k in range(i, j + 1): # Iterate over the rules for lhs, rule in R.items(): for rhs in rule: # If a terminal is found if len(rhs) == 2 and \\ rhs[0] in T[i][k] and \\ rhs[1] in T[k + 1][j]: T[i][j].add(lhs) # If word can be formed by rules # of given grammar if len(T[0][n-1]) != 0: print(\"True\") else: print(\"False\") # Driver Code # Given stringw = \"a very heavy orange book\".split() # Function CallcykParse(w)", "e": 10033, "s": 8248, "text": null }, { "code": "// C# program to implement above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // terminal and Non-terminals symbols // static List<string> terminals = new List<string>(); // static List<string> non_terminals = new List<string>(); // Rules of the grammar static Dictionary<string,List<List<string>>> R = new Dictionary<string,List<List<string>>>(); // function to perform the CYK Algorithm static void cykParse(List<string> w) { int n = w.Count; // Initialize the table SortedDictionary<int, SortedDictionary<int, SortedSet<string>>> T = new SortedDictionary<int, SortedDictionary<int, SortedSet<string>>>(); // Filling in the table for (int j = 0 ; j < n ; j++) { // Iterate over the rules foreach (KeyValuePair<string,List<List<string>>> x in R) { string lhs = x.Key; List<List<string>> rule = x.Value; foreach (List<string> rhs in rule) { // If a terminal is found if(rhs.Count == 1 && rhs[0] == w[j]){ if(!T.ContainsKey(j)){ T.Add(j, new SortedDictionary<int, SortedSet<string>>()); } if(!T[j].ContainsKey(j)){ T[j].Add(j, new SortedSet<string>()); } T[j][j].Add(lhs); } } } for(int i = j ; i >= 0 ; i--) { // Iterate over the range from i to j for(int k = i ; k <= j ; k++) { // Iterate over the rules foreach (KeyValuePair<string,List<List<string>>> x in R) { string lhs = x.Key; List<List<string>> rule = x.Value; foreach (List<string> rhs in rule) { // If a terminal is found if(rhs.Count == 2 && T.ContainsKey(i) && T[i].ContainsKey(k) && T[i][k].Contains(rhs[0]) && T.ContainsKey(k + 1) && T[k + 1].ContainsKey(j) && T[k + 1][j].Contains(rhs[1])) { if(!T.ContainsKey(i)){ T.Add(i, new SortedDictionary<int, SortedSet<string>>()); } if(!T[i].ContainsKey(j)){ T[i].Add(j, new SortedSet<string>()); } T[i][j].Add(lhs); } } } } } } // If word can be formed by rules // of given grammar if(T.ContainsKey(0) && T[0].ContainsKey(n - 1) && T[0][n - 1].Count != 0){ Console.Write(\"True\\n\"); }else{ Console.Write(\"False\\n\"); } } // Driver code public static void Main(string[] args){ // terminal symbols // terminals = new List<string>{ // \"book\", // \"orange\", \"man\", // \"tall\", \"heavy\", // \"very\", \"muscular\" // }; // non terminal symbols // non_terminals = new List<string>{ // \"NP\", \"Nom\", \"Det\", // \"AP\", \"Adv\", \"A\" // }; // Rules R.Add(\"NP\", new List<List<string>>{ new List<string>{\"Det\", \"Nom\"} }); R[\"Nom\"]= new List<List<string>>{ new List<string>{\"AP\", \"Nom\"}, new List<string>{\"book\"}, new List<string>{\"orange\"}, new List<string>{\"man\"} }; R[\"AP\"] = new List<List<string>>{ new List<string>{\"Adv\", \"A\"}, new List<string>{\"heavy\"}, new List<string>{\"orange\"}, new List<string>{\"tall\"} }; R[\"Det\"] = new List<List<string>>{ new List<string>{\"a\"} }; R[\"Adv\"] = new List<List<string>>{ new List<string>{\"very\"}, new List<string>{\"extremely\"} }; R[\"A\"] = new List<List<string>>{ new List<string>{\"heavy\"}, new List<string>{\"orange\"}, new List<string>{\"tall\"}, new List<string>{\"muscular\"} }; // Given String List<string> w = new List<string>{\"a\", \"very\", \"heavy\", \"orange\", \"book\"}; // Function Call cykParse(w); }} // This code is contributed by subhamgoyal2014.", "e": 14891, "s": 10033, "text": null }, { "code": null, "e": 14896, "s": 14891, "text": "True" }, { "code": null, "e": 14944, "s": 14898, "text": "Time Complexity: O(N3) Auxiliary Space:O(N2) " }, { "code": null, "e": 14971, "s": 14944, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 14987, "s": 14971, "text": "subhamgoyal2014" }, { "code": null, "e": 14998, "s": 14987, "text": "Algorithms" }, { "code": null, "e": 15014, "s": 14998, "text": "Compiler Design" }, { "code": null, "e": 15034, "s": 15014, "text": "Dynamic Programming" }, { "code": null, "e": 15054, "s": 15034, "text": "Dynamic Programming" }, { "code": null, "e": 15065, "s": 15054, "text": "Algorithms" } ]
Python | Excel File Comparison
09 Sep, 2019 Input : Two Excel files Output : Column name : 'location' and Row Number : 0 Column name : 'location' and Row Number : 3 Column name : 'date' and Row Number : 1 Code : Python code for comparing two excel files # Write Python3 code here# importing Pandas import pandas as pd #Reading two Excel Sheets sheet1 = pd.read_excel(r'Book1.xlsx')sheet2 = pd.read_excel(r'Book2.xlsx') # Iterating the Columns Names of both Sheetsfor i,j in zip(sheet1,sheet2): # Creating empty lists to append the columns values a,b =[],[] # Iterating the columns values for m, n in zip(sheet1[i],sheet2[j]): # Appending values in lists a.append(m) b.append(n) # Sorting the lists a.sort() b.sort() # Iterating the list's values and comparing them for m, n in zip(range(len(a)), range(len(b))): if a[m] != b[n]: print('Column name : \'{}\' and Row Number : {}'.format(i,m)) Articles Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Sep, 2019" }, { "code": null, "e": 223, "s": 54, "text": "Input : \nTwo Excel files\n\nOutput :\nColumn name : 'location' and Row Number : 0\nColumn name : 'location' and Row Number : 3\nColumn name : 'date' and Row Number : 1\n\n" }, { "code": null, "e": 272, "s": 223, "text": "Code : Python code for comparing two excel files" }, { "code": "# Write Python3 code here# importing Pandas import pandas as pd #Reading two Excel Sheets sheet1 = pd.read_excel(r'Book1.xlsx')sheet2 = pd.read_excel(r'Book2.xlsx') # Iterating the Columns Names of both Sheetsfor i,j in zip(sheet1,sheet2): # Creating empty lists to append the columns values a,b =[],[] # Iterating the columns values for m, n in zip(sheet1[i],sheet2[j]): # Appending values in lists a.append(m) b.append(n) # Sorting the lists a.sort() b.sort() # Iterating the list's values and comparing them for m, n in zip(range(len(a)), range(len(b))): if a[m] != b[n]: print('Column name : \\'{}\\' and Row Number : {}'.format(i,m))", "e": 996, "s": 272, "text": null }, { "code": null, "e": 1005, "s": 996, "text": "Articles" }, { "code": null, "e": 1012, "s": 1005, "text": "Python" }, { "code": null, "e": 1028, "s": 1012, "text": "Python Programs" } ]
ML | Implementing L1 and L2 regularization using Sklearn
22 Nov, 2021 Prerequisites: L2 and L1 regularizationThis article aims to implement the L2 and L1 regularization for Linear regression using the Ridge and Lasso modules of the Sklearn library of Python. Dataset – House prices dataset.Step 1: Importing the required libraries Python3 import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegression, Ridge, Lassofrom sklearn.model_selection import train_test_split, cross_val_scorefrom statistics import mean Step 2: Loading and cleaning the Data Python3 # Changing the working location to the location of the datacd C:\Users\Dev\Desktop\Kaggle\House Prices # Loading the data into a Pandas DataFramedata = pd.read_csv('kc_house_data.csv') # Dropping the numerically non-sensical variablesdropColumns = ['id', 'date', 'zipcode']data = data.drop(dropColumns, axis = 1) # Separating the dependent and independent variablesy = data['price']X = data.drop('price', axis = 1) # Dividing the data into training and testing setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25) Step 3: Building and evaluating the different modelsa) Linear Regression: Python3 # Building and fitting the Linear Regression modellinearModel = LinearRegression()linearModel.fit(X_train, y_train) # Evaluating the Linear Regression modelprint(linearModel.score(X_test, y_test)) b) Ridge(L2) Regression: Python3 # List to maintain the different cross-validation scorescross_val_scores_ridge = [] # List to maintain the different values of alphaalpha = [] # Loop to compute the different values of cross-validation scoresfor i in range(1, 9): ridgeModel = Ridge(alpha = i * 0.25) ridgeModel.fit(X_train, y_train) scores = cross_val_score(ridgeModel, X, y, cv = 10) avg_cross_val_score = mean(scores)*100 cross_val_scores_ridge.append(avg_cross_val_score) alpha.append(i * 0.25) # Loop to print the different values of cross-validation scoresfor i in range(0, len(alpha)): print(str(alpha[i])+' : '+str(cross_val_scores_ridge[i])) From the above output, we can conclude that the best value of alpha for the data is 2. Python3 # Building and fitting the Ridge Regression modelridgeModelChosen = Ridge(alpha = 2)ridgeModelChosen.fit(X_train, y_train) # Evaluating the Ridge Regression modelprint(ridgeModelChosen.score(X_test, y_test)) c) Lasso(L1) Regression: Python3 # List to maintain the cross-validation scorescross_val_scores_lasso = [] # List to maintain the different values of LambdaLambda = [] # Loop to compute the cross-validation scoresfor i in range(1, 9): lassoModel = Lasso(alpha = i * 0.25, tol = 0.0925) lassoModel.fit(X_train, y_train) scores = cross_val_score(lassoModel, X, y, cv = 10) avg_cross_val_score = mean(scores)*100 cross_val_scores_lasso.append(avg_cross_val_score) Lambda.append(i * 0.25) # Loop to print the different values of cross-validation scoresfor i in range(0, len(alpha)): print(str(alpha[i])+' : '+str(cross_val_scores_lasso[i])) From the above output, we can conclude that the best value of lambda is 2. Python3 # Building and fitting the Lasso Regression ModellassoModelChosen = Lasso(alpha = 2, tol = 0.0925)lassoModelChosen.fit(X_train, y_train) # Evaluating the Lasso Regression modelprint(lassoModelChosen.score(X_test, y_test)) Step 4: Comparing and Visualizing the results Python3 # Building the two lists for visualizationmodels = ['Linear Regression', 'Ridge Regression', 'Lasso Regression']scores = [linearModel.score(X_test, y_test), ridgeModelChosen.score(X_test, y_test), lassoModelChosen.score(X_test, y_test)] # Building the dictionary to compare the scoresmapping = {}mapping['Linear Regression'] = linearModel.score(X_test, y_test)mapping['Ridge Regression'] = ridgeModelChosen.score(X_test, y_test)mapping['Lasso Regression'] = lassoModelChosen.score(X_test, y_test) # Printing the scores for different modelsfor key, val in mapping.items(): print(str(key)+' : '+str(val)) Python3 # Plotting the scoresplt.bar(models, scores)plt.xlabel('Regression Models')plt.ylabel('Score')plt.show() shubham_singh clintra surinderdawra388 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Introduction to Recurrent Neural Network Markov Decision Process Support Vector Machine Algorithm DBSCAN Clustering in ML | Density based clustering Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2021" }, { "code": null, "e": 290, "s": 28, "text": "Prerequisites: L2 and L1 regularizationThis article aims to implement the L2 and L1 regularization for Linear regression using the Ridge and Lasso modules of the Sklearn library of Python. Dataset – House prices dataset.Step 1: Importing the required libraries " }, { "code": null, "e": 298, "s": 290, "text": "Python3" }, { "code": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegression, Ridge, Lassofrom sklearn.model_selection import train_test_split, cross_val_scorefrom statistics import mean", "e": 526, "s": 298, "text": null }, { "code": null, "e": 565, "s": 526, "text": "Step 2: Loading and cleaning the Data " }, { "code": null, "e": 573, "s": 565, "text": "Python3" }, { "code": "# Changing the working location to the location of the datacd C:\\Users\\Dev\\Desktop\\Kaggle\\House Prices # Loading the data into a Pandas DataFramedata = pd.read_csv('kc_house_data.csv') # Dropping the numerically non-sensical variablesdropColumns = ['id', 'date', 'zipcode']data = data.drop(dropColumns, axis = 1) # Separating the dependent and independent variablesy = data['price']X = data.drop('price', axis = 1) # Dividing the data into training and testing setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)", "e": 1113, "s": 573, "text": null }, { "code": null, "e": 1188, "s": 1113, "text": "Step 3: Building and evaluating the different modelsa) Linear Regression: " }, { "code": null, "e": 1196, "s": 1188, "text": "Python3" }, { "code": "# Building and fitting the Linear Regression modellinearModel = LinearRegression()linearModel.fit(X_train, y_train) # Evaluating the Linear Regression modelprint(linearModel.score(X_test, y_test))", "e": 1393, "s": 1196, "text": null }, { "code": null, "e": 1419, "s": 1393, "text": "b) Ridge(L2) Regression: " }, { "code": null, "e": 1427, "s": 1419, "text": "Python3" }, { "code": "# List to maintain the different cross-validation scorescross_val_scores_ridge = [] # List to maintain the different values of alphaalpha = [] # Loop to compute the different values of cross-validation scoresfor i in range(1, 9): ridgeModel = Ridge(alpha = i * 0.25) ridgeModel.fit(X_train, y_train) scores = cross_val_score(ridgeModel, X, y, cv = 10) avg_cross_val_score = mean(scores)*100 cross_val_scores_ridge.append(avg_cross_val_score) alpha.append(i * 0.25) # Loop to print the different values of cross-validation scoresfor i in range(0, len(alpha)): print(str(alpha[i])+' : '+str(cross_val_scores_ridge[i]))", "e": 2065, "s": 1427, "text": null }, { "code": null, "e": 2153, "s": 2065, "text": "From the above output, we can conclude that the best value of alpha for the data is 2. " }, { "code": null, "e": 2161, "s": 2153, "text": "Python3" }, { "code": "# Building and fitting the Ridge Regression modelridgeModelChosen = Ridge(alpha = 2)ridgeModelChosen.fit(X_train, y_train) # Evaluating the Ridge Regression modelprint(ridgeModelChosen.score(X_test, y_test))", "e": 2369, "s": 2161, "text": null }, { "code": null, "e": 2395, "s": 2369, "text": "c) Lasso(L1) Regression: " }, { "code": null, "e": 2403, "s": 2395, "text": "Python3" }, { "code": "# List to maintain the cross-validation scorescross_val_scores_lasso = [] # List to maintain the different values of LambdaLambda = [] # Loop to compute the cross-validation scoresfor i in range(1, 9): lassoModel = Lasso(alpha = i * 0.25, tol = 0.0925) lassoModel.fit(X_train, y_train) scores = cross_val_score(lassoModel, X, y, cv = 10) avg_cross_val_score = mean(scores)*100 cross_val_scores_lasso.append(avg_cross_val_score) Lambda.append(i * 0.25) # Loop to print the different values of cross-validation scoresfor i in range(0, len(alpha)): print(str(alpha[i])+' : '+str(cross_val_scores_lasso[i]))", "e": 3028, "s": 2403, "text": null }, { "code": null, "e": 3104, "s": 3028, "text": "From the above output, we can conclude that the best value of lambda is 2. " }, { "code": null, "e": 3112, "s": 3104, "text": "Python3" }, { "code": "# Building and fitting the Lasso Regression ModellassoModelChosen = Lasso(alpha = 2, tol = 0.0925)lassoModelChosen.fit(X_train, y_train) # Evaluating the Lasso Regression modelprint(lassoModelChosen.score(X_test, y_test))", "e": 3334, "s": 3112, "text": null }, { "code": null, "e": 3381, "s": 3334, "text": "Step 4: Comparing and Visualizing the results " }, { "code": null, "e": 3389, "s": 3381, "text": "Python3" }, { "code": "# Building the two lists for visualizationmodels = ['Linear Regression', 'Ridge Regression', 'Lasso Regression']scores = [linearModel.score(X_test, y_test), ridgeModelChosen.score(X_test, y_test), lassoModelChosen.score(X_test, y_test)] # Building the dictionary to compare the scoresmapping = {}mapping['Linear Regression'] = linearModel.score(X_test, y_test)mapping['Ridge Regression'] = ridgeModelChosen.score(X_test, y_test)mapping['Lasso Regression'] = lassoModelChosen.score(X_test, y_test) # Printing the scores for different modelsfor key, val in mapping.items(): print(str(key)+' : '+str(val))", "e": 4011, "s": 3389, "text": null }, { "code": null, "e": 4019, "s": 4011, "text": "Python3" }, { "code": "# Plotting the scoresplt.bar(models, scores)plt.xlabel('Regression Models')plt.ylabel('Score')plt.show()", "e": 4124, "s": 4019, "text": null }, { "code": null, "e": 4138, "s": 4124, "text": "shubham_singh" }, { "code": null, "e": 4146, "s": 4138, "text": "clintra" }, { "code": null, "e": 4163, "s": 4146, "text": "surinderdawra388" }, { "code": null, "e": 4180, "s": 4163, "text": "Machine Learning" }, { "code": null, "e": 4187, "s": 4180, "text": "Python" }, { "code": null, "e": 4204, "s": 4187, "text": "Machine Learning" }, { "code": null, "e": 4302, "s": 4204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4338, "s": 4302, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 4379, "s": 4338, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 4403, "s": 4379, "text": "Markov Decision Process" }, { "code": null, "e": 4436, "s": 4403, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 4487, "s": 4436, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 4515, "s": 4487, "text": "Read JSON file using Python" }, { "code": null, "e": 4537, "s": 4515, "text": "Python map() function" }, { "code": null, "e": 4587, "s": 4537, "text": "Adding new column to existing DataFrame in Pandas" } ]
TextSpan Widget in Flutter
01 Jul, 2021 TextSpan is an immutable span of text. It has style property to give style to the text. It is also having children property to add more text to this widget and give style to the children. Let’s understand this with the help of an example. Syntax: TextSpan({String text, List<InlineSpan> children, TextStyle style, GestureRecognizer recognizer, String semanticsLabel}) text: The text contained in the span. children: More spans to include as children. style: The TextStyle given to the text. recognizer: The gesture detector when user hit the TextSpan widget. semanticsLabel: An alternative semantic label for this widget. hashCode: This parameter takes in an int value as the object to provide a hash code to the TextSpan widget. Hash code is an integer value that represents the state of the object that effect operator == comparison. runtimeType: This property takes in a Type as the object to represent the runtime type of the object. This property supports null safety. Example: Dart import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is //the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'TextSpan', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green ), body: Center( child: Text.rich( TextSpan( text: 'This is textspan ', children: <InlineSpan>[ TextSpan( text: 'Widget in flutter', style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold), ) ] ) ), ), backgroundColor: Colors.lightBlue[50], ); }} Output: If the properties are defined as below: TextSpan( text: 'This is textspan ', style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold), children: <InlineSpan>[ TextSpan( text: 'Widget in flutter', ) ] ) The following design changes can be observed: If the properties are defined as below: TextSpan( text: 'This is textspan ', children: <InlineSpan>[ TextSpan( text: 'Widget in flutter', style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold), ) ] ) The following design changes can be observed: Create TextSpan widget and wrap it with Text.rich() widget. Give the text to the TextSpan and add more inline children to it. Give style to the text and see the output. build(ParagraphBuilder builder, {double textScaleFactor: 1.0, List<PlaceholderDimensions>? dimensions}) @override void build ( ParagraphBuilder builder, {double textScaleFactor: 1.0, List<PlaceholderDimensions>? dimensions} ) override This build method helps in building drawing the paragraph objects. Paragraph can be obtained by applying the style, text and children of this object to the given ParagraphBuilder. compareTo(InlineSpan other) → RenderComparison @override RenderComparison compareTo ( InlineSpan other ) override This method returns the difference between this span and another, in terms of the damage that can be made to the rendering. toStringShort() → String @override String toStringShort () override This method gives a concise description of the object, which are usually the runtimeType and the hashCode. visitChildren(InlineSpanVisitor visitor) → bool @override bool visitChildren ( InlineSpanVisitor visitor ) override This method moves this TextSpan and its child in pre-order and calls visitor for each span that has text. operator ==(Object other) → bool @override bool operator == ( Object other ) override The equality operator. The default action for all Objects is to return true if and only if this object and other are the same object. This method is overridden to define a different equality relation on a class. ankit_kumar_ android Flutter Flutter-widgets Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jul, 2021" }, { "code": null, "e": 293, "s": 54, "text": "TextSpan is an immutable span of text. It has style property to give style to the text. It is also having children property to add more text to this widget and give style to the children. Let’s understand this with the help of an example." }, { "code": null, "e": 426, "s": 293, "text": "Syntax:\nTextSpan({String text, \nList<InlineSpan> children, \nTextStyle style, \nGestureRecognizer recognizer, \nString semanticsLabel})" }, { "code": null, "e": 464, "s": 426, "text": "text: The text contained in the span." }, { "code": null, "e": 509, "s": 464, "text": "children: More spans to include as children." }, { "code": null, "e": 549, "s": 509, "text": "style: The TextStyle given to the text." }, { "code": null, "e": 617, "s": 549, "text": "recognizer: The gesture detector when user hit the TextSpan widget." }, { "code": null, "e": 680, "s": 617, "text": "semanticsLabel: An alternative semantic label for this widget." }, { "code": null, "e": 894, "s": 680, "text": "hashCode: This parameter takes in an int value as the object to provide a hash code to the TextSpan widget. Hash code is an integer value that represents the state of the object that effect operator == comparison." }, { "code": null, "e": 1032, "s": 894, "text": "runtimeType: This property takes in a Type as the object to represent the runtime type of the object. This property supports null safety." }, { "code": null, "e": 1041, "s": 1032, "text": "Example:" }, { "code": null, "e": 1046, "s": 1041, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is //the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'TextSpan', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green ), body: Center( child: Text.rich( TextSpan( text: 'This is textspan ', children: <InlineSpan>[ TextSpan( text: 'Widget in flutter', style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold), ) ] ) ), ), backgroundColor: Colors.lightBlue[50], ); }}", "e": 2195, "s": 1046, "text": null }, { "code": null, "e": 2203, "s": 2195, "text": "Output:" }, { "code": null, "e": 2243, "s": 2203, "text": "If the properties are defined as below:" }, { "code": null, "e": 2525, "s": 2243, "text": "TextSpan(\n text: 'This is textspan ',\n style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),\n children: <InlineSpan>[\n TextSpan(\n text: 'Widget in flutter',\n )\n ]\n )" }, { "code": null, "e": 2571, "s": 2525, "text": "The following design changes can be observed:" }, { "code": null, "e": 2611, "s": 2571, "text": "If the properties are defined as below:" }, { "code": null, "e": 2897, "s": 2611, "text": "TextSpan(\n text: 'This is textspan ',\n children: <InlineSpan>[\n TextSpan(\n text: 'Widget in flutter',\n style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),\n )\n ]\n )" }, { "code": null, "e": 2943, "s": 2897, "text": "The following design changes can be observed:" }, { "code": null, "e": 3003, "s": 2943, "text": "Create TextSpan widget and wrap it with Text.rich() widget." }, { "code": null, "e": 3069, "s": 3003, "text": "Give the text to the TextSpan and add more inline children to it." }, { "code": null, "e": 3112, "s": 3069, "text": "Give style to the text and see the output." }, { "code": null, "e": 3218, "s": 3112, "text": "build(ParagraphBuilder builder, {double textScaleFactor: 1.0, List<PlaceholderDimensions>? dimensions}) " }, { "code": null, "e": 3349, "s": 3218, "text": "@override\nvoid build (\nParagraphBuilder builder,\n{double textScaleFactor: 1.0,\nList<PlaceholderDimensions>? dimensions}\n)\noverride" }, { "code": null, "e": 3530, "s": 3349, "text": "This build method helps in building drawing the paragraph objects. Paragraph can be obtained by applying the style, text and children of this object to the given ParagraphBuilder. " }, { "code": null, "e": 3577, "s": 3530, "text": "compareTo(InlineSpan other) → RenderComparison" }, { "code": null, "e": 3644, "s": 3577, "text": "@override\nRenderComparison compareTo (\nInlineSpan other\n)\noverride" }, { "code": null, "e": 3768, "s": 3644, "text": "This method returns the difference between this span and another, in terms of the damage that can be made to the rendering." }, { "code": null, "e": 3793, "s": 3768, "text": "toStringShort() → String" }, { "code": null, "e": 3836, "s": 3793, "text": "@override\nString toStringShort ()\noverride" }, { "code": null, "e": 3943, "s": 3836, "text": "This method gives a concise description of the object, which are usually the runtimeType and the hashCode." }, { "code": null, "e": 3991, "s": 3943, "text": "visitChildren(InlineSpanVisitor visitor) → bool" }, { "code": null, "e": 4059, "s": 3991, "text": "@override\nbool visitChildren (\nInlineSpanVisitor visitor\n)\noverride" }, { "code": null, "e": 4165, "s": 4059, "text": "This method moves this TextSpan and its child in pre-order and calls visitor for each span that has text." }, { "code": null, "e": 4198, "s": 4165, "text": "operator ==(Object other) → bool" }, { "code": null, "e": 4251, "s": 4198, "text": "@override\nbool operator == (\nObject other\n)\noverride" }, { "code": null, "e": 4274, "s": 4251, "text": "The equality operator." }, { "code": null, "e": 4463, "s": 4274, "text": "The default action for all Objects is to return true if and only if this object and other are the same object. This method is overridden to define a different equality relation on a class." }, { "code": null, "e": 4476, "s": 4463, "text": "ankit_kumar_" }, { "code": null, "e": 4484, "s": 4476, "text": "android" }, { "code": null, "e": 4492, "s": 4484, "text": "Flutter" }, { "code": null, "e": 4508, "s": 4492, "text": "Flutter-widgets" }, { "code": null, "e": 4513, "s": 4508, "text": "Dart" }, { "code": null, "e": 4521, "s": 4513, "text": "Flutter" } ]
Python – Remove empty List from List
04 Jul, 2022 Sometimes, while working with python, we can have a problem in which we need to filter out certain empty data. These can be none, empty string, etc. This can have applications in many domains. Let us discuss certain ways in which the removal of empty lists can be performed. Method 1: Using list comprehension: This is one of the ways in which this problem can be solved. In this, we iterate through the list and don’t include the list which is empty. Example Python3 # Python3 code to Demonstrate Remove empty List# from List using list comprehension # Initializing listtest_list = [5, 6, [], 3, [], [], 9] # printing original listprint("The original list is : " + str(test_list)) # Remove empty List from List# using list comprehensionres = [ele for ele in test_list if ele != []] # printing resultprint("List after empty list removal : " + str(res)) The original list is : [5, 6, [], 3, [], [], 9] List after empty list removal : [5, 6, 3, 9] Method 2: Using filter() method This is yet another way in which this task can be performed. In this, we filter None values. The none values include empty lists as well and hence these get removed. Example Python3 # Python3 Code to Demonstrate Remove empty List# from List using filter() Method # Initializing list by custom valuestest_list = [5, 6, [], 3, [], [], 9] # Printing original listprint("The original list is : " + str(test_list)) # Removing empty List from List# using filter() methodres = list(filter(None, test_list)) # Printing the resultant listprint("List after empty list removal : " + str(res)) The original list is : [5, 6, [], 3, [], [], 9] List after empty list removal : [5, 6, 3, 9] Method 3: Using function defination Python3 # Python Code to Remove empty List from List def empty_list_remove(input_list): new_list = [] for ele in input_list: if ele: new_list.append(ele) return new_list # input list valuesinput_list = [5, 6, [], 3, [], [], 9] # print initial list valuesprint(f"The original list is : {input_list}")# function-call & print valuesprint(f"List after empty list removal : {empty_list_remove(input_list)}") The original list is : [5, 6, [], 3, [], [], 9] List after empty list removal : [5, 6, 3, 9] Above defined method(Method 3) is best optimized method among all three. Method 4: Using len() and type() methods.If the length is zero then the list is empty. Python3 # Python3 code to Demonstrate Remove empty List # Initializing listtest_list = [5, 6, [], 3, [], [], 9] # printing original listprint("The original list is : " + str(test_list))new_list=[]# Remove empty List from Listfor i in test_list: x=str(type(i)) if(x.find('list')!=-1): if(len(i)!=0): new_list.append(i) else: new_list.append(i)# printing resultprint("List after empty list removal : " + str(new_list)) The original list is : [5, 6, [], 3, [], [], 9] List after empty list removal : [5, 6, 3, 9] saikot varshagumber28 kogantibhavya Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2022" }, { "code": null, "e": 328, "s": 52, "text": "Sometimes, while working with python, we can have a problem in which we need to filter out certain empty data. These can be none, empty string, etc. This can have applications in many domains. Let us discuss certain ways in which the removal of empty lists can be performed. " }, { "code": null, "e": 506, "s": 328, "text": "Method 1: Using list comprehension: This is one of the ways in which this problem can be solved. In this, we iterate through the list and don’t include the list which is empty. " }, { "code": null, "e": 514, "s": 506, "text": "Example" }, { "code": null, "e": 522, "s": 514, "text": "Python3" }, { "code": "# Python3 code to Demonstrate Remove empty List# from List using list comprehension # Initializing listtest_list = [5, 6, [], 3, [], [], 9] # printing original listprint(\"The original list is : \" + str(test_list)) # Remove empty List from List# using list comprehensionres = [ele for ele in test_list if ele != []] # printing resultprint(\"List after empty list removal : \" + str(res))", "e": 907, "s": 522, "text": null }, { "code": null, "e": 1000, "s": 907, "text": "The original list is : [5, 6, [], 3, [], [], 9]\nList after empty list removal : [5, 6, 3, 9]" }, { "code": null, "e": 1032, "s": 1000, "text": "Method 2: Using filter() method" }, { "code": null, "e": 1198, "s": 1032, "text": "This is yet another way in which this task can be performed. In this, we filter None values. The none values include empty lists as well and hence these get removed." }, { "code": null, "e": 1206, "s": 1198, "text": "Example" }, { "code": null, "e": 1214, "s": 1206, "text": "Python3" }, { "code": "# Python3 Code to Demonstrate Remove empty List# from List using filter() Method # Initializing list by custom valuestest_list = [5, 6, [], 3, [], [], 9] # Printing original listprint(\"The original list is : \" + str(test_list)) # Removing empty List from List# using filter() methodres = list(filter(None, test_list)) # Printing the resultant listprint(\"List after empty list removal : \" + str(res))", "e": 1614, "s": 1214, "text": null }, { "code": null, "e": 1707, "s": 1614, "text": "The original list is : [5, 6, [], 3, [], [], 9]\nList after empty list removal : [5, 6, 3, 9]" }, { "code": null, "e": 1744, "s": 1707, "text": "Method 3: Using function defination " }, { "code": null, "e": 1752, "s": 1744, "text": "Python3" }, { "code": "# Python Code to Remove empty List from List def empty_list_remove(input_list): new_list = [] for ele in input_list: if ele: new_list.append(ele) return new_list # input list valuesinput_list = [5, 6, [], 3, [], [], 9] # print initial list valuesprint(f\"The original list is : {input_list}\")# function-call & print valuesprint(f\"List after empty list removal : {empty_list_remove(input_list)}\")", "e": 2175, "s": 1752, "text": null }, { "code": null, "e": 2268, "s": 2175, "text": "The original list is : [5, 6, [], 3, [], [], 9]\nList after empty list removal : [5, 6, 3, 9]" }, { "code": null, "e": 2341, "s": 2268, "text": "Above defined method(Method 3) is best optimized method among all three." }, { "code": null, "e": 2428, "s": 2341, "text": "Method 4: Using len() and type() methods.If the length is zero then the list is empty." }, { "code": null, "e": 2436, "s": 2428, "text": "Python3" }, { "code": "# Python3 code to Demonstrate Remove empty List # Initializing listtest_list = [5, 6, [], 3, [], [], 9] # printing original listprint(\"The original list is : \" + str(test_list))new_list=[]# Remove empty List from Listfor i in test_list: x=str(type(i)) if(x.find('list')!=-1): if(len(i)!=0): new_list.append(i) else: new_list.append(i)# printing resultprint(\"List after empty list removal : \" + str(new_list))", "e": 2879, "s": 2436, "text": null }, { "code": null, "e": 2972, "s": 2879, "text": "The original list is : [5, 6, [], 3, [], [], 9]\nList after empty list removal : [5, 6, 3, 9]" }, { "code": null, "e": 2979, "s": 2972, "text": "saikot" }, { "code": null, "e": 2994, "s": 2979, "text": "varshagumber28" }, { "code": null, "e": 3008, "s": 2994, "text": "kogantibhavya" }, { "code": null, "e": 3029, "s": 3008, "text": "Python list-programs" }, { "code": null, "e": 3036, "s": 3029, "text": "Python" }, { "code": null, "e": 3052, "s": 3036, "text": "Python Programs" } ]
Print matrix in zig-zag fashion
26 May, 2022 Given a matrix of 2D array of n rows and m columns. Print this matrix in ZIG-ZAG fashion as shown in figure. Example: Input: 1 2 3 4 5 6 7 8 9 Output: 1 2 4 7 5 3 6 8 9 Approach of C++ code The approach is simple. Just simply iterate over every diagonal elements one at a time and change the direction according to the previous match. Approach of Python3 code This approach is simple. While travelling the matrix in the usual fashion, on basis of parity of the sum of the indices of the element, add that particular element to the list either at the beginning or at the end if sum of i and j is either even or odd respectively. Print the solution list as it is. C++ Java Python3 C# PHP Javascript /* C++ Program to print matrix in Zig-zag pattern*/#include <iostream>using namespace std;#define C 3 // Utility function to print matrix// in zig-zag formvoid zigZagMatrix(int arr[][C], int n, int m){ int row = 0, col = 0; // Boolean variable that will true if we // need to increment 'row' value otherwise // false- if increment 'col' value bool row_inc = 0; // Print matrix of lower half zig-zag pattern int mn = min(m, n); for (int len = 1; len <= mn; ++len) { for (int i = 0; i < len; ++i) { cout << arr[row][col] << " "; if (i + 1 == len) break; // If row_increment value is true // increment row and decrement col // else decrement row and increment // col if (row_inc) ++row, --col; else --row, ++col; } if (len == mn) break; // Update row or col value according // to the last increment if (row_inc) ++row, row_inc = false; else ++col, row_inc = true; } // Update the indexes of row and col variable if (row == 0) { if (col == m - 1) ++row; else ++col; row_inc = 1; } else { if (row == n - 1) ++col; else ++row; row_inc = 0; } // Print the next half zig-zag pattern int MAX = max(m, n) - 1; for (int len, diag = MAX; diag > 0; --diag) { if (diag > mn) len = mn; else len = diag; for (int i = 0; i < len; ++i) { cout << arr[row][col] << " "; if (i + 1 == len) break; // Update row or col value according // to the last increment if (row_inc) ++row, --col; else ++col, --row; } // Update the indexes of row and col variable if (row == 0 || col == m - 1) { if (col == m - 1) ++row; else ++col; row_inc = true; } else if (col == 0 || row == n - 1) { if (row == n - 1) ++col; else ++row; row_inc = false; } }} // Driver codeint main(){ int matrix[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; zigZagMatrix(matrix, 3, 3); return 0;} /* Java Program to print matrix in Zig-zag pattern*/class GFG { static final int C = 3; // Utility function to print matrix // in zig-zag form static void zigZagMatrix(int arr[][], int n, int m) { int row = 0, col = 0; // Boolean variable that will true if we // need to increment 'row' value otherwise // false- if increment 'col' value boolean row_inc = false; // Print matrix of lower half zig-zag pattern int mn = Math.min(m, n); for (int len = 1; len <= mn; ++len) { for (int i = 0; i < len; ++i) { System.out.print(arr[row][col] + " "); if (i + 1 == len) break; // If row_increment value is true // increment row and decrement col // else decrement row and increment // col if (row_inc) { ++row; --col; } else { --row; ++col; } } if (len == mn) break; // Update row or col value according // to the last increment if (row_inc) { ++row; row_inc = false; } else { ++col; row_inc = true; } } // Update the indexes of row and col variable if (row == 0) { if (col == m - 1) ++row; else ++col; row_inc = true; } else { if (row == n - 1) ++col; else ++row; row_inc = false; } // Print the next half zig-zag pattern int MAX = Math.max(m, n) - 1; for (int len, diag = MAX; diag > 0; --diag) { if (diag > mn) len = mn; else len = diag; for (int i = 0; i < len; ++i) { System.out.print(arr[row][col] + " "); if (i + 1 == len) break; // Update row or col value according // to the last increment if (row_inc) { ++row; --col; } else { ++col; --row; } } // Update the indexes of row and col variable if (row == 0 || col == m - 1) { if (col == m - 1) ++row; else ++col; row_inc = true; } else if (col == 0 || row == n - 1) { if (row == n - 1) ++col; else ++row; row_inc = false; } } } // Driver code public static void main(String[] args) { int matrix[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; zigZagMatrix(matrix, 3, 3); }}// This code is contributed by Anant Agarwal. # Program to print matrix in Zig-zag pattern matrix =[ [ 1, 2, 3,], [ 4, 5, 6 ], [ 7, 8, 9 ], ]rows=3columns=3 solution=[[] for i in range(rows+columns-1)] for i in range(rows): for j in range(columns): sum=i+j if(sum%2 ==0): #add at beginning solution[sum].insert(0,matrix[i][j]) else: #add at end of the list solution[sum].append(matrix[i][j]) # print the solution as it asfor i in solution: for j in i: print(j,end=" ") // C# Program to print matrix// in Zig-zag patternusing System; class GFG { static int C = 3; // Utility function to print // matrix in zig-zag form static void zigZagMatrix(int[, ] arr, int n, int m) { int row = 0, col = 0; // Boolean variable that will // true if we need to increment // 'row' valueotherwise false- // if increment 'col' value bool row_inc = false; // Print matrix of lower half // zig-zag pattern int mn = Math.Min(m, n); for (int len = 1; len <= mn; ++len) { for (int i = 0; i < len; ++i) { Console.Write(arr[row, col] + " "); if (i + 1 == len) break; // If row_increment value is true // increment row and decrement col // else decrement row and increment // col if (row_inc) { ++row; --col; } else { --row; ++col; } } if (len == mn) break; // Update row or col value // according to the last // increment if (row_inc) { ++row; row_inc = false; } else { ++col; row_inc = true; } } // Update the indexes of row // and col variable if (row == 0) { if (col == m - 1) ++row; else ++col; row_inc = true; } else { if (row == n - 1) ++col; else ++row; row_inc = false; } // Print the next half // zig-zag pattern int MAX = Math.Max(m, n) - 1; for (int len, diag = MAX; diag > 0; --diag) { if (diag > mn) len = mn; else len = diag; for (int i = 0; i < len; ++i) { Console.Write(arr[row, col] + " "); if (i + 1 == len) break; // Update row or col value // according to the last // increment if (row_inc) { ++row; --col; } else { ++col; --row; } } // Update the indexes of // row and col variable if (row == 0 || col == m - 1) { if (col == m - 1) ++row; else ++col; row_inc = true; } else if (col == 0 || row == n - 1) { if (row == n - 1) ++col; else ++row; row_inc = false; } } } // Driver code public static void Main() { int[, ] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; zigZagMatrix(matrix, 3, 3); }} // This code is contributed by vt_m. <?php// PHP Program to print// matrix in Zig-zag pattern$C = 3; // Utility function// to print matrix// in zig-zag formfunction zigZagMatrix($arr, $n, $m){ $row = 0; $col = 0; // Boolean variable that // will true if we need // to increment 'row' // value otherwise false- // if increment 'col' value $row_inc = false; // Print matrix of lower // half zig-zag pattern $mn = min($m, $n); for ($len = 1; $len <= $mn; $len++) { for ($i = 0; $i < $len; $i++) { echo ($arr[$row][$col]." "); if ($i + 1 == $len) break; // If row_increment value // is true increment row // and decrement col else // decrement row and // increment col if ($row_inc) { $row++; $col--; } else { $row--; $col++; } } if ($len == $mn) break; // Update row or col // value according // to the last increment if ($row_inc) { ++$row; $row_inc = false; } else { ++$col; $row_inc = true; } } // Update the indexes of // row and col variable if ($row == 0) { if ($col == $m - 1) ++$row; else ++$col; $row_inc = 1; } else { if ($row == $n - 1) ++$col; else ++$row; $row_inc = 0; } // Print the next half // zig-zag pattern $MAX = max($m, $n) - 1; for ($len, $diag = $MAX; $diag > 0; --$diag) { if ($diag > $mn) $len = $mn; else $len = $diag; for ($i = 0; $i < $len; ++$i) { echo($arr[$row][$col] . " "); if ($i + 1 == $len) break; // Update row or col // value according to // the last increment if ($row_inc) { ++$row; --$col; } else { ++$col; --$row; } } // Update the indexes of // row and col variable if ($row == 0 || $col == $m - 1) { if ($col == $m - 1) ++$row; else ++$col; $row_inc = true; } else if ($col == 0 || $row == $n - 1) { if ($row == $n - 1) ++$col; else ++$row; $row_inc = false; } }} // Driver code$matrix = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); zigZagMatrix($matrix, 3, 3); // This code is contributed by// Manish Shaw(manishshaw1)?> // Javascript Program to print matrix in Zig-zag patternvar n = 3, m = 3;var a = [[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]];var zigZagMatrix=function(arr, n, m){ var row = 0; var col = 0; // Variable that will be 1 if we // need to increment 'row' value and 0 otherwise // if we need to increment 'col' value var row_inc = 0; // print matrix of lower half zig-zag pattern var mn = Math.min(m, n); for (var len = 1; len <= mn; ++len) { for (var i = 0; i < len; ++i) { console.log(arr[row][col]); console.log(" "); if (i + 1 == len) break; // If row_increment value is true // increment row and decrement col // else decrement row and increment col if (row_inc) ++row, --col; else --row, ++col; } if (len == mn) break; // Update row or col value according // to the last increment if (row_inc) ++row, row_inc = false; else ++col, row_inc = true; } // Update the indexes of row and col variable if (row == 0) { if (col == m - 1) ++row; else ++col; row_inc = 1; } else { if (row == n - 1) ++col; else ++row; row_inc = 0; } // Print the next half zig-zag pattern var MAX = Math.max(m, n) - 1; for (var len, diag = MAX; diag > 0; --diag) { if (diag > mn) len = mn; else len = diag; for (var i = 0; i < len; ++i) { console.log(arr[row][col]); console.log(" "); if (i + 1 == len) break; // Update row or col value according // to the last increment if (row_inc) ++row, --col; else ++col, --row; } // Update the indexes of row and col variable if (row == 0 || col == m - 1) { if (col == m - 1) ++row; else ++col; row_inc = true; } else if (col == 0 || row == n - 1) { if (row == n - 1) ++col; else ++row; row_inc = false; } }}zigZagMatrix(a, 3, 3); // This code is contributed by Sajal Aggarwal. Output: 1 2 4 7 5 3 6 8 9 Time complexity: O(n*m) Auxiliary space: O(1) manishshaw1 nidhi_biet 19euit177 arorakashish0911 aggarwalsajal19 pattern-printing Matrix pattern-printing Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find largest element in an array Matrix Chain Multiplication | DP-8 Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 Find the number of islands | Set 1 (Using DFS) Rotate a matrix by 90 degree in clockwise direction without using any extra space The Celebrity Problem Unique paths in a Grid with Obstacles Count all possible paths from top left to bottom right of a mXn matrix Printing all solutions in N-Queen Problem
[ { "code": null, "e": 52, "s": 24, "text": "\n26 May, 2022" }, { "code": null, "e": 163, "s": 52, "text": "Given a matrix of 2D array of n rows and m columns. Print this matrix in ZIG-ZAG fashion as shown in figure. " }, { "code": null, "e": 174, "s": 163, "text": "Example: " }, { "code": null, "e": 227, "s": 174, "text": "Input: \n1 2 3\n4 5 6\n7 8 9\nOutput: \n1 2 4 7 5 3 6 8 9" }, { "code": null, "e": 723, "s": 229, "text": "Approach of C++ code The approach is simple. Just simply iterate over every diagonal elements one at a time and change the direction according to the previous match. Approach of Python3 code This approach is simple. While travelling the matrix in the usual fashion, on basis of parity of the sum of the indices of the element, add that particular element to the list either at the beginning or at the end if sum of i and j is either even or odd respectively. Print the solution list as it is. " }, { "code": null, "e": 727, "s": 723, "text": "C++" }, { "code": null, "e": 732, "s": 727, "text": "Java" }, { "code": null, "e": 740, "s": 732, "text": "Python3" }, { "code": null, "e": 743, "s": 740, "text": "C#" }, { "code": null, "e": 747, "s": 743, "text": "PHP" }, { "code": null, "e": 758, "s": 747, "text": "Javascript" }, { "code": "/* C++ Program to print matrix in Zig-zag pattern*/#include <iostream>using namespace std;#define C 3 // Utility function to print matrix// in zig-zag formvoid zigZagMatrix(int arr[][C], int n, int m){ int row = 0, col = 0; // Boolean variable that will true if we // need to increment 'row' value otherwise // false- if increment 'col' value bool row_inc = 0; // Print matrix of lower half zig-zag pattern int mn = min(m, n); for (int len = 1; len <= mn; ++len) { for (int i = 0; i < len; ++i) { cout << arr[row][col] << \" \"; if (i + 1 == len) break; // If row_increment value is true // increment row and decrement col // else decrement row and increment // col if (row_inc) ++row, --col; else --row, ++col; } if (len == mn) break; // Update row or col value according // to the last increment if (row_inc) ++row, row_inc = false; else ++col, row_inc = true; } // Update the indexes of row and col variable if (row == 0) { if (col == m - 1) ++row; else ++col; row_inc = 1; } else { if (row == n - 1) ++col; else ++row; row_inc = 0; } // Print the next half zig-zag pattern int MAX = max(m, n) - 1; for (int len, diag = MAX; diag > 0; --diag) { if (diag > mn) len = mn; else len = diag; for (int i = 0; i < len; ++i) { cout << arr[row][col] << \" \"; if (i + 1 == len) break; // Update row or col value according // to the last increment if (row_inc) ++row, --col; else ++col, --row; } // Update the indexes of row and col variable if (row == 0 || col == m - 1) { if (col == m - 1) ++row; else ++col; row_inc = true; } else if (col == 0 || row == n - 1) { if (row == n - 1) ++col; else ++row; row_inc = false; } }} // Driver codeint main(){ int matrix[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; zigZagMatrix(matrix, 3, 3); return 0;}", "e": 3246, "s": 758, "text": null }, { "code": "/* Java Program to print matrix in Zig-zag pattern*/class GFG { static final int C = 3; // Utility function to print matrix // in zig-zag form static void zigZagMatrix(int arr[][], int n, int m) { int row = 0, col = 0; // Boolean variable that will true if we // need to increment 'row' value otherwise // false- if increment 'col' value boolean row_inc = false; // Print matrix of lower half zig-zag pattern int mn = Math.min(m, n); for (int len = 1; len <= mn; ++len) { for (int i = 0; i < len; ++i) { System.out.print(arr[row][col] + \" \"); if (i + 1 == len) break; // If row_increment value is true // increment row and decrement col // else decrement row and increment // col if (row_inc) { ++row; --col; } else { --row; ++col; } } if (len == mn) break; // Update row or col value according // to the last increment if (row_inc) { ++row; row_inc = false; } else { ++col; row_inc = true; } } // Update the indexes of row and col variable if (row == 0) { if (col == m - 1) ++row; else ++col; row_inc = true; } else { if (row == n - 1) ++col; else ++row; row_inc = false; } // Print the next half zig-zag pattern int MAX = Math.max(m, n) - 1; for (int len, diag = MAX; diag > 0; --diag) { if (diag > mn) len = mn; else len = diag; for (int i = 0; i < len; ++i) { System.out.print(arr[row][col] + \" \"); if (i + 1 == len) break; // Update row or col value according // to the last increment if (row_inc) { ++row; --col; } else { ++col; --row; } } // Update the indexes of row and col variable if (row == 0 || col == m - 1) { if (col == m - 1) ++row; else ++col; row_inc = true; } else if (col == 0 || row == n - 1) { if (row == n - 1) ++col; else ++row; row_inc = false; } } } // Driver code public static void main(String[] args) { int matrix[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; zigZagMatrix(matrix, 3, 3); }}// This code is contributed by Anant Agarwal.", "e": 5659, "s": 3246, "text": null }, { "code": "# Program to print matrix in Zig-zag pattern matrix =[ [ 1, 2, 3,], [ 4, 5, 6 ], [ 7, 8, 9 ], ]rows=3columns=3 solution=[[] for i in range(rows+columns-1)] for i in range(rows): for j in range(columns): sum=i+j if(sum%2 ==0): #add at beginning solution[sum].insert(0,matrix[i][j]) else: #add at end of the list solution[sum].append(matrix[i][j]) # print the solution as it asfor i in solution: for j in i: print(j,end=\" \") ", "e": 6241, "s": 5659, "text": null }, { "code": "// C# Program to print matrix// in Zig-zag patternusing System; class GFG { static int C = 3; // Utility function to print // matrix in zig-zag form static void zigZagMatrix(int[, ] arr, int n, int m) { int row = 0, col = 0; // Boolean variable that will // true if we need to increment // 'row' valueotherwise false- // if increment 'col' value bool row_inc = false; // Print matrix of lower half // zig-zag pattern int mn = Math.Min(m, n); for (int len = 1; len <= mn; ++len) { for (int i = 0; i < len; ++i) { Console.Write(arr[row, col] + \" \"); if (i + 1 == len) break; // If row_increment value is true // increment row and decrement col // else decrement row and increment // col if (row_inc) { ++row; --col; } else { --row; ++col; } } if (len == mn) break; // Update row or col value // according to the last // increment if (row_inc) { ++row; row_inc = false; } else { ++col; row_inc = true; } } // Update the indexes of row // and col variable if (row == 0) { if (col == m - 1) ++row; else ++col; row_inc = true; } else { if (row == n - 1) ++col; else ++row; row_inc = false; } // Print the next half // zig-zag pattern int MAX = Math.Max(m, n) - 1; for (int len, diag = MAX; diag > 0; --diag) { if (diag > mn) len = mn; else len = diag; for (int i = 0; i < len; ++i) { Console.Write(arr[row, col] + \" \"); if (i + 1 == len) break; // Update row or col value // according to the last // increment if (row_inc) { ++row; --col; } else { ++col; --row; } } // Update the indexes of // row and col variable if (row == 0 || col == m - 1) { if (col == m - 1) ++row; else ++col; row_inc = true; } else if (col == 0 || row == n - 1) { if (row == n - 1) ++col; else ++row; row_inc = false; } } } // Driver code public static void Main() { int[, ] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; zigZagMatrix(matrix, 3, 3); }} // This code is contributed by vt_m.", "e": 9488, "s": 6241, "text": null }, { "code": "<?php// PHP Program to print// matrix in Zig-zag pattern$C = 3; // Utility function// to print matrix// in zig-zag formfunction zigZagMatrix($arr, $n, $m){ $row = 0; $col = 0; // Boolean variable that // will true if we need // to increment 'row' // value otherwise false- // if increment 'col' value $row_inc = false; // Print matrix of lower // half zig-zag pattern $mn = min($m, $n); for ($len = 1; $len <= $mn; $len++) { for ($i = 0; $i < $len; $i++) { echo ($arr[$row][$col].\" \"); if ($i + 1 == $len) break; // If row_increment value // is true increment row // and decrement col else // decrement row and // increment col if ($row_inc) { $row++; $col--; } else { $row--; $col++; } } if ($len == $mn) break; // Update row or col // value according // to the last increment if ($row_inc) { ++$row; $row_inc = false; } else { ++$col; $row_inc = true; } } // Update the indexes of // row and col variable if ($row == 0) { if ($col == $m - 1) ++$row; else ++$col; $row_inc = 1; } else { if ($row == $n - 1) ++$col; else ++$row; $row_inc = 0; } // Print the next half // zig-zag pattern $MAX = max($m, $n) - 1; for ($len, $diag = $MAX; $diag > 0; --$diag) { if ($diag > $mn) $len = $mn; else $len = $diag; for ($i = 0; $i < $len; ++$i) { echo($arr[$row][$col] . \" \"); if ($i + 1 == $len) break; // Update row or col // value according to // the last increment if ($row_inc) { ++$row; --$col; } else { ++$col; --$row; } } // Update the indexes of // row and col variable if ($row == 0 || $col == $m - 1) { if ($col == $m - 1) ++$row; else ++$col; $row_inc = true; } else if ($col == 0 || $row == $n - 1) { if ($row == $n - 1) ++$col; else ++$row; $row_inc = false; } }} // Driver code$matrix = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); zigZagMatrix($matrix, 3, 3); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 12374, "s": 9488, "text": null }, { "code": "// Javascript Program to print matrix in Zig-zag patternvar n = 3, m = 3;var a = [[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]];var zigZagMatrix=function(arr, n, m){ var row = 0; var col = 0; // Variable that will be 1 if we // need to increment 'row' value and 0 otherwise // if we need to increment 'col' value var row_inc = 0; // print matrix of lower half zig-zag pattern var mn = Math.min(m, n); for (var len = 1; len <= mn; ++len) { for (var i = 0; i < len; ++i) { console.log(arr[row][col]); console.log(\" \"); if (i + 1 == len) break; // If row_increment value is true // increment row and decrement col // else decrement row and increment col if (row_inc) ++row, --col; else --row, ++col; } if (len == mn) break; // Update row or col value according // to the last increment if (row_inc) ++row, row_inc = false; else ++col, row_inc = true; } // Update the indexes of row and col variable if (row == 0) { if (col == m - 1) ++row; else ++col; row_inc = 1; } else { if (row == n - 1) ++col; else ++row; row_inc = 0; } // Print the next half zig-zag pattern var MAX = Math.max(m, n) - 1; for (var len, diag = MAX; diag > 0; --diag) { if (diag > mn) len = mn; else len = diag; for (var i = 0; i < len; ++i) { console.log(arr[row][col]); console.log(\" \"); if (i + 1 == len) break; // Update row or col value according // to the last increment if (row_inc) ++row, --col; else ++col, --row; } // Update the indexes of row and col variable if (row == 0 || col == m - 1) { if (col == m - 1) ++row; else ++col; row_inc = true; } else if (col == 0 || row == n - 1) { if (row == n - 1) ++col; else ++row; row_inc = false; } }}zigZagMatrix(a, 3, 3); // This code is contributed by Sajal Aggarwal.", "e": 14776, "s": 12374, "text": null }, { "code": null, "e": 14786, "s": 14776, "text": "Output: " }, { "code": null, "e": 14805, "s": 14786, "text": "1 2 4 7 5 3 6 8 9 " }, { "code": null, "e": 14852, "s": 14805, "text": "Time complexity: O(n*m) Auxiliary space: O(1) " }, { "code": null, "e": 14864, "s": 14852, "text": "manishshaw1" }, { "code": null, "e": 14875, "s": 14864, "text": "nidhi_biet" }, { "code": null, "e": 14885, "s": 14875, "text": "19euit177" }, { "code": null, "e": 14902, "s": 14885, "text": "arorakashish0911" }, { "code": null, "e": 14918, "s": 14902, "text": "aggarwalsajal19" }, { "code": null, "e": 14935, "s": 14918, "text": "pattern-printing" }, { "code": null, "e": 14942, "s": 14935, "text": "Matrix" }, { "code": null, "e": 14959, "s": 14942, "text": "pattern-printing" }, { "code": null, "e": 14966, "s": 14959, "text": "Matrix" }, { "code": null, "e": 15064, "s": 14966, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15108, "s": 15064, "text": "Program to find largest element in an array" }, { "code": null, "e": 15143, "s": 15108, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 15174, "s": 15143, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 15198, "s": 15174, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 15245, "s": 15198, "text": "Find the number of islands | Set 1 (Using DFS)" }, { "code": null, "e": 15327, "s": 15245, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" }, { "code": null, "e": 15349, "s": 15327, "text": "The Celebrity Problem" }, { "code": null, "e": 15387, "s": 15349, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 15458, "s": 15387, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
Node.js process.exit() Method
24 Dec, 2021 The process.exit() method is used to end the process which is running at the same time with an exit code in NodeJS. Syntax: process.exit( code ) Parameter: This function accepts single parameter as mentioned above and described below: Code: It can be either 0 or 1. 0 means end the process without any kind of failure and 1 means end the process with some failure. Return value: It does not return any value. As it is the predefined module, so we don’t have to install it in our directory. How to implement in code? Create a file with name index.jsCreate a variable with the name process and require the ‘process’ module in it.Create an infinite loop to check the functionality of .exit(). Create a file with name index.js Create a variable with the name process and require the ‘process’ module in it. Create an infinite loop to check the functionality of .exit(). Case 1: Without using process.exit() method: index.js // Importing process modulevar process = require('process'); var a = 0; // Infinite loopwhile (a == 0) { // Printing statement console.log('GeeksforGeeks'); } Run index.js file using below command: node index.js Output: In the above code, we have created an infinite loop that prints GeeksForGeeks until we have stopped the program manually. Case-II: Using process.exit() method: index.js // Importing process modulevar process = require('process');var a = 0; // Infinite loopwhile (a == 0) { // Printing statement console.log('GeeksForGeeks'); // Terminate the entire process process.exit(0);} Run index.js file using below command: node index.js Output: In the above code, we have used the same code as CASE-I but the only difference is we have used process.exit() function that automatically stops the NodeJS program when there is some problem with the code. In this case, the code prints GeeksForGeeks only for a single time. Reference: https://nodejs.org/api/process.html#process_process_exit_code surinderdawra388 Node.js-Methods Node.js-process-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2021" }, { "code": null, "e": 144, "s": 28, "text": "The process.exit() method is used to end the process which is running at the same time with an exit code in NodeJS." }, { "code": null, "e": 152, "s": 144, "text": "Syntax:" }, { "code": null, "e": 173, "s": 152, "text": "process.exit( code )" }, { "code": null, "e": 264, "s": 173, "text": "Parameter: This function accepts single parameter as mentioned above and described below:" }, { "code": null, "e": 394, "s": 264, "text": "Code: It can be either 0 or 1. 0 means end the process without any kind of failure and 1 means end the process with some failure." }, { "code": null, "e": 438, "s": 394, "text": "Return value: It does not return any value." }, { "code": null, "e": 519, "s": 438, "text": "As it is the predefined module, so we don’t have to install it in our directory." }, { "code": null, "e": 545, "s": 519, "text": "How to implement in code?" }, { "code": null, "e": 719, "s": 545, "text": "Create a file with name index.jsCreate a variable with the name process and require the ‘process’ module in it.Create an infinite loop to check the functionality of .exit()." }, { "code": null, "e": 752, "s": 719, "text": "Create a file with name index.js" }, { "code": null, "e": 832, "s": 752, "text": "Create a variable with the name process and require the ‘process’ module in it." }, { "code": null, "e": 895, "s": 832, "text": "Create an infinite loop to check the functionality of .exit()." }, { "code": null, "e": 940, "s": 895, "text": "Case 1: Without using process.exit() method:" }, { "code": null, "e": 949, "s": 940, "text": "index.js" }, { "code": "// Importing process modulevar process = require('process'); var a = 0; // Infinite loopwhile (a == 0) { // Printing statement console.log('GeeksforGeeks'); }", "e": 1119, "s": 949, "text": null }, { "code": null, "e": 1158, "s": 1119, "text": "Run index.js file using below command:" }, { "code": null, "e": 1172, "s": 1158, "text": "node index.js" }, { "code": null, "e": 1302, "s": 1172, "text": "Output: In the above code, we have created an infinite loop that prints GeeksForGeeks until we have stopped the program manually." }, { "code": null, "e": 1340, "s": 1302, "text": "Case-II: Using process.exit() method:" }, { "code": null, "e": 1349, "s": 1340, "text": "index.js" }, { "code": "// Importing process modulevar process = require('process');var a = 0; // Infinite loopwhile (a == 0) { // Printing statement console.log('GeeksForGeeks'); // Terminate the entire process process.exit(0);}", "e": 1576, "s": 1349, "text": null }, { "code": null, "e": 1615, "s": 1576, "text": "Run index.js file using below command:" }, { "code": null, "e": 1629, "s": 1615, "text": "node index.js" }, { "code": null, "e": 1911, "s": 1629, "text": "Output: In the above code, we have used the same code as CASE-I but the only difference is we have used process.exit() function that automatically stops the NodeJS program when there is some problem with the code. In this case, the code prints GeeksForGeeks only for a single time." }, { "code": null, "e": 1984, "s": 1911, "text": "Reference: https://nodejs.org/api/process.html#process_process_exit_code" }, { "code": null, "e": 2001, "s": 1984, "text": "surinderdawra388" }, { "code": null, "e": 2017, "s": 2001, "text": "Node.js-Methods" }, { "code": null, "e": 2040, "s": 2017, "text": "Node.js-process-module" }, { "code": null, "e": 2047, "s": 2040, "text": "Picked" }, { "code": null, "e": 2055, "s": 2047, "text": "Node.js" }, { "code": null, "e": 2072, "s": 2055, "text": "Web Technologies" } ]
Searching For Characters and Substring in a String in Java
08 Jul, 2022 Strings are a very important aspect from a programming perspective as many questions can be framed out among strings. There arise wide varied sets of concepts and questions that are pivotal to understanding strings. Now over here will be discussing different ways to play with strings where we will be playing with characters with strings and substrings which is a part of input strings with help of inbuilt methods and also by proposing logic listing wide varied ways as follows: Way 1: indexOf(char c) It searches the index of specified characters within a given string. It starts searching from the beginning to the end of the string (from left to right) and returns the corresponding index if found otherwise returns -1. Note: If the given string contains multiple occurrences of a specified character then it returns the index of the only first occurrence of the specified character. Syntax: int indexOf(char c) // Accepts character as argument, Returns index of // the first occurrence of specified character Way 2: lastIndexOf(char c) It starts searching backward from the end of the string and returns the index of specified characters whenever it is encountered. Syntax: public int lastIndexOf(char c) // Accepts character as argument, Returns an // index of the last occurrence specified // character Way 3: indexOf(char c, int indexFrom) It starts searching forward from the specified index in the string and returns the corresponding index when the specified character is encountered otherwise returns -1. Note: The returned index must be greater than or equal to the specified index. Syntax: public int IndexOf(char c, int indexFrom) Parameters: The character to be searched An integer from where searching Return Type: An index of a specified character that appeared at or after the specified index in a forwarding direction. Way 4: lastIndexOf(char c, int fromIndex) It starts searching backward from the specified index in the string. And returns the corresponding index when the specified character is encountered otherwise returns -1. Note: The returned index must be less than or equal to the specified index. Syntax: public int lastIndexOf(char c, int fromIndex) Way 5: charAt(int indexNumber) Returns the character existing at the specified index, indexNumber in the given string. If the specified index number does not exist in the string, the method throws an unchecked exception, StringIndexOutOfBoundsException. Syntax: char charAt(int indexNumber) Example: Java // Java Program to Illustrate to Find a Character// in the String // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // String in which a character to be searched. String str = "GeeksforGeeks is a computer science portal"; // Returns index of first occurrence of character. int firstIndex = str.indexOf('s'); System.out.println("First occurrence of char 's'" + " is found at : " + firstIndex); // Returns index of last occurrence specified // character. int lastIndex = str.lastIndexOf('s'); System.out.println("Last occurrence of char 's' is" + " found at : " + lastIndex); // Index of the first occurrence of specified char // after the specified index if found. int first_in = str.indexOf('s', 10); System.out.println("First occurrence of char 's'" + " after index 10 : " + first_in); int last_in = str.lastIndexOf('s', 20); System.out.println("Last occurrence of char 's'" + " after index 20 is : " + last_in); // gives ASCII value of character at location 20 int char_at = str.charAt(20); System.out.println("Character at location 20: " + char_at); // Note: If we uncomment it will throw // StringIndexOutOfBoundsException // char_at = str.charAt(50); }} First occurrence of char 's' is found at : 4 Last occurrence of char 's' is found at : 28 First occurrence of char 's' after index 10 : 12 Last occurrence of char 's' after index 20 is : 15 Character at location 20: 111 Way 6: Searching Substring in the String The methods used for searching a character in the string which are mentioned above can also be used for searching the substring in the string. Example Java // Java Program to illustrate to Find a Substring// in the String // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // A string in which a substring // is to be searched String str = "GeeksforGeeks is a computer science portal"; // Returns index of first occurrence of substring int firstIndex = str.indexOf("Geeks"); System.out.println("First occurrence of char Geeks" + " is found at : " + firstIndex); // Returns index of last occurrence int lastIndex = str.lastIndexOf("Geeks"); System.out.println( "Last occurrence of char Geeks is" + " found at : " + lastIndex); // Index of the first occurrence // after the specified index if found int first_in = str.indexOf("Geeks", 10); System.out.println("First occurrence of char Geeks" + " after index 10 : " + first_in); int last_in = str.lastIndexOf("Geeks", 20); System.out.println("Last occurrence of char Geeks " + "after index 20 is : " + last_in); }} First occurrence of char Geeks is found at : 0 Last occurrence of char Geeks is found at : 8 First occurrence of char Geeks after index 10 : -1 Last occurrence of char Geeks after index 20 is : 8 Way 7: contains(CharSequence seq): It returns true if the string contains the specified sequence of char values otherwise returns false. Its parameters specify the sequence of characters to be searched and throw NullPointerException if seq is null. Syntax: public boolean contains(CharSequence seq) Note: CharSequence is an interface that is implemented by String class, Therefore we use string as an argument in contains() method. Example Java // Java Program to Illustrate How to Find a Substring// in the String using contains() Method // Importing required classesimport java.io.*;import java.lang.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // String in which substring // to be searched String test = "software"; CharSequence seq = "soft"; boolean bool = test.contains(seq); System.out.println("Found soft?: " + bool); // Returns true substring if found. boolean seqFound = test.contains("war"); System.out.println("Found war? " + seqFound); // Returns true substring if found // otherwise return false boolean sqFound = test.contains("wr"); System.out.println("Found wr?: " + sqFound); }} Found soft?: true Found war? true Found wr?: false Way 8: Matching String Start and End boolean startsWith(String str): Returns true if the string str exists at the starting of the given string, else false. boolean startsWith(String str, int indexNum): Returns true if the string str exists at the starting of the index indexNum in the given string, else false. boolean endsWith(String str): Returns true if the string str exists at the ending of the given string, else false. Example: Java // Java Program to Match ofstart and endof a Substring // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Input string in which substring // is to be searched String str = "GeeksforGeeks is a computer science portal"; // Print and display commands System.out.println(str.startsWith("Geek")); System.out.println(str.startsWith("is", 14)); System.out.println(str.endsWith("port")); }} true true false This article is contributed by Nitsdheerendra. 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. solankimayank karthikchowdaryetukuru1 hardikkoriintern Java-String-Programs Java-Strings Java School Programming Strings Java-Strings Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jul, 2022" }, { "code": null, "e": 535, "s": 53, "text": "Strings are a very important aspect from a programming perspective as many questions can be framed out among strings. There arise wide varied sets of concepts and questions that are pivotal to understanding strings. Now over here will be discussing different ways to play with strings where we will be playing with characters with strings and substrings which is a part of input strings with help of inbuilt methods and also by proposing logic listing wide varied ways as follows: " }, { "code": null, "e": 558, "s": 535, "text": "Way 1: indexOf(char c)" }, { "code": null, "e": 780, "s": 558, "text": "It searches the index of specified characters within a given string. It starts searching from the beginning to the end of the string (from left to right) and returns the corresponding index if found otherwise returns -1. " }, { "code": null, "e": 945, "s": 780, "text": "Note: If the given string contains multiple occurrences of a specified character then it returns the index of the only first occurrence of the specified character. " }, { "code": null, "e": 954, "s": 945, "text": "Syntax: " }, { "code": null, "e": 1074, "s": 954, "text": "int indexOf(char c)\n// Accepts character as argument, Returns index of \n// the first occurrence of specified character " }, { "code": null, "e": 1101, "s": 1074, "text": "Way 2: lastIndexOf(char c)" }, { "code": null, "e": 1232, "s": 1101, "text": "It starts searching backward from the end of the string and returns the index of specified characters whenever it is encountered. " }, { "code": null, "e": 1241, "s": 1232, "text": "Syntax: " }, { "code": null, "e": 1374, "s": 1241, "text": "public int lastIndexOf(char c)\n// Accepts character as argument, Returns an \n// index of the last occurrence specified \n// character" }, { "code": null, "e": 1412, "s": 1374, "text": "Way 3: indexOf(char c, int indexFrom)" }, { "code": null, "e": 1582, "s": 1412, "text": "It starts searching forward from the specified index in the string and returns the corresponding index when the specified character is encountered otherwise returns -1. " }, { "code": null, "e": 1662, "s": 1582, "text": "Note: The returned index must be greater than or equal to the specified index. " }, { "code": null, "e": 1671, "s": 1662, "text": "Syntax: " }, { "code": null, "e": 1713, "s": 1671, "text": "public int IndexOf(char c, int indexFrom)" }, { "code": null, "e": 1726, "s": 1713, "text": "Parameters: " }, { "code": null, "e": 1755, "s": 1726, "text": "The character to be searched" }, { "code": null, "e": 1787, "s": 1755, "text": "An integer from where searching" }, { "code": null, "e": 1907, "s": 1787, "text": "Return Type: An index of a specified character that appeared at or after the specified index in a forwarding direction." }, { "code": null, "e": 1949, "s": 1907, "text": "Way 4: lastIndexOf(char c, int fromIndex)" }, { "code": null, "e": 2121, "s": 1949, "text": "It starts searching backward from the specified index in the string. And returns the corresponding index when the specified character is encountered otherwise returns -1. " }, { "code": null, "e": 2198, "s": 2121, "text": "Note: The returned index must be less than or equal to the specified index. " }, { "code": null, "e": 2207, "s": 2198, "text": "Syntax: " }, { "code": null, "e": 2253, "s": 2207, "text": "public int lastIndexOf(char c, int fromIndex)" }, { "code": null, "e": 2284, "s": 2253, "text": "Way 5: charAt(int indexNumber)" }, { "code": null, "e": 2508, "s": 2284, "text": "Returns the character existing at the specified index, indexNumber in the given string. If the specified index number does not exist in the string, the method throws an unchecked exception, StringIndexOutOfBoundsException. " }, { "code": null, "e": 2516, "s": 2508, "text": "Syntax:" }, { "code": null, "e": 2545, "s": 2516, "text": "char charAt(int indexNumber)" }, { "code": null, "e": 2554, "s": 2545, "text": "Example:" }, { "code": null, "e": 2559, "s": 2554, "text": "Java" }, { "code": "// Java Program to Illustrate to Find a Character// in the String // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // String in which a character to be searched. String str = \"GeeksforGeeks is a computer science portal\"; // Returns index of first occurrence of character. int firstIndex = str.indexOf('s'); System.out.println(\"First occurrence of char 's'\" + \" is found at : \" + firstIndex); // Returns index of last occurrence specified // character. int lastIndex = str.lastIndexOf('s'); System.out.println(\"Last occurrence of char 's' is\" + \" found at : \" + lastIndex); // Index of the first occurrence of specified char // after the specified index if found. int first_in = str.indexOf('s', 10); System.out.println(\"First occurrence of char 's'\" + \" after index 10 : \" + first_in); int last_in = str.lastIndexOf('s', 20); System.out.println(\"Last occurrence of char 's'\" + \" after index 20 is : \" + last_in); // gives ASCII value of character at location 20 int char_at = str.charAt(20); System.out.println(\"Character at location 20: \" + char_at); // Note: If we uncomment it will throw // StringIndexOutOfBoundsException // char_at = str.charAt(50); }}", "e": 4189, "s": 2559, "text": null }, { "code": null, "e": 4409, "s": 4189, "text": "First occurrence of char 's' is found at : 4\nLast occurrence of char 's' is found at : 28\nFirst occurrence of char 's' after index 10 : 12\nLast occurrence of char 's' after index 20 is : 15\nCharacter at location 20: 111" }, { "code": null, "e": 4451, "s": 4409, "text": " Way 6: Searching Substring in the String" }, { "code": null, "e": 4595, "s": 4451, "text": "The methods used for searching a character in the string which are mentioned above can also be used for searching the substring in the string. " }, { "code": null, "e": 4603, "s": 4595, "text": "Example" }, { "code": null, "e": 4608, "s": 4603, "text": "Java" }, { "code": "// Java Program to illustrate to Find a Substring// in the String // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // A string in which a substring // is to be searched String str = \"GeeksforGeeks is a computer science portal\"; // Returns index of first occurrence of substring int firstIndex = str.indexOf(\"Geeks\"); System.out.println(\"First occurrence of char Geeks\" + \" is found at : \" + firstIndex); // Returns index of last occurrence int lastIndex = str.lastIndexOf(\"Geeks\"); System.out.println( \"Last occurrence of char Geeks is\" + \" found at : \" + lastIndex); // Index of the first occurrence // after the specified index if found int first_in = str.indexOf(\"Geeks\", 10); System.out.println(\"First occurrence of char Geeks\" + \" after index 10 : \" + first_in); int last_in = str.lastIndexOf(\"Geeks\", 20); System.out.println(\"Last occurrence of char Geeks \" + \"after index 20 is : \" + last_in); }}", "e": 5911, "s": 4608, "text": null }, { "code": null, "e": 6107, "s": 5911, "text": "First occurrence of char Geeks is found at : 0\nLast occurrence of char Geeks is found at : 8\nFirst occurrence of char Geeks after index 10 : -1\nLast occurrence of char Geeks after index 20 is : 8" }, { "code": null, "e": 6357, "s": 6107, "text": "Way 7: contains(CharSequence seq): It returns true if the string contains the specified sequence of char values otherwise returns false. Its parameters specify the sequence of characters to be searched and throw NullPointerException if seq is null. " }, { "code": null, "e": 6366, "s": 6357, "text": "Syntax: " }, { "code": null, "e": 6408, "s": 6366, "text": "public boolean contains(CharSequence seq)" }, { "code": null, "e": 6542, "s": 6408, "text": "Note: CharSequence is an interface that is implemented by String class, Therefore we use string as an argument in contains() method. " }, { "code": null, "e": 6551, "s": 6542, "text": "Example " }, { "code": null, "e": 6556, "s": 6551, "text": "Java" }, { "code": "// Java Program to Illustrate How to Find a Substring// in the String using contains() Method // Importing required classesimport java.io.*;import java.lang.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // String in which substring // to be searched String test = \"software\"; CharSequence seq = \"soft\"; boolean bool = test.contains(seq); System.out.println(\"Found soft?: \" + bool); // Returns true substring if found. boolean seqFound = test.contains(\"war\"); System.out.println(\"Found war? \" + seqFound); // Returns true substring if found // otherwise return false boolean sqFound = test.contains(\"wr\"); System.out.println(\"Found wr?: \" + sqFound); }}", "e": 7356, "s": 6556, "text": null }, { "code": null, "e": 7407, "s": 7356, "text": "Found soft?: true\nFound war? true\nFound wr?: false" }, { "code": null, "e": 7446, "s": 7407, "text": " Way 8: Matching String Start and End " }, { "code": null, "e": 7565, "s": 7446, "text": "boolean startsWith(String str): Returns true if the string str exists at the starting of the given string, else false." }, { "code": null, "e": 7720, "s": 7565, "text": "boolean startsWith(String str, int indexNum): Returns true if the string str exists at the starting of the index indexNum in the given string, else false." }, { "code": null, "e": 7835, "s": 7720, "text": "boolean endsWith(String str): Returns true if the string str exists at the ending of the given string, else false." }, { "code": null, "e": 7844, "s": 7835, "text": "Example:" }, { "code": null, "e": 7849, "s": 7844, "text": "Java" }, { "code": "// Java Program to Match ofstart and endof a Substring // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Input string in which substring // is to be searched String str = \"GeeksforGeeks is a computer science portal\"; // Print and display commands System.out.println(str.startsWith(\"Geek\")); System.out.println(str.startsWith(\"is\", 14)); System.out.println(str.endsWith(\"port\")); }}", "e": 8393, "s": 7849, "text": null }, { "code": null, "e": 8409, "s": 8393, "text": "true\ntrue\nfalse" }, { "code": null, "e": 8707, "s": 8409, "text": "This article is contributed by Nitsdheerendra. 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": 8721, "s": 8707, "text": "solankimayank" }, { "code": null, "e": 8745, "s": 8721, "text": "karthikchowdaryetukuru1" }, { "code": null, "e": 8762, "s": 8745, "text": "hardikkoriintern" }, { "code": null, "e": 8783, "s": 8762, "text": "Java-String-Programs" }, { "code": null, "e": 8796, "s": 8783, "text": "Java-Strings" }, { "code": null, "e": 8801, "s": 8796, "text": "Java" }, { "code": null, "e": 8820, "s": 8801, "text": "School Programming" }, { "code": null, "e": 8828, "s": 8820, "text": "Strings" }, { "code": null, "e": 8841, "s": 8828, "text": "Java-Strings" }, { "code": null, "e": 8849, "s": 8841, "text": "Strings" }, { "code": null, "e": 8854, "s": 8849, "text": "Java" } ]
get_cookie driver method – Selenium Python
03 Dec, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around get_cookie driver method in Selenium. get_cookie method is used to get a cookie with a specified name. It returns the cookie if found, None if not. Syntax – driver.get_cookie(name) Example – Now one can use get_cookie method as a driver method as below – driver.get("https://www.geeksforgeeks.org/") driver.get_cookie("foo") To demonstrate, get_cookie method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s first add a cookie and then get it. Program – Python3 # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # add_cookie method driverdriver.add_cookie({"name" : "foo", "value" : "bar"}) # get browser cookiedriver.get_cookie("foo") Output – Screenshot after cookie added – Akanksha_Rai Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2020" }, { "code": null, "e": 768, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. " }, { "code": null, "e": 945, "s": 768, "text": "This article revolves around get_cookie driver method in Selenium. get_cookie method is used to get a cookie with a specified name. It returns the cookie if found, None if not." }, { "code": null, "e": 955, "s": 945, "text": "Syntax – " }, { "code": null, "e": 979, "s": 955, "text": "driver.get_cookie(name)" }, { "code": null, "e": 1054, "s": 979, "text": "Example – Now one can use get_cookie method as a driver method as below – " }, { "code": null, "e": 1124, "s": 1054, "text": "driver.get(\"https://www.geeksforgeeks.org/\")\ndriver.get_cookie(\"foo\")" }, { "code": null, "e": 1307, "s": 1124, "text": "To demonstrate, get_cookie method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s first add a cookie and then get it." }, { "code": null, "e": 1318, "s": 1307, "text": "Program – " }, { "code": null, "e": 1326, "s": 1318, "text": "Python3" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # add_cookie method driverdriver.add_cookie({\"name\" : \"foo\", \"value\" : \"bar\"}) # get browser cookiedriver.get_cookie(\"foo\")", "e": 1621, "s": 1326, "text": null }, { "code": null, "e": 1664, "s": 1621, "text": "Output – Screenshot after cookie added – " }, { "code": null, "e": 1679, "s": 1666, "text": "Akanksha_Rai" }, { "code": null, "e": 1695, "s": 1679, "text": "Python-selenium" }, { "code": null, "e": 1704, "s": 1695, "text": "selenium" }, { "code": null, "e": 1711, "s": 1704, "text": "Python" }, { "code": null, "e": 1809, "s": 1711, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1827, "s": 1809, "text": "Python Dictionary" }, { "code": null, "e": 1869, "s": 1827, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1891, "s": 1869, "text": "Enumerate() in Python" }, { "code": null, "e": 1926, "s": 1891, "text": "Read a file line by line in Python" }, { "code": null, "e": 1958, "s": 1926, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1984, "s": 1958, "text": "Python String | replace()" }, { "code": null, "e": 2013, "s": 1984, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2040, "s": 2013, "text": "Python Classes and Objects" }, { "code": null, "e": 2061, "s": 2040, "text": "Python OOPs Concepts" } ]
Collectors toSet() in Java with Examples
06 Dec, 2018 Collectors toSet() returns a Collector that accumulates the input elements into a new Set. There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned. This is an unordered Collector i.e, the collection operation does not commit to preserving the encounter order of input elements. Syntax: public static <T> Collector<T, ?, Set<T>> toSet() where: T: The type of the input elements. 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. Set: A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. Return Value: A Collector which collects all the input elements into a Set. Below are the examples to illustrate toSet() method: Example 1: // Java code to show the implementation of// Collectors toSet() function import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a Stream of strings Stream<String> s = Stream.of("Geeks", "for", "GeeksforGeeks", "Geeks Classes"); // using Collectors toSet() function Set<String> mySet = s.collect(Collectors.toSet()); // printing the elements System.out.println(mySet); }} [Geeks Classes, GeeksforGeeks, Geeks, for] Example 2: // Java code to show the implementation of// Collectors toSet() function import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a Stream of strings Stream<String> s = Stream.of("1", "2", "3", "4"); // using Collectors toSet() function Set<String> mySet = s.collect(Collectors.toSet()); // printing the elements System.out.println(mySet); }} [1, 2, 3, 4] 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.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Dec, 2018" }, { "code": null, "e": 377, "s": 52, "text": "Collectors toSet() returns a Collector that accumulates the input elements into a new Set. There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned. This is an unordered Collector i.e, the collection operation does not commit to preserving the encounter order of input elements." }, { "code": null, "e": 385, "s": 377, "text": "Syntax:" }, { "code": null, "e": 436, "s": 385, "text": "public static <T> Collector<T, ?, Set<T>> toSet()\n" }, { "code": null, "e": 443, "s": 436, "text": "where:" }, { "code": null, "e": 478, "s": 443, "text": "T: The type of the input elements." }, { "code": null, "e": 961, "s": 478, "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": 1019, "s": 961, "text": "T: The type of input elements to the reduction operation." }, { "code": null, "e": 1080, "s": 1019, "text": "A: The mutable accumulation type of the reduction operation." }, { "code": null, "e": 1127, "s": 1080, "text": "R: The result type of the reduction operation." }, { "code": null, "e": 1295, "s": 1127, "text": "Set: A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element." }, { "code": null, "e": 1371, "s": 1295, "text": "Return Value: A Collector which collects all the input elements into a Set." }, { "code": null, "e": 1424, "s": 1371, "text": "Below are the examples to illustrate toSet() method:" }, { "code": null, "e": 1435, "s": 1424, "text": "Example 1:" }, { "code": "// Java code to show the implementation of// Collectors toSet() function import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a Stream of strings Stream<String> s = Stream.of(\"Geeks\", \"for\", \"GeeksforGeeks\", \"Geeks Classes\"); // using Collectors toSet() function Set<String> mySet = s.collect(Collectors.toSet()); // printing the elements System.out.println(mySet); }}", "e": 2089, "s": 1435, "text": null }, { "code": null, "e": 2133, "s": 2089, "text": "[Geeks Classes, GeeksforGeeks, Geeks, for]\n" }, { "code": null, "e": 2144, "s": 2133, "text": "Example 2:" }, { "code": "// Java code to show the implementation of// Collectors toSet() function import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // creating a Stream of strings Stream<String> s = Stream.of(\"1\", \"2\", \"3\", \"4\"); // using Collectors toSet() function Set<String> mySet = s.collect(Collectors.toSet()); // printing the elements System.out.println(mySet); }}", "e": 2662, "s": 2144, "text": null }, { "code": null, "e": 2676, "s": 2662, "text": "[1, 2, 3, 4]\n" }, { "code": null, "e": 2696, "s": 2676, "text": "Java - util package" }, { "code": null, "e": 2712, "s": 2696, "text": "Java-Collectors" }, { "code": null, "e": 2727, "s": 2712, "text": "Java-Functions" }, { "code": null, "e": 2739, "s": 2727, "text": "java-stream" }, { "code": null, "e": 2762, "s": 2739, "text": "Java-Stream-Collectors" }, { "code": null, "e": 2767, "s": 2762, "text": "Java" }, { "code": null, "e": 2772, "s": 2767, "text": "Java" } ]
How to remove HTML tags with RegExp in JavaScript?
06 Sep, 2019 Here, the task is to remove the HTML tags from the string. Here string contains a part of the document and we need to extract only the text part from it. Here we are going to do that with the help of JavaScript. Approach: Take the string in a variable. Anything between the less than symbol and the greater than symbol is removed from the string by the RegExp. Finally we will get the text. Example 1: This example using the approach defined above. <!DOCTYPE HTML><html> <head> <title> How to remove HTML tags with RegExp in JavaScript? </title></head> <body id="body" style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var str2 = '<p> GeeksForGeeks </p>'; // same as the str2. var str1 = "< p > GeeksForGeeks < /p >"; up.innerHTML = "Click on button to remove the "+ "HTML tags from the string.<br>String = '" + str1 + "'"; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { var regex = /( |<([^>]+)>)/ig; down.innerHTML = str2.replace(regex, ""); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example using the approach defined above but by a different RegExp. <!DOCTYPE HTML><html> <head> <title> How to remove HTML tags with RegExp in JavaScript? </title></head> <body id="body" style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var str2 = '<p> GeeksForGeeks </p>'; // same as the str2. var str1 = "< p > GeeksForGeeks < /p >"; up.innerHTML = "Click on button to remove the HTML"+ " tags from the string.<br>String = '" + str1 + "'"; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { var regex = /(<([^>]+)>)/ig; down.innerHTML = str2.replace(regex, ""); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Sep, 2019" }, { "code": null, "e": 240, "s": 28, "text": "Here, the task is to remove the HTML tags from the string. Here string contains a part of the document and we need to extract only the text part from it. Here we are going to do that with the help of JavaScript." }, { "code": null, "e": 250, "s": 240, "text": "Approach:" }, { "code": null, "e": 281, "s": 250, "text": "Take the string in a variable." }, { "code": null, "e": 389, "s": 281, "text": "Anything between the less than symbol and the greater than symbol is removed from the string by the RegExp." }, { "code": null, "e": 419, "s": 389, "text": "Finally we will get the text." }, { "code": null, "e": 477, "s": 419, "text": "Example 1: This example using the approach defined above." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to remove HTML tags with RegExp in JavaScript? </title></head> <body id=\"body\" style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var str2 = '<p> GeeksForGeeks </p>'; // same as the str2. var str1 = \"< p > GeeksForGeeks < /p >\"; up.innerHTML = \"Click on button to remove the \"+ \"HTML tags from the string.<br>String = '\" + str1 + \"'\"; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { var regex = /( |<([^>]+)>)/ig; down.innerHTML = str2.replace(regex, \"\"); } </script></body> </html>", "e": 1517, "s": 477, "text": null }, { "code": null, "e": 1525, "s": 1517, "text": "Output:" }, { "code": null, "e": 1556, "s": 1525, "text": "Before clicking on the button:" }, { "code": null, "e": 1586, "s": 1556, "text": "After clicking on the button:" }, { "code": null, "e": 1670, "s": 1586, "text": "Example 2: This example using the approach defined above but by a different RegExp." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to remove HTML tags with RegExp in JavaScript? </title></head> <body id=\"body\" style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var str2 = '<p> GeeksForGeeks </p>'; // same as the str2. var str1 = \"< p > GeeksForGeeks < /p >\"; up.innerHTML = \"Click on button to remove the HTML\"+ \" tags from the string.<br>String = '\" + str1 + \"'\"; var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { var regex = /(<([^>]+)>)/ig; down.innerHTML = str2.replace(regex, \"\"); } </script></body> </html>", "e": 2716, "s": 1670, "text": null }, { "code": null, "e": 2724, "s": 2716, "text": "Output:" }, { "code": null, "e": 2755, "s": 2724, "text": "Before clicking on the button:" }, { "code": null, "e": 2785, "s": 2755, "text": "After clicking on the button:" }, { "code": null, "e": 2801, "s": 2785, "text": "JavaScript-Misc" }, { "code": null, "e": 2812, "s": 2801, "text": "JavaScript" }, { "code": null, "e": 2829, "s": 2812, "text": "Web Technologies" }, { "code": null, "e": 2856, "s": 2829, "text": "Web technologies Questions" } ]
Conversion of S-R Flip-Flop into D Flip-Flop
28 Apr, 2020 Prerequisite – Flip-flop 1. S-R Flip-Flop :S-R flip-flop is similar to S-R latch expect clock signal and two AND gates. The circuit responds to the positive edge of clock pulse to the inputs S and R. 2. D Flip-Flop :D Flip-Flop is a modified SR flip-flop which has an additional inverter. It prevents the inputs from becoming the same value. Conversion of S-R Flip-Flop into D Flip-Flop : Step-1:We construct the characteristic table of D flip-flop and excitation table of S-R flip-flop. Step-2:Using the K-map we find the boolean expression of S and R in terms of D.S = D R = D' S = D R = D' Step-3:We construct the circuit diagram of the conversion of S-R flip-flop into D flip-flop. Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Apr, 2020" }, { "code": null, "e": 78, "s": 53, "text": "Prerequisite – Flip-flop" }, { "code": null, "e": 253, "s": 78, "text": "1. S-R Flip-Flop :S-R flip-flop is similar to S-R latch expect clock signal and two AND gates. The circuit responds to the positive edge of clock pulse to the inputs S and R." }, { "code": null, "e": 395, "s": 253, "text": "2. D Flip-Flop :D Flip-Flop is a modified SR flip-flop which has an additional inverter. It prevents the inputs from becoming the same value." }, { "code": null, "e": 442, "s": 395, "text": "Conversion of S-R Flip-Flop into D Flip-Flop :" }, { "code": null, "e": 541, "s": 442, "text": "Step-1:We construct the characteristic table of D flip-flop and excitation table of S-R flip-flop." }, { "code": null, "e": 634, "s": 541, "text": "Step-2:Using the K-map we find the boolean expression of S and R in terms of D.S = D\nR = D' " }, { "code": null, "e": 648, "s": 634, "text": "S = D\nR = D' " }, { "code": null, "e": 741, "s": 648, "text": "Step-3:We construct the circuit diagram of the conversion of S-R flip-flop into D flip-flop." }, { "code": null, "e": 776, "s": 741, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 784, "s": 776, "text": "GATE CS" } ]
Find size of a list in Python
12 Nov, 2018 In Python, List is a collection data-type which is ordered and changeable. A list can have duplicate entry as well. Here, the task is find the number of entries in a list. See the examples below. Examples: Input : a = [1, 2, 3, 1, 2, 3] Output : 6 Count the number of entries in the list a. Input : a = [] Output : 0 The idea is to use len() in Python # Python program to demonstrate working# of len()a = []a.append("Hello")a.append("Geeks")a.append("For")a.append("Geeks")print("The length of list is: ", len(a)) The length of list is: 4 Example 2: # Python program to demonstrate working# of len()n = len([10, 20, 30])print("The length of list is: ", n) The length of list is: 3 How does len() work?len() works in O(1) time as list is an object and has a member to store its size. Below is description of len() from Python docs. Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set). How to check if a list is empty in Python Picked python-list Technical Scripter 2018 Python Technical Scripter python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Nov, 2018" }, { "code": null, "e": 249, "s": 53, "text": "In Python, List is a collection data-type which is ordered and changeable. A list can have duplicate entry as well. Here, the task is find the number of entries in a list. See the examples below." }, { "code": null, "e": 259, "s": 249, "text": "Examples:" }, { "code": null, "e": 372, "s": 259, "text": "Input : a = [1, 2, 3, 1, 2, 3]\nOutput : 6\nCount the number of entries in the list a.\n\nInput : a = []\nOutput : 0\n" }, { "code": null, "e": 407, "s": 372, "text": "The idea is to use len() in Python" }, { "code": "# Python program to demonstrate working# of len()a = []a.append(\"Hello\")a.append(\"Geeks\")a.append(\"For\")a.append(\"Geeks\")print(\"The length of list is: \", len(a))", "e": 569, "s": 407, "text": null }, { "code": null, "e": 596, "s": 569, "text": "The length of list is: 4\n" }, { "code": null, "e": 607, "s": 596, "text": "Example 2:" }, { "code": "# Python program to demonstrate working# of len()n = len([10, 20, 30])print(\"The length of list is: \", n)", "e": 713, "s": 607, "text": null }, { "code": null, "e": 740, "s": 713, "text": "The length of list is: 3\n" }, { "code": null, "e": 890, "s": 740, "text": "How does len() work?len() works in O(1) time as list is an object and has a member to store its size. Below is description of len() from Python docs." }, { "code": null, "e": 1084, "s": 890, "text": "Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set)." }, { "code": null, "e": 1126, "s": 1084, "text": "How to check if a list is empty in Python" }, { "code": null, "e": 1133, "s": 1126, "text": "Picked" }, { "code": null, "e": 1145, "s": 1133, "text": "python-list" }, { "code": null, "e": 1169, "s": 1145, "text": "Technical Scripter 2018" }, { "code": null, "e": 1176, "s": 1169, "text": "Python" }, { "code": null, "e": 1195, "s": 1176, "text": "Technical Scripter" }, { "code": null, "e": 1207, "s": 1195, "text": "python-list" } ]
Python | Pandas Series.rolling()
07 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.rolling() function is a very useful function. It Provides rolling window calculations over the underlying data in the given Series object. Syntax: Series.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None) Parameter :window : Size of the moving windowmin_periods : Minimum number of observations in window required to have a valuecenter : Set the labels at the center of the window.win_type : Provide a window type.on : str, optionalaxis : int or str, default 0closed : Make the interval closed on the ‘right’, ‘left’, ‘both’ or ‘neither’ endpoints. Returns : a Window or Rolling sub-classed for the particular operation Example #1: Use Series.rolling() function to find the rolling window sum of the underlying data for the given Series object. The size of the rolling window should be 2 and the weightage of each element should be same. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.rolling() function to find the sum of the underlying data having a window size of 2. # Find sum over a window size of 2result = sr.rolling(2).sum() # Print the returned Series objectprint(result) Output :As we can see in the output, the Series.rolling() function has successfully returned a series object having found the sum of the underlying data over a window size of 2. Notice the first value is a missing value as there was no element previous to it so the sum could not be performed. Example #2: Use Series.rolling() function to find the rolling window sum of the underlying data for the given Series object. The size of the rolling window should be 2 and the rolling window type should be ‘triang’. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.rolling() function to find the sum of the underlying data having a window size of 2. # Find sum over a window size of 2# We have also provided the window typeresult = sr.rolling(2, win_type ='triang').sum() # Print the returned Series objectprint(result) Output : As we can see in the output, the Series.rolling() function has successfully returned a series object having found the sum of the underlying data over a window size of 2. Notice the first value is a missing value as there was no element previous to it so the sum could not be performed. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python Different ways to create Pandas Dataframe How to Install PIP on Windows ? *args and **kwargs in Python Python OOPs Concepts Python Classes and Objects Introduction To PYTHON Create a Pandas DataFrame from Lists Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Feb, 2019" }, { "code": null, "e": 284, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 437, "s": 284, "text": "Pandas Series.rolling() function is a very useful function. It Provides rolling window calculations over the underlying data in the given Series object." }, { "code": null, "e": 545, "s": 437, "text": "Syntax: Series.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None)" }, { "code": null, "e": 889, "s": 545, "text": "Parameter :window : Size of the moving windowmin_periods : Minimum number of observations in window required to have a valuecenter : Set the labels at the center of the window.win_type : Provide a window type.on : str, optionalaxis : int or str, default 0closed : Make the interval closed on the ‘right’, ‘left’, ‘both’ or ‘neither’ endpoints." }, { "code": null, "e": 960, "s": 889, "text": "Returns : a Window or Rolling sub-classed for the particular operation" }, { "code": null, "e": 1178, "s": 960, "text": "Example #1: Use Series.rolling() function to find the rolling window sum of the underlying data for the given Series object. The size of the rolling window should be 2 and the weightage of each element should be same." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 1434, "s": 1178, "text": null }, { "code": null, "e": 1443, "s": 1434, "text": "Output :" }, { "code": null, "e": 1551, "s": 1443, "text": "Now we will use Series.rolling() function to find the sum of the underlying data having a window size of 2." }, { "code": "# Find sum over a window size of 2result = sr.rolling(2).sum() # Print the returned Series objectprint(result)", "e": 1663, "s": 1551, "text": null }, { "code": null, "e": 2173, "s": 1663, "text": "Output :As we can see in the output, the Series.rolling() function has successfully returned a series object having found the sum of the underlying data over a window size of 2. Notice the first value is a missing value as there was no element previous to it so the sum could not be performed. Example #2: Use Series.rolling() function to find the rolling window sum of the underlying data for the given Series object. The size of the rolling window should be 2 and the rolling window type should be ‘triang’." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 2429, "s": 2173, "text": null }, { "code": null, "e": 2438, "s": 2429, "text": "Output :" }, { "code": null, "e": 2546, "s": 2438, "text": "Now we will use Series.rolling() function to find the sum of the underlying data having a window size of 2." }, { "code": "# Find sum over a window size of 2# We have also provided the window typeresult = sr.rolling(2, win_type ='triang').sum() # Print the returned Series objectprint(result)", "e": 2717, "s": 2546, "text": null }, { "code": null, "e": 2726, "s": 2717, "text": "Output :" }, { "code": null, "e": 3012, "s": 2726, "text": "As we can see in the output, the Series.rolling() function has successfully returned a series object having found the sum of the underlying data over a window size of 2. Notice the first value is a missing value as there was no element previous to it so the sum could not be performed." }, { "code": null, "e": 3033, "s": 3012, "text": "Python pandas-series" }, { "code": null, "e": 3062, "s": 3033, "text": "Python pandas-series-methods" }, { "code": null, "e": 3076, "s": 3062, "text": "Python-pandas" }, { "code": null, "e": 3083, "s": 3076, "text": "Python" }, { "code": null, "e": 3181, "s": 3083, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3199, "s": 3181, "text": "Python Dictionary" }, { "code": null, "e": 3221, "s": 3199, "text": "Enumerate() in Python" }, { "code": null, "e": 3263, "s": 3221, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3295, "s": 3263, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3324, "s": 3295, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3345, "s": 3324, "text": "Python OOPs Concepts" }, { "code": null, "e": 3372, "s": 3345, "text": "Python Classes and Objects" }, { "code": null, "e": 3395, "s": 3372, "text": "Introduction To PYTHON" }, { "code": null, "e": 3432, "s": 3395, "text": "Create a Pandas DataFrame from Lists" } ]
Angular-JS ng-repeat Directive - GeeksforGeeks
09 Aug, 2019 Angular-JS ng-repeat directive is a handy tool to repeat a set of HTML code for a number of times or once per item in a collection of items. ng-repeat is mostly used on arrays and objects.ng-repeat is similar to a loop that we have in C, C++ or other languages but technically it instantiates a template(normally a set of HTML structures) for each element in a collection that we are accessing. Angular maintains a $index variable as a key to the element which is currently being accessed and a user can also access this variable. Syntax : <div ng-repeat="keyName in MyObjectName "> {{keyName}} </div> Here “MyObjectName” is a collection that can be an object or an array and you can access each value inside it using a “keyName”. Example 1 Create an app.js file for the app.var app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.names = ['Adam','Steve','George','James','Armin']; console.log($scope.names);});Line 1- Created an app module named “myApp” with no dependencies.Line 3- Main controller for our application.Line 4- Array of strings “names”.Create index.html page<!DOCTYPE html><html ng-app="myApp"><head> <title>Angular ng-repeat</title> <script> type="text/javascript" src="jquery-3.2.1.min.js"> </script> <script> type="text/javascript" src="angular.js"></script> <script> type="text/javascript" src="app.js"></script></head><body ng-controller="MainCtrl"> <h2>Here is the name list</h2> <ul> <li ng-repeat="name in names"> {{name}} </li> </ul></body></html> Line 5- Include all the dependencies like jquery, angular-js and app.js fileLine 12- Use ng-repeat directive to get one name from names array at a time and display it.Output : Create an app.js file for the app.var app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.names = ['Adam','Steve','George','James','Armin']; console.log($scope.names);});Line 1- Created an app module named “myApp” with no dependencies.Line 3- Main controller for our application.Line 4- Array of strings “names”. var app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.names = ['Adam','Steve','George','James','Armin']; console.log($scope.names);}); Line 1- Created an app module named “myApp” with no dependencies.Line 3- Main controller for our application.Line 4- Array of strings “names”. Create index.html page<!DOCTYPE html><html ng-app="myApp"><head> <title>Angular ng-repeat</title> <script> type="text/javascript" src="jquery-3.2.1.min.js"> </script> <script> type="text/javascript" src="angular.js"></script> <script> type="text/javascript" src="app.js"></script></head><body ng-controller="MainCtrl"> <h2>Here is the name list</h2> <ul> <li ng-repeat="name in names"> {{name}} </li> </ul></body></html> Line 5- Include all the dependencies like jquery, angular-js and app.js fileLine 12- Use ng-repeat directive to get one name from names array at a time and display it. <!DOCTYPE html><html ng-app="myApp"><head> <title>Angular ng-repeat</title> <script> type="text/javascript" src="jquery-3.2.1.min.js"> </script> <script> type="text/javascript" src="angular.js"></script> <script> type="text/javascript" src="app.js"></script></head><body ng-controller="MainCtrl"> <h2>Here is the name list</h2> <ul> <li ng-repeat="name in names"> {{name}} </li> </ul></body></html> Line 5- Include all the dependencies like jquery, angular-js and app.js fileLine 12- Use ng-repeat directive to get one name from names array at a time and display it. Output : Example 2app.js filevar app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.strings= ['Geeks','For','Geeks']; console.log($scope.strings);});We have a list of three strings.index.html<!DOCTYPE html><html ng-app="myApp"><head> <title>Angular ng-repeat</title> <script> type="text/javascript" src="jquery-3.2.1.min.js"> </script> <script> type="text/javascript" src="angular.js"></script> <script> type="text/javascript" src="app.js"></script></head><body ng-controller="MainCtrl"> <h2>Here is the string list</h2> <ul> <li ng-repeat="s in strings> {{name}} </li> </ul></body></html> Note-“track by $index” is used here because there are duplicate entries in our list i.e. “Geeks”. Duplicate keys are not allowed because AngularJS uses keys to associate DOM nodes with items. “track by $index”, will cause the items to be keyed by their position in the array instead of their valueOutput :Applications:ng-repeat can be used to iterate through an array which requires less lines of code than the usual javascript method.Filters can be used with ng-repeat to create an easy to implement search bar.Referenceshttps://angularjs.org/https://docs.angularjs.org/api/ng/directive/ngRepeathttps://docs.angularjs.org/error/ngRepeat/dupesMy Personal Notes arrow_drop_upSave app.js filevar app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.strings= ['Geeks','For','Geeks']; console.log($scope.strings);}); var app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.strings= ['Geeks','For','Geeks']; console.log($scope.strings);}); We have a list of three strings.index.html<!DOCTYPE html><html ng-app="myApp"><head> <title>Angular ng-repeat</title> <script> type="text/javascript" src="jquery-3.2.1.min.js"> </script> <script> type="text/javascript" src="angular.js"></script> <script> type="text/javascript" src="app.js"></script></head><body ng-controller="MainCtrl"> <h2>Here is the string list</h2> <ul> <li ng-repeat="s in strings> {{name}} </li> </ul></body></html> Note-“track by $index” is used here because there are duplicate entries in our list i.e. “Geeks”. Duplicate keys are not allowed because AngularJS uses keys to associate DOM nodes with items. “track by $index”, will cause the items to be keyed by their position in the array instead of their value index.html <!DOCTYPE html><html ng-app="myApp"><head> <title>Angular ng-repeat</title> <script> type="text/javascript" src="jquery-3.2.1.min.js"> </script> <script> type="text/javascript" src="angular.js"></script> <script> type="text/javascript" src="app.js"></script></head><body ng-controller="MainCtrl"> <h2>Here is the string list</h2> <ul> <li ng-repeat="s in strings> {{name}} </li> </ul></body></html> Note-“track by $index” is used here because there are duplicate entries in our list i.e. “Geeks”. Duplicate keys are not allowed because AngularJS uses keys to associate DOM nodes with items. “track by $index”, will cause the items to be keyed by their position in the array instead of their value Output :Applications:ng-repeat can be used to iterate through an array which requires less lines of code than the usual javascript method.Filters can be used with ng-repeat to create an easy to implement search bar.Referenceshttps://angularjs.org/https://docs.angularjs.org/api/ng/directive/ngRepeathttps://docs.angularjs.org/error/ngRepeat/dupesMy Personal Notes arrow_drop_upSave Applications: ng-repeat can be used to iterate through an array which requires less lines of code than the usual javascript method.Filters can be used with ng-repeat to create an easy to implement search bar. ng-repeat can be used to iterate through an array which requires less lines of code than the usual javascript method. Filters can be used with ng-repeat to create an easy to implement search bar. References https://angularjs.org/ https://docs.angularjs.org/api/ng/directive/ngRepeat https://docs.angularjs.org/error/ngRepeat/dupes mayank5326 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 Top 10 Angular Libraries For Web Developers Convert a string to an integer in JavaScript How to Insert Form Data into Database using PHP ? Client-Server Model Set the value of an input field in JavaScript Differences between Functional Components and Class Components in React How to fetch data from an API in ReactJS ? How to use <mat-chip-list> and <mat-chip> in Angular Material ? How do Web Servers work?
[ { "code": null, "e": 24525, "s": 24497, "text": "\n09 Aug, 2019" }, { "code": null, "e": 25056, "s": 24525, "text": "Angular-JS ng-repeat directive is a handy tool to repeat a set of HTML code for a number of times or once per item in a collection of items. ng-repeat is mostly used on arrays and objects.ng-repeat is similar to a loop that we have in C, C++ or other languages but technically it instantiates a template(normally a set of HTML structures) for each element in a collection that we are accessing. Angular maintains a $index variable as a key to the element which is currently being accessed and a user can also access this variable." }, { "code": null, "e": 25065, "s": 25056, "text": "Syntax :" }, { "code": null, "e": 25130, "s": 25065, "text": "<div ng-repeat=\"keyName in MyObjectName \">\n {{keyName}}\n</div>\n" }, { "code": null, "e": 25259, "s": 25130, "text": "Here “MyObjectName” is a collection that can be an object or an array and you can access each value inside it using a “keyName”." }, { "code": null, "e": 25269, "s": 25259, "text": "Example 1" }, { "code": null, "e": 26325, "s": 25269, "text": "Create an app.js file for the app.var app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.names = ['Adam','Steve','George','James','Armin']; console.log($scope.names);});Line 1- Created an app module named “myApp” with no dependencies.Line 3- Main controller for our application.Line 4- Array of strings “names”.Create index.html page<!DOCTYPE html><html ng-app=\"myApp\"><head> <title>Angular ng-repeat</title> <script> type=\"text/javascript\" src=\"jquery-3.2.1.min.js\"> </script> <script> type=\"text/javascript\" src=\"angular.js\"></script> <script> type=\"text/javascript\" src=\"app.js\"></script></head><body ng-controller=\"MainCtrl\"> <h2>Here is the name list</h2> <ul> <li ng-repeat=\"name in names\"> {{name}} </li> </ul></body></html> Line 5- Include all the dependencies like jquery, angular-js and app.js fileLine 12- Use ng-repeat directive to get one name from names array at a time and display it.Output :" }, { "code": null, "e": 26679, "s": 26325, "text": "Create an app.js file for the app.var app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.names = ['Adam','Steve','George','James','Armin']; console.log($scope.names);});Line 1- Created an app module named “myApp” with no dependencies.Line 3- Main controller for our application.Line 4- Array of strings “names”." }, { "code": "var app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.names = ['Adam','Steve','George','James','Armin']; console.log($scope.names);});", "e": 26857, "s": 26679, "text": null }, { "code": null, "e": 27000, "s": 26857, "text": "Line 1- Created an app module named “myApp” with no dependencies.Line 3- Main controller for our application.Line 4- Array of strings “names”." }, { "code": null, "e": 27695, "s": 27000, "text": "Create index.html page<!DOCTYPE html><html ng-app=\"myApp\"><head> <title>Angular ng-repeat</title> <script> type=\"text/javascript\" src=\"jquery-3.2.1.min.js\"> </script> <script> type=\"text/javascript\" src=\"angular.js\"></script> <script> type=\"text/javascript\" src=\"app.js\"></script></head><body ng-controller=\"MainCtrl\"> <h2>Here is the name list</h2> <ul> <li ng-repeat=\"name in names\"> {{name}} </li> </ul></body></html> Line 5- Include all the dependencies like jquery, angular-js and app.js fileLine 12- Use ng-repeat directive to get one name from names array at a time and display it." }, { "code": "<!DOCTYPE html><html ng-app=\"myApp\"><head> <title>Angular ng-repeat</title> <script> type=\"text/javascript\" src=\"jquery-3.2.1.min.js\"> </script> <script> type=\"text/javascript\" src=\"angular.js\"></script> <script> type=\"text/javascript\" src=\"app.js\"></script></head><body ng-controller=\"MainCtrl\"> <h2>Here is the name list</h2> <ul> <li ng-repeat=\"name in names\"> {{name}} </li> </ul></body></html> ", "e": 28201, "s": 27695, "text": null }, { "code": null, "e": 28369, "s": 28201, "text": "Line 5- Include all the dependencies like jquery, angular-js and app.js fileLine 12- Use ng-repeat directive to get one name from names array at a time and display it." }, { "code": null, "e": 28378, "s": 28369, "text": "Output :" }, { "code": null, "e": 29786, "s": 28378, "text": "Example 2app.js filevar app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.strings= ['Geeks','For','Geeks']; console.log($scope.strings);});We have a list of three strings.index.html<!DOCTYPE html><html ng-app=\"myApp\"><head> <title>Angular ng-repeat</title> <script> type=\"text/javascript\" src=\"jquery-3.2.1.min.js\"> </script> <script> type=\"text/javascript\" src=\"angular.js\"></script> <script> type=\"text/javascript\" src=\"app.js\"></script></head><body ng-controller=\"MainCtrl\"> <h2>Here is the string list</h2> <ul> <li ng-repeat=\"s in strings> {{name}} </li> </ul></body></html> Note-“track by $index” is used here because there are duplicate entries in our list i.e. “Geeks”. Duplicate keys are not allowed because AngularJS uses keys to associate DOM nodes with items. “track by $index”, will cause the items to be keyed by their position in the array instead of their valueOutput :Applications:ng-repeat can be used to iterate through an array which requires less lines of code than the usual javascript method.Filters can be used with ng-repeat to create an easy to implement search bar.Referenceshttps://angularjs.org/https://docs.angularjs.org/api/ng/directive/ngRepeathttps://docs.angularjs.org/error/ngRepeat/dupesMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29960, "s": 29786, "text": "app.js filevar app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.strings= ['Geeks','For','Geeks']; console.log($scope.strings);});" }, { "code": "var app = angular.module('myApp',[]); app.controller('MainCtrl', function($scope){ $scope.strings= ['Geeks','For','Geeks']; console.log($scope.strings);});", "e": 30123, "s": 29960, "text": null }, { "code": null, "e": 30968, "s": 30123, "text": "We have a list of three strings.index.html<!DOCTYPE html><html ng-app=\"myApp\"><head> <title>Angular ng-repeat</title> <script> type=\"text/javascript\" src=\"jquery-3.2.1.min.js\"> </script> <script> type=\"text/javascript\" src=\"angular.js\"></script> <script> type=\"text/javascript\" src=\"app.js\"></script></head><body ng-controller=\"MainCtrl\"> <h2>Here is the string list</h2> <ul> <li ng-repeat=\"s in strings> {{name}} </li> </ul></body></html> Note-“track by $index” is used here because there are duplicate entries in our list i.e. “Geeks”. Duplicate keys are not allowed because AngularJS uses keys to associate DOM nodes with items. “track by $index”, will cause the items to be keyed by their position in the array instead of their value" }, { "code": null, "e": 30979, "s": 30968, "text": "index.html" }, { "code": "<!DOCTYPE html><html ng-app=\"myApp\"><head> <title>Angular ng-repeat</title> <script> type=\"text/javascript\" src=\"jquery-3.2.1.min.js\"> </script> <script> type=\"text/javascript\" src=\"angular.js\"></script> <script> type=\"text/javascript\" src=\"app.js\"></script></head><body ng-controller=\"MainCtrl\"> <h2>Here is the string list</h2> <ul> <li ng-repeat=\"s in strings> {{name}} </li> </ul></body></html> ", "e": 31485, "s": 30979, "text": null }, { "code": null, "e": 31783, "s": 31485, "text": "Note-“track by $index” is used here because there are duplicate entries in our list i.e. “Geeks”. Duplicate keys are not allowed because AngularJS uses keys to associate DOM nodes with items. “track by $index”, will cause the items to be keyed by their position in the array instead of their value" }, { "code": null, "e": 32165, "s": 31783, "text": "Output :Applications:ng-repeat can be used to iterate through an array which requires less lines of code than the usual javascript method.Filters can be used with ng-repeat to create an easy to implement search bar.Referenceshttps://angularjs.org/https://docs.angularjs.org/api/ng/directive/ngRepeathttps://docs.angularjs.org/error/ngRepeat/dupesMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 32179, "s": 32165, "text": "Applications:" }, { "code": null, "e": 32374, "s": 32179, "text": "ng-repeat can be used to iterate through an array which requires less lines of code than the usual javascript method.Filters can be used with ng-repeat to create an easy to implement search bar." }, { "code": null, "e": 32492, "s": 32374, "text": "ng-repeat can be used to iterate through an array which requires less lines of code than the usual javascript method." }, { "code": null, "e": 32570, "s": 32492, "text": "Filters can be used with ng-repeat to create an easy to implement search bar." }, { "code": null, "e": 32581, "s": 32570, "text": "References" }, { "code": null, "e": 32604, "s": 32581, "text": "https://angularjs.org/" }, { "code": null, "e": 32657, "s": 32604, "text": "https://docs.angularjs.org/api/ng/directive/ngRepeat" }, { "code": null, "e": 32705, "s": 32657, "text": "https://docs.angularjs.org/error/ngRepeat/dupes" }, { "code": null, "e": 32716, "s": 32705, "text": "mayank5326" }, { "code": null, "e": 32733, "s": 32716, "text": "Web Technologies" }, { "code": null, "e": 32831, "s": 32733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32840, "s": 32831, "text": "Comments" }, { "code": null, "e": 32853, "s": 32840, "text": "Old Comments" }, { "code": null, "e": 32890, "s": 32853, "text": "Express.js express.Router() Function" }, { "code": null, "e": 32934, "s": 32890, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 32979, "s": 32934, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33029, "s": 32979, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 33049, "s": 33029, "text": "Client-Server Model" }, { "code": null, "e": 33095, "s": 33049, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 33167, "s": 33095, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 33210, "s": 33167, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 33274, "s": 33210, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" } ]
Multinomial Naïve Bayes classifier using pointwise mutual information | by Arghavan Moradi | Towards Data Science
Text classification means assigning documents to a list of categories based on the content of each document. We can improve the performance of classifiers if we select the trainset in a way to maximize the information gain. Pointwise Mutual Information (PMI) is a feature scoring metrics that estimate the association between a feature and a class. You can read this article to learn more about PMI. We can improve the performance of classifiers if we select the trainset in a way to maximize the information gain. If we consider words as features and the category of documents as classes, then we can use PMI to reduce the dimensionality of the document space. In other words, when we convert documents with different topics into the bag of words (Document Term matrix), there are a huge number of words as a feature set of documents. But only a small set of words are very helpful to predict the topic of documents. The PMI score between a word and a category represents the information gain of a word given a topic. Thus, we can calculate the PMI score of all words given different topics in a corpus, then rank words in each topic based on its PMI score, and at the end select the top K words in each topic. With this approach, we can reduce the dimensionality of train data in a way to maximize the information gain of words. In this article, I will show you how to use PMI in a Naïve Bayes classifier. Multinomial Naïve Bayes is a probabilistic and supervised learning method. It is a famous method in text classification. Suppose that we have a set of classes C={c_1, c_2, ..., c_|C|} where |C| is the number of classes and a set of vocabulary V={w_1,w_2,...,w_|V|} while |V| is the total number of vocabularies. Also, we have a set of documents D={d_1,d_2, ..., d_|D|} distributed between classes while |D| is the number of documents. Each document “d” has a set of words W={w_1,w_2, ..., w_|W|} while W is a subset of V and |W| is the number of words in document “d”. This method calculates the posterior probability of a class given a document, P(c|d), and then assigns the document to a class with the highest probability. In other words, we choose a category for a document in a way to maximize the joint probability of the document’s words in a class. It is known as the maximum likelihood function. Since multiplying a set of probabilities may lead to floating-point underflow results, it is common to apply a logarithm to the maximum likelihood function. So, the log-maximum likelihood function for Naïve Bayes is as follow: We use the below relations to estimate P(c) and P(w_t|c). It is important to mention that we estimate these two probabilities based on the trainset. Suppose N is the total number of documents in a corpus and N_c is the number of documents in class c, then: Also, given that n(c, w_t) is the number of occurrence of w_t in training documents in class c, considering repetition, and n(c) is the total number of words in class c, then: To avoid zero probability (since in the joint probabilities in the maximum likelihood function, a zero probability can convert the whole result to zero), we can add a Laplace correction into the above formula. Then we have: In the Naïve Bayes classifier with Pointwise Mutual Information, instead of estimating the probability of all words given a class, we only use those words which are in the top k words based on their ranked PMI scores. To do so, first, we select a list of words (features) to maximize the information gain based on their PMI score and then apply Naïve Bayes classifier in this set of words. Here is a step-by-step python code to apply this classifier. Since this article focuses on Multinomial Naïve Bayes Classifier using PMI, I avoid talking about how to convert documents into the bag of words. Thus, we assume that we have a vector space matrix of documents as rows and words as columns. Also, an extra column, “label”, identifies the category of each document. Here is the head of the dataset: To start the process, first, we need to divide the dataset into trainset and test set. We consider 30% of the dataset as a testset. cl_dt= pd.read_csv(r'C:\...\Classification_data.csv')from sklearn.model_selection import train_test_splitX_train, X_test = train_test_split(cl_dt, test_size=0.30, random_state=42) Now, to calculate the PMI score of each word, first, we need to build a dictionary of words and the number of documents in each category that contain that word. The dictionary is as follow: “list_token” is a function that returns a list of words in a document. def list_token(doc , ack): temp1=pd.DataFrame(row).transpose() temp2 = temp1.loc[:, (temp1 != 0).any(axis=0)] if ack==0: freq = temp2.drop([‘Doc_ID’,’label’], axis=1) else: freq = temp2.drop([‘label’], axis=1) list_words =freq.columns.tolist() return list_words We use this function to build a dictionary of words and the number of documents in each category that contain that word. word_cat_dic={}n = len(X_train)for i in range(0,len(X_train)): dt=X_train.iloc[i,] lst_words=list_token(dt,0) cl=dt['label'] for w in set(lst_words): word_cl_dic[w]=word_cl_dic.get(w,{}) word_cl_dic[w][cl]=word_cl_dic[w].get(cl,0) word_cl_dic[w][cl]+=1 This a part of “word_cl_dic” as output: {'get': {'cloud': 51, 'ntw': 47, 'img': 18, 'inf': 56, 'nlp': 28}, 'environ': {'cloud': 18, 'img': 9, 'inf': 16, 'ntw': 14, 'nlp': 10}, 'error': {'ntw': 23, 'img': 4, 'inf': 20, 'cloud': 8, 'nlp': 9}, 'flush': {'ntw': 6, 'img': 6, 'nlp': 6, 'inf': 6, 'cloud': 6}, 'struct': {'ntw': 8, 'img': 1, 'inf': 4, 'cloud': 2}, 'split': {'ntw': 25, 'cloud': 22, 'img': 22, 'nlp': 36, 'inf': 24}, 'connect': {'ntw': 12, 'img': 7, 'inf': 9, 'nlp': 6, 'cloud': 1}, 'close': {'ntw': 26, 'img': 12, 'inf': 16, 'nlp': 16, 'cloud': 8}, 'sys': {'ntw': 29, 'cloud': 13, 'img': 23, 'inf': 20, 'nlp': 25}, 'select': {'ntw': 2, 'inf': 13, 'img': 2, 'cloud': 1, 'nlp': 1}, 'logging': {'ntw': 12, 'img': 12, 'nlp': 16, 'inf': 21, 'cloud': 16},...} Now, we calculate the PMI of each word given a class and then choose the top k=100 words per class: word_features={}num_top_words=100#calculate the number of document in each class, N_cnum_doc_cl=X_train.groupby([‘label’])[‘Doc_ID’].count()for w in word_cl_dic.keys(): dic = word_cl_dic[w] n_kw=0 for cl in dic.keys(): n_kw+=dic[cl] #Number of document in trainset contain word "w" for cl in dic.keys(): word_features[cl]=word_features.get(cl,[]) n_kw_cl=dic[cl] #Number of documents in class "cl" contains "w" n_dev_cl=num_doc_cl.loc[cl] #Number of documents in class "cl" p_w=n_kw/n p_cl = n_dev_cl/n p_w_cl= n_kw_cl/n pmi=log((p_w_cl)/(p_w*p_cl)) #pointwise mutual information score if len(word_features[cl])<k: word_features[cl].append((w,pmi)) if len(word_features[cl])==k: word_features[cl].sort(key=operator.itemgetter(1),reverse=True) else: if word_features[cl][k-1][1]<pmi: word_features[cl][k-1]= (w,pmi) word_features[cl].sort(key=operator.itemgetter(1),reverse=True) The result in “word_features” shows a list of top k=100 words in each class based on their PMI score: {'cloud': [('delete_function', 1.5032890640590577), ('describe_stacks', 1.5032890640590577), ('s3', 1.5032890640590577), ('create_stack', 1.5032890640590577), ('update_stack', 1.5032890640590577), ('delete_stack', 1.5032890640590577), ('tag_resource', 1.5032890640590577), ('list_tags_for_resource', 1.5032890640590577), ('untag_resource', 1.5032890640590577), ('delete_policy', 1.5032890640590577), ('get_waiter', 1.5032890640590577), ('validate_configuration', 1.5032890640590577), ('codebuild', 1.5032890640590577), ('rekognition', 1.5032890640590577), ('apigateway', 1.5032890640590577), ('xray', 1.5032890640590577), ('codepipeline', 1.5032890640590577),...} Here we create a list of all top k words in all classes: word_list=[]for cat in word_features.keys(): word_features[cat]=dict(word_features[cat]) for w in word_features[cat]: word_list.append(w) Now that we find the top k=100 words in each class that give us maximum information gain, it's time to train our classifier. We build two dictionaries. The first one represents n(c,w_t) per each word in “word_features” (the number of occurrence of w_t in training documents in class c) and the second one is the n(c) (the total number of words in class c): dt_per_cl=X_train.groupby([‘label’]).sum().reset_index()cl_word_count_dic={}cl_word_dic={}for j in range(0,len(dt_per_cl)): cl = dt_per_cl.iloc[j][‘label’] temp_per_cl=dt_per_cl.iloc[j,] list_word=list_token(temp_per_cl,1) list_words = [w for w in list_word if word_features[cl].get(w,-100000)!=-100000] cl_word_count_dic[cl] = cl_word_count_dic.get(cl,0) cl_word_dic[cl] = cl_word_dic.get(cl,{}) sum_all=0 for w in set(list_words): cl_word_dic[cl][w] = cl_word_dic[cl].get(w,0) cl_word_dic[cl][w] = temp_per_cl[w] sum_all += temp_per_cl[w] cl_word_count_dic[cl]=sum_all Here, we calculate the |V|: vocab_length=0 for cl in cl_word_dic.keys(): length = len(cl_word_dic[cat]) vocab_length+=length Now, it’s time to apply the log-maximum likelihood function on the testset to predict the category of each document. We can maximize the likelihood function or minimize the negative of the function. In our approach, we minimize the negative version of the log-likelihood function. for i in range(0,len(X_test)): minimum_neg_log_prob=1000000000 min_category=’’ dt=X_test.iloc[i,] list_word=list_token(dt,0) list_words = [w for w in list_word if w in word_list] cl_doc=dt[‘label’] Doc_ID = dt[‘Doc_ID’] for cl in cl_word_count_dic: #this is the -p(c), n is total number of documents in trainset neg_log_prob= -log(num_doc_cl.loc[cl]/n) word_dict = cl_word_dic[cl] count_cl = cl_word_count_dic[cl] for w in list_words: count_word_train=word_dict.get(w,0) #this the laplace correction of p(W_t|c) ratio = (count_word_train+1)/(count_cl+vocab_length) #minimizing the negative version neg_log_prob-=log(ratio) if minimum_neg_log_prob>neg_log_prob: min_category=cat minimum_neg_log_prob=neg_log_prob li_results.append((Doc_ID,min_category,cat_dev)) The result shows each document with its predicted class in the second column (min_category) and the ground truth in the third column (cl_doc): [('Doc868', 'cloud', 'img'), ('Doc440', 'ntw', 'ntw'), ('Doc334', 'cloud', 'cloud'), ('Doc736', 'nlp', 'nlp'), ('Doc785', 'img', 'img'), ('Doc523', 'nlp', 'nlp'), ('Doc226', 'cloud', 'nlp'), ('Doc68', 'cloud', 'inf'), ('Doc12', 'cloud', 'ntw'), ('Doc549', 'cloud', 'cloud'),...] We calculate the performance of the classifier as follow by comparing two last columns of “li_results”: precision= 0.5929707286187414recall= 0.5346135118242998F-measure= 0.5622820047774385 In this article, we present how to select features of documents in a way to maximize the information gain from those features about the category of documents. We use the Multinomial Naive Bayes method as a classifier and apply Pointwise Mutual Information (PMI) for feature selection. All codes for this article available on GitHub. [1] Schneider, K. M. (2005, October). Weighted average pointwise mutual information for feature selection in text categorization. In European Conference on Principles of Data Mining and Knowledge Discovery (pp. 252–263). Springer, Berlin, Heidelberg. [2] Manning, C., Raghavan, P., & Schütze, H. (2008). Text classification and Naive Bayes. In Introduction to Information Retrieval (pp. 234–265). Cambridge: Cambridge University Press. doi:10.1017/CBO9780511809071.014
[ { "code": null, "e": 571, "s": 171, "text": "Text classification means assigning documents to a list of categories based on the content of each document. We can improve the performance of classifiers if we select the trainset in a way to maximize the information gain. Pointwise Mutual Information (PMI) is a feature scoring metrics that estimate the association between a feature and a class. You can read this article to learn more about PMI." }, { "code": null, "e": 686, "s": 571, "text": "We can improve the performance of classifiers if we select the trainset in a way to maximize the information gain." }, { "code": null, "e": 1702, "s": 686, "text": "If we consider words as features and the category of documents as classes, then we can use PMI to reduce the dimensionality of the document space. In other words, when we convert documents with different topics into the bag of words (Document Term matrix), there are a huge number of words as a feature set of documents. But only a small set of words are very helpful to predict the topic of documents. The PMI score between a word and a category represents the information gain of a word given a topic. Thus, we can calculate the PMI score of all words given different topics in a corpus, then rank words in each topic based on its PMI score, and at the end select the top K words in each topic. With this approach, we can reduce the dimensionality of train data in a way to maximize the information gain of words. In this article, I will show you how to use PMI in a Naïve Bayes classifier. Multinomial Naïve Bayes is a probabilistic and supervised learning method. It is a famous method in text classification." }, { "code": null, "e": 2486, "s": 1702, "text": "Suppose that we have a set of classes C={c_1, c_2, ..., c_|C|} where |C| is the number of classes and a set of vocabulary V={w_1,w_2,...,w_|V|} while |V| is the total number of vocabularies. Also, we have a set of documents D={d_1,d_2, ..., d_|D|} distributed between classes while |D| is the number of documents. Each document “d” has a set of words W={w_1,w_2, ..., w_|W|} while W is a subset of V and |W| is the number of words in document “d”. This method calculates the posterior probability of a class given a document, P(c|d), and then assigns the document to a class with the highest probability. In other words, we choose a category for a document in a way to maximize the joint probability of the document’s words in a class. It is known as the maximum likelihood function." }, { "code": null, "e": 2714, "s": 2486, "text": "Since multiplying a set of probabilities may lead to floating-point underflow results, it is common to apply a logarithm to the maximum likelihood function. So, the log-maximum likelihood function for Naïve Bayes is as follow:" }, { "code": null, "e": 2971, "s": 2714, "text": "We use the below relations to estimate P(c) and P(w_t|c). It is important to mention that we estimate these two probabilities based on the trainset. Suppose N is the total number of documents in a corpus and N_c is the number of documents in class c, then:" }, { "code": null, "e": 3147, "s": 2971, "text": "Also, given that n(c, w_t) is the number of occurrence of w_t in training documents in class c, considering repetition, and n(c) is the total number of words in class c, then:" }, { "code": null, "e": 3371, "s": 3147, "text": "To avoid zero probability (since in the joint probabilities in the maximum likelihood function, a zero probability can convert the whole result to zero), we can add a Laplace correction into the above formula. Then we have:" }, { "code": null, "e": 3763, "s": 3371, "text": "In the Naïve Bayes classifier with Pointwise Mutual Information, instead of estimating the probability of all words given a class, we only use those words which are in the top k words based on their ranked PMI scores. To do so, first, we select a list of words (features) to maximize the information gain based on their PMI score and then apply Naïve Bayes classifier in this set of words." }, { "code": null, "e": 4172, "s": 3763, "text": "Here is a step-by-step python code to apply this classifier. Since this article focuses on Multinomial Naïve Bayes Classifier using PMI, I avoid talking about how to convert documents into the bag of words. Thus, we assume that we have a vector space matrix of documents as rows and words as columns. Also, an extra column, “label”, identifies the category of each document. Here is the head of the dataset:" }, { "code": null, "e": 4304, "s": 4172, "text": "To start the process, first, we need to divide the dataset into trainset and test set. We consider 30% of the dataset as a testset." }, { "code": null, "e": 4484, "s": 4304, "text": "cl_dt= pd.read_csv(r'C:\\...\\Classification_data.csv')from sklearn.model_selection import train_test_splitX_train, X_test = train_test_split(cl_dt, test_size=0.30, random_state=42)" }, { "code": null, "e": 4674, "s": 4484, "text": "Now, to calculate the PMI score of each word, first, we need to build a dictionary of words and the number of documents in each category that contain that word. The dictionary is as follow:" }, { "code": null, "e": 4745, "s": 4674, "text": "“list_token” is a function that returns a list of words in a document." }, { "code": null, "e": 5007, "s": 4745, "text": "def list_token(doc , ack): temp1=pd.DataFrame(row).transpose() temp2 = temp1.loc[:, (temp1 != 0).any(axis=0)] if ack==0: freq = temp2.drop([‘Doc_ID’,’label’], axis=1) else: freq = temp2.drop([‘label’], axis=1) list_words =freq.columns.tolist() return list_words" }, { "code": null, "e": 5128, "s": 5007, "text": "We use this function to build a dictionary of words and the number of documents in each category that contain that word." }, { "code": null, "e": 5414, "s": 5128, "text": "word_cat_dic={}n = len(X_train)for i in range(0,len(X_train)): dt=X_train.iloc[i,] lst_words=list_token(dt,0) cl=dt['label'] for w in set(lst_words): word_cl_dic[w]=word_cl_dic.get(w,{}) word_cl_dic[w][cl]=word_cl_dic[w].get(cl,0) word_cl_dic[w][cl]+=1" }, { "code": null, "e": 5454, "s": 5414, "text": "This a part of “word_cl_dic” as output:" }, { "code": null, "e": 6178, "s": 5454, "text": "{'get': {'cloud': 51, 'ntw': 47, 'img': 18, 'inf': 56, 'nlp': 28}, 'environ': {'cloud': 18, 'img': 9, 'inf': 16, 'ntw': 14, 'nlp': 10}, 'error': {'ntw': 23, 'img': 4, 'inf': 20, 'cloud': 8, 'nlp': 9}, 'flush': {'ntw': 6, 'img': 6, 'nlp': 6, 'inf': 6, 'cloud': 6}, 'struct': {'ntw': 8, 'img': 1, 'inf': 4, 'cloud': 2}, 'split': {'ntw': 25, 'cloud': 22, 'img': 22, 'nlp': 36, 'inf': 24}, 'connect': {'ntw': 12, 'img': 7, 'inf': 9, 'nlp': 6, 'cloud': 1}, 'close': {'ntw': 26, 'img': 12, 'inf': 16, 'nlp': 16, 'cloud': 8}, 'sys': {'ntw': 29, 'cloud': 13, 'img': 23, 'inf': 20, 'nlp': 25}, 'select': {'ntw': 2, 'inf': 13, 'img': 2, 'cloud': 1, 'nlp': 1}, 'logging': {'ntw': 12, 'img': 12, 'nlp': 16, 'inf': 21, 'cloud': 16},...}" }, { "code": null, "e": 6278, "s": 6178, "text": "Now, we calculate the PMI of each word given a class and then choose the top k=100 words per class:" }, { "code": null, "e": 7195, "s": 6278, "text": "word_features={}num_top_words=100#calculate the number of document in each class, N_cnum_doc_cl=X_train.groupby([‘label’])[‘Doc_ID’].count()for w in word_cl_dic.keys(): dic = word_cl_dic[w] n_kw=0 for cl in dic.keys(): n_kw+=dic[cl] #Number of document in trainset contain word \"w\" for cl in dic.keys(): word_features[cl]=word_features.get(cl,[]) n_kw_cl=dic[cl] #Number of documents in class \"cl\" contains \"w\" n_dev_cl=num_doc_cl.loc[cl] #Number of documents in class \"cl\" p_w=n_kw/n p_cl = n_dev_cl/n p_w_cl= n_kw_cl/n pmi=log((p_w_cl)/(p_w*p_cl)) #pointwise mutual information score if len(word_features[cl])<k: word_features[cl].append((w,pmi)) if len(word_features[cl])==k: word_features[cl].sort(key=operator.itemgetter(1),reverse=True) else: if word_features[cl][k-1][1]<pmi: word_features[cl][k-1]= (w,pmi) word_features[cl].sort(key=operator.itemgetter(1),reverse=True)" }, { "code": null, "e": 7297, "s": 7195, "text": "The result in “word_features” shows a list of top k=100 words in each class based on their PMI score:" }, { "code": null, "e": 7977, "s": 7297, "text": "{'cloud': [('delete_function', 1.5032890640590577), ('describe_stacks', 1.5032890640590577), ('s3', 1.5032890640590577), ('create_stack', 1.5032890640590577), ('update_stack', 1.5032890640590577), ('delete_stack', 1.5032890640590577), ('tag_resource', 1.5032890640590577), ('list_tags_for_resource', 1.5032890640590577), ('untag_resource', 1.5032890640590577), ('delete_policy', 1.5032890640590577), ('get_waiter', 1.5032890640590577), ('validate_configuration', 1.5032890640590577), ('codebuild', 1.5032890640590577), ('rekognition', 1.5032890640590577), ('apigateway', 1.5032890640590577), ('xray', 1.5032890640590577), ('codepipeline', 1.5032890640590577),...}" }, { "code": null, "e": 8034, "s": 7977, "text": "Here we create a list of all top k words in all classes:" }, { "code": null, "e": 8185, "s": 8034, "text": "word_list=[]for cat in word_features.keys(): word_features[cat]=dict(word_features[cat]) for w in word_features[cat]: word_list.append(w)" }, { "code": null, "e": 8542, "s": 8185, "text": "Now that we find the top k=100 words in each class that give us maximum information gain, it's time to train our classifier. We build two dictionaries. The first one represents n(c,w_t) per each word in “word_features” (the number of occurrence of w_t in training documents in class c) and the second one is the n(c) (the total number of words in class c):" }, { "code": null, "e": 9115, "s": 8542, "text": "dt_per_cl=X_train.groupby([‘label’]).sum().reset_index()cl_word_count_dic={}cl_word_dic={}for j in range(0,len(dt_per_cl)): cl = dt_per_cl.iloc[j][‘label’] temp_per_cl=dt_per_cl.iloc[j,] list_word=list_token(temp_per_cl,1) list_words = [w for w in list_word if word_features[cl].get(w,-100000)!=-100000] cl_word_count_dic[cl] = cl_word_count_dic.get(cl,0) cl_word_dic[cl] = cl_word_dic.get(cl,{}) sum_all=0 for w in set(list_words): cl_word_dic[cl][w] = cl_word_dic[cl].get(w,0) cl_word_dic[cl][w] = temp_per_cl[w] sum_all += temp_per_cl[w] cl_word_count_dic[cl]=sum_all" }, { "code": null, "e": 9143, "s": 9115, "text": "Here, we calculate the |V|:" }, { "code": null, "e": 9240, "s": 9143, "text": "vocab_length=0 for cl in cl_word_dic.keys(): length = len(cl_word_dic[cat]) vocab_length+=length" }, { "code": null, "e": 9521, "s": 9240, "text": "Now, it’s time to apply the log-maximum likelihood function on the testset to predict the category of each document. We can maximize the likelihood function or minimize the negative of the function. In our approach, we minimize the negative version of the log-likelihood function." }, { "code": null, "e": 10326, "s": 9521, "text": "for i in range(0,len(X_test)): minimum_neg_log_prob=1000000000 min_category=’’ dt=X_test.iloc[i,] list_word=list_token(dt,0) list_words = [w for w in list_word if w in word_list] cl_doc=dt[‘label’] Doc_ID = dt[‘Doc_ID’] for cl in cl_word_count_dic: #this is the -p(c), n is total number of documents in trainset neg_log_prob= -log(num_doc_cl.loc[cl]/n) word_dict = cl_word_dic[cl] count_cl = cl_word_count_dic[cl] for w in list_words: count_word_train=word_dict.get(w,0) #this the laplace correction of p(W_t|c) ratio = (count_word_train+1)/(count_cl+vocab_length) #minimizing the negative version neg_log_prob-=log(ratio) if minimum_neg_log_prob>neg_log_prob: min_category=cat minimum_neg_log_prob=neg_log_prob li_results.append((Doc_ID,min_category,cat_dev))" }, { "code": null, "e": 10469, "s": 10326, "text": "The result shows each document with its predicted class in the second column (min_category) and the ground truth in the third column (cl_doc):" }, { "code": null, "e": 10748, "s": 10469, "text": "[('Doc868', 'cloud', 'img'), ('Doc440', 'ntw', 'ntw'), ('Doc334', 'cloud', 'cloud'), ('Doc736', 'nlp', 'nlp'), ('Doc785', 'img', 'img'), ('Doc523', 'nlp', 'nlp'), ('Doc226', 'cloud', 'nlp'), ('Doc68', 'cloud', 'inf'), ('Doc12', 'cloud', 'ntw'), ('Doc549', 'cloud', 'cloud'),...]" }, { "code": null, "e": 10852, "s": 10748, "text": "We calculate the performance of the classifier as follow by comparing two last columns of “li_results”:" }, { "code": null, "e": 10937, "s": 10852, "text": "precision= 0.5929707286187414recall= 0.5346135118242998F-measure= 0.5622820047774385" }, { "code": null, "e": 11270, "s": 10937, "text": "In this article, we present how to select features of documents in a way to maximize the information gain from those features about the category of documents. We use the Multinomial Naive Bayes method as a classifier and apply Pointwise Mutual Information (PMI) for feature selection. All codes for this article available on GitHub." }, { "code": null, "e": 11521, "s": 11270, "text": "[1] Schneider, K. M. (2005, October). Weighted average pointwise mutual information for feature selection in text categorization. In European Conference on Principles of Data Mining and Knowledge Discovery (pp. 252–263). Springer, Berlin, Heidelberg." } ]
Android - RadioGroup Control
A RadioGroup class is used for set of radio buttons. If we check one radio button that belongs to a radio group, it automatically unchecks any previously checked radio button within the same group. Following are the important attributes related to RadioGroup control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time. Inherited from android.view.View Class − android:background This is a drawable to use as the background. android:contentDescription This defines text that briefly describes content of the view. android:id This supplies an identifier name for this view android:onClick This is the name of the method in this View's context to invoke when the view is clicked. android:visibility This controls the initial visibility of the view. This example will take you through simple steps to show how to create your own Android application using Linear Layout and RadioGroup. Following is the content of the modified main activity file src/MainActivity.java. This file can include each of the fundamental lifecycle methods. package com.example.saira_000.myapplication; import android.app.Activity; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; public class MainActivity extends Activity { private RadioGroup radioSexGroup; private RadioButton radioSexButton; private Button btnDisplay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup); btnDisplay=(Button)findViewById(R.id.button); btnDisplay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int selectedId=radioSexGroup.getCheckedRadioButtonId(); radioSexButton=(RadioButton)findViewById(selectedId); Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show(); } }); } } Following will be the content of res/layout/activity_main.xml file − <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Radio button" android:id="@+id/textView" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:textSize="35dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorialspoint" android:id="@+id/textView2" android:layout_below="@+id/textView" android:layout_alignRight="@+id/textView" android:layout_alignEnd="@+id/textView" android:textSize="35dp" android:textColor="@android:color/holo_green_dark" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:src="@drawable/abc" android:layout_below="@+id/textView2" android:layout_alignLeft="@+id/textView" android:layout_alignStart="@+id/textView" android:layout_alignRight="@+id/textView" android:layout_alignEnd="@+id/textView" /> <RadioGroup android:layout_width="fill_parent" android:layout_height="90dp" android:layout_below="@+id/imageView" android:layout_marginTop="58dp" android:weightSum="1" android:id="@+id/radioGroup" android:layout_alignLeft="@+id/textView2" android:layout_alignStart="@+id/textView2" android:layout_alignRight="@+id/textView3" android:layout_alignEnd="@+id/textView3"> <RadioButton android:layout_width="wrap_content" android:layout_height="55dp" android:text="Male" android:id="@+id/radioButton" android:layout_gravity="center_horizontal" android:checked="false" android:textSize="25dp" /> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Female" android:id="@+id/radioButton2" android:layout_gravity="center_horizontal" android:checked="false" android:textSize="25dp" android:layout_weight="0.13" /> </RadioGroup> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" Are you?" android:id="@+id/textView3" android:textSize="35dp" android:layout_below="@+id/imageView" android:layout_alignRight="@+id/textView2" android:layout_alignEnd="@+id/textView2" android:layout_alignLeft="@+id/imageView" android:layout_alignStart="@+id/imageView" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Button" android:id="@+id/button" android:layout_gravity="center_horizontal" android:layout_below="@+id/radioGroup" android:layout_centerHorizontal="true" /> </RelativeLayout> Following will be the content of res/values/strings.xml to define these new constants − <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">My Applicaiton</string> <string name="example_radiogroup">Example showing RadioGroup</string> </resources> Following is the default content of AndroidManifest.xml − <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.saira_000.myapplication" > <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.My Application.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your My Application application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − The following screen will appear, here we have a RadioGroup. Need to select male or female radio button then click on new button. if you do above steps without fail, you would get a toast message after clicked by new button I will recommend to try above example with different attributes of RadioButton in Layout XML file as well at programming time to have different look and feel of the RadioButton. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple RadioButton controls in one activity. 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3660, "s": 3607, "text": "A RadioGroup class is used for set of radio buttons." }, { "code": null, "e": 3805, "s": 3660, "text": "If we check one radio button that belongs to a radio group, it automatically unchecks any previously checked radio button within the same group." }, { "code": null, "e": 4031, "s": 3805, "text": "Following are the important attributes related to RadioGroup control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time." }, { "code": null, "e": 4072, "s": 4031, "text": "Inherited from android.view.View Class −" }, { "code": null, "e": 4091, "s": 4072, "text": "android:background" }, { "code": null, "e": 4136, "s": 4091, "text": "This is a drawable to use as the background." }, { "code": null, "e": 4163, "s": 4136, "text": "android:contentDescription" }, { "code": null, "e": 4225, "s": 4163, "text": "This defines text that briefly describes content of the view." }, { "code": null, "e": 4236, "s": 4225, "text": "android:id" }, { "code": null, "e": 4283, "s": 4236, "text": "This supplies an identifier name for this view" }, { "code": null, "e": 4299, "s": 4283, "text": "android:onClick" }, { "code": null, "e": 4389, "s": 4299, "text": "This is the name of the method in this View's context to invoke when the view is clicked." }, { "code": null, "e": 4408, "s": 4389, "text": "android:visibility" }, { "code": null, "e": 4458, "s": 4408, "text": "This controls the initial visibility of the view." }, { "code": null, "e": 4593, "s": 4458, "text": "This example will take you through simple steps to show how to create your own Android application using Linear Layout and RadioGroup." }, { "code": null, "e": 4741, "s": 4593, "text": "Following is the content of the modified main activity file src/MainActivity.java. This file can include each of the fundamental lifecycle methods." }, { "code": null, "e": 5926, "s": 4741, "text": "package com.example.saira_000.myapplication;\n\nimport android.app.Activity;\nimport android.support.v7.app.ActionBarActivity;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.RadioButton;\nimport android.widget.RadioGroup;\nimport android.widget.Toast;\n\npublic class MainActivity extends Activity {\n private RadioGroup radioSexGroup;\n private RadioButton radioSexButton;\n private Button btnDisplay;\n \n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup);\n \n btnDisplay=(Button)findViewById(R.id.button);\n \n btnDisplay.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n int selectedId=radioSexGroup.getCheckedRadioButtonId();\n radioSexButton=(RadioButton)findViewById(selectedId);\n Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();\n }\n });\n }\n}" }, { "code": null, "e": 5995, "s": 5926, "text": "Following will be the content of res/layout/activity_main.xml file −" }, { "code": null, "e": 9452, "s": 5995, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" \n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" \n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\">\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Radio button\"\n android:id=\"@+id/textView\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"35dp\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorialspoint\"\n android:id=\"@+id/textView2\"\n android:layout_below=\"@+id/textView\"\n android:layout_alignRight=\"@+id/textView\"\n android:layout_alignEnd=\"@+id/textView\"\n android:textSize=\"35dp\"\n android:textColor=\"@android:color/holo_green_dark\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView2\"\n android:layout_alignLeft=\"@+id/textView\"\n android:layout_alignStart=\"@+id/textView\"\n android:layout_alignRight=\"@+id/textView\"\n android:layout_alignEnd=\"@+id/textView\" />\n \n <RadioGroup\n android:layout_width=\"fill_parent\"\n android:layout_height=\"90dp\"\n android:layout_below=\"@+id/imageView\"\n android:layout_marginTop=\"58dp\"\n android:weightSum=\"1\"\n android:id=\"@+id/radioGroup\"\n android:layout_alignLeft=\"@+id/textView2\"\n android:layout_alignStart=\"@+id/textView2\"\n android:layout_alignRight=\"@+id/textView3\"\n android:layout_alignEnd=\"@+id/textView3\">\n \n <RadioButton\n android:layout_width=\"wrap_content\"\n android:layout_height=\"55dp\"\n android:text=\"Male\"\n android:id=\"@+id/radioButton\"\n android:layout_gravity=\"center_horizontal\"\n android:checked=\"false\"\n android:textSize=\"25dp\" />\n\n <RadioButton\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Female\"\n android:id=\"@+id/radioButton2\"\n android:layout_gravity=\"center_horizontal\"\n android:checked=\"false\"\n android:textSize=\"25dp\"\n android:layout_weight=\"0.13\" />\n </RadioGroup>\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\" Are you?\"\n android:id=\"@+id/textView3\"\n android:textSize=\"35dp\"\n android:layout_below=\"@+id/imageView\"\n android:layout_alignRight=\"@+id/textView2\"\n android:layout_alignEnd=\"@+id/textView2\"\n android:layout_alignLeft=\"@+id/imageView\"\n android:layout_alignStart=\"@+id/imageView\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"New Button\"\n android:id=\"@+id/button\"\n android:layout_gravity=\"center_horizontal\"\n android:layout_below=\"@+id/radioGroup\"\n android:layout_centerHorizontal=\"true\" />\n\n</RelativeLayout>" }, { "code": null, "e": 9541, "s": 9452, "text": "Following will be the content of res/values/strings.xml to define these new constants −" }, { "code": null, "e": 9729, "s": 9541, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">My Applicaiton</string>\n <string name=\"example_radiogroup\">Example showing RadioGroup</string>\n</resources>" }, { "code": null, "e": 9788, "s": 9729, "text": "Following is the default content of AndroidManifest.xml −" }, { "code": null, "e": 10511, "s": 9788, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.saira_000.myapplication\" >\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.My Application.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>" }, { "code": null, "e": 10903, "s": 10511, "text": "Let's try to run your My Application application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −" }, { "code": null, "e": 10964, "s": 10903, "text": "The following screen will appear, here we have a RadioGroup." }, { "code": null, "e": 11127, "s": 10964, "text": "Need to select male or female radio button then click on new button. if you do above steps without fail, you would get a toast message after clicked by new button" }, { "code": null, "e": 11488, "s": 11127, "text": "I will recommend to try above example with different attributes of RadioButton in Layout XML file as well at programming time to have different look and feel of the RadioButton. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple RadioButton controls in one activity." }, { "code": null, "e": 11523, "s": 11488, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 11535, "s": 11523, "text": " Aditya Dua" }, { "code": null, "e": 11570, "s": 11535, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 11584, "s": 11570, "text": " Sharad Kumar" }, { "code": null, "e": 11616, "s": 11584, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 11633, "s": 11616, "text": " Abhilash Nelson" }, { "code": null, "e": 11668, "s": 11633, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11685, "s": 11668, "text": " Abhilash Nelson" }, { "code": null, "e": 11720, "s": 11685, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11737, "s": 11720, "text": " Abhilash Nelson" }, { "code": null, "e": 11770, "s": 11737, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 11787, "s": 11770, "text": " Abhilash Nelson" }, { "code": null, "e": 11794, "s": 11787, "text": " Print" }, { "code": null, "e": 11805, "s": 11794, "text": " Add Notes" } ]
The Deep Music Visualizer: Using sound to explore the latent space of BigGAN | by Matt Siegelman | Towards Data Science
Want to make a deep music video? Wrap your mind around BigGAN. Developed at Google by Brock et al. (2018)1, BigGAN is a recent chapter in a brief history of generative adversarial networks (GANs). GANs are AI models trained by two competing neural networks: a generator creates new images based on statistical patterns learned from a set of example images, and a discriminator tries to classify the images as real or fake. By training the generator to fool the discriminator, GANs learn to create realistic images. BigGAN is considered Big because it contains over 300 million parameters trained on hundreds of google TPUs at the cost of an estimated $60,000. The result is an AI model that generates images from 1128 input parameters: i) a 1000-unit class vector of weights {0 ≤ 1} that correspond to 1000 ImageNet classes, or object categories. ii) a 128-unit noise vector of values {-2 ≤ 2} that control the visual features of objects in the output image, like color, size, position and orientation. A class vector of zeros except a one in the vase class outputs a vase: Interpolating between classes without changing the noise vector reveals shared features in the latent space, like faces: Interpolating between random vectors reveals deeper sorts of structure: If you’re intrigued, join the expedition of artists, computer scientists and cryptozoologists on this strange frontier. Apps like artbreeder have provided simple interfaces for creating AI artwork, and autonomous artificial artists loom while some users occupy themselves searching for the Mona Lisa. Others have set BigGAN to music. These “deep music videos” have garnered mixed reactions, varying between beautiful, trippy, and horrifying. To be fair, one is wise to fear what lurks in latent space... What other unlikely chimeras, mythical creatures, priceless artworks and familiar dreams reside within BigGAN? To find out, we need to cover more ground. That’s why I built the deep music visualizer, an open source, easy-to-use tool for navigating the latent space with sound. A latent spaceship, with bluetooth. Take it for a spin and create some cool music videos along the way. Just make sure to share what you discover. Clone the GitHub repository and follow the installation instructions in the README file. github.com Run this command in your terminal: python visualize.py --song beethoven.mp3 That’s it. Here’s the output: What’s going on here? The deep music visualizer syncs pitch with the class vector and volume and tempo with the noise vector, so that pitch controls the objects, shapes, and textures in each frame, while volume and tempo control movement between frames. At each time point in the song, a chromagram of the twelve chromatic notes determines the weights {0 ≤ 1} of up to twelve ImageNet classes in the class vector. Independently, the rate of change of the volume — mainly percussion — controls the rate of change of the noise vector. 128, 256, or 512 Default: 512 BigGAN is big, and therefore slow. If you ran the first example on your laptop, it will take ~7 hours to render. With a resolution of 128x128, it would only take 25 minutes (per minute of video). python visualize.py --song beethoven.mp3 --resolution 128 However, I recommend you generate high resolution videos by launching a virtual GPU on google cloud to significantly speed up runtime from ~7 hours to a few minutes. While it isn’t free, google awards new users $300 in credit, and a GPU costs $1/hour. Integer ≥ 1 Default: Full length of audio It can be useful to generate shorter videos to limit runtime while testing out some other input parameters. Range: 1–299 Default: 220 The pitch sensitivity is the sensitivity of the class vector to changes in pitch. At higher pitch sensitivity, the shapes, textures and objects in the video change more rapidly and adhere more precisely to the notes in the music. Range: 0 ≤ 1 Default: 0.25 The tempo sensitivity is the sensitivity of the noise vector to changes in volume and tempo. Higher tempo sensitivity yields more movement. In this example, the classes cohere strongly to the pitch because pitch sensitivity is high, but there is little overall movement because tempo sensitivity is low. python visualize.py --song moon_river.mp3 --duration 60--pitch_sensitivity 290 --tempo_sensitivity 0 In this example, the class mixture hardly changes because pitch sensitivity is low, but there is more overall movement because tempo sensitivity is high. python visualize.py --song moon_river.mp3 --duration 60--pitch_sensitivity 10 --tempo_sensitivity 0.6 1–12 Default: 12 Lower the number of classes to mix fewer objects. Up to twelve indices {0–999} corresponding to 1000 ImageNet classes Default: Twelve random indices You can choose which classes you want to include in the video. The classes sync with pitches in chromatic order (A, A#, B...). Alternatively, set sort_classes_by_power to 1 if you prefer to enter classes in a prioritized order. In this example, the video includes daisy (#985) and jellyfish (#107), but with more daisy than jellyfish: python visualize.py --song cold.mp3 --duration 10 --pitch_sensitivity 260 --tempo_sensitivity 0.8 --num_classes 2 --classes 985 107 --sort_classes_by_power 1 Multiples of 64 Default: 512 The frame length is the number of audio samples per video frame. The default frame length of 512 yields a video frame rate of ~43 fps. Decreasing the frame length increases the frame rate so the image updates more frequently (but the video will take longer to render). This is most useful for visualizing rapid music. python visualize.py --song T69_collapse.mp3 --duration 30 --num_classes 4 --classes 527 511 545 611 --sort_classes_by_power 1 --frame_length 128 I hope you found this tutorial interesting and informative. If you want to express thanks, tweet me a deep music video you create with this code! You can find more of my videos here. What sort of art can GANs not create? Must art imitate reality? Does music have intrinsic visual structure? Are certain sounds, instruments, songs and genres better represented by certain ImageNet classes? Someone with synesthesia might think so. Is BigGAN’s artistic ability explained by the representational similarity between deep neural networks and the human visual cortex2? If so, could the latent space represent a topological map of the human imagination?Can BigGAN predict object imageability? For example, picture a wall clock. Did you actually visualize all of the digits? Neither did BigGAN. Build a visualizer that responds to live music in real time. Use natural language processing to automatically select ImageNet classes based on semantic associations with song lyrics (or audio books). Play music to people in fMRI, and interface the class and noise vectors with neural activity to create deep music videos from the brain. All of these simultaneously? [1] A. Brock, J. Donahu and K. Simonyan, Large Scale GAN Training for High Fidelity Natural Image Synthesis (2018), Eighth International Conference on Learning Representations. [2] N. Kriegeskorte, Deep Neural Networks: A New Framework for Modeling Biological Vision and Brain Information Processing (2015), Annual Review of Vision Science.
[ { "code": null, "e": 687, "s": 172, "text": "Want to make a deep music video? Wrap your mind around BigGAN. Developed at Google by Brock et al. (2018)1, BigGAN is a recent chapter in a brief history of generative adversarial networks (GANs). GANs are AI models trained by two competing neural networks: a generator creates new images based on statistical patterns learned from a set of example images, and a discriminator tries to classify the images as real or fake. By training the generator to fool the discriminator, GANs learn to create realistic images." }, { "code": null, "e": 908, "s": 687, "text": "BigGAN is considered Big because it contains over 300 million parameters trained on hundreds of google TPUs at the cost of an estimated $60,000. The result is an AI model that generates images from 1128 input parameters:" }, { "code": null, "e": 1019, "s": 908, "text": "i) a 1000-unit class vector of weights {0 ≤ 1} that correspond to 1000 ImageNet classes, or object categories." }, { "code": null, "e": 1175, "s": 1019, "text": "ii) a 128-unit noise vector of values {-2 ≤ 2} that control the visual features of objects in the output image, like color, size, position and orientation." }, { "code": null, "e": 1246, "s": 1175, "text": "A class vector of zeros except a one in the vase class outputs a vase:" }, { "code": null, "e": 1367, "s": 1246, "text": "Interpolating between classes without changing the noise vector reveals shared features in the latent space, like faces:" }, { "code": null, "e": 1439, "s": 1367, "text": "Interpolating between random vectors reveals deeper sorts of structure:" }, { "code": null, "e": 1740, "s": 1439, "text": "If you’re intrigued, join the expedition of artists, computer scientists and cryptozoologists on this strange frontier. Apps like artbreeder have provided simple interfaces for creating AI artwork, and autonomous artificial artists loom while some users occupy themselves searching for the Mona Lisa." }, { "code": null, "e": 1773, "s": 1740, "text": "Others have set BigGAN to music." }, { "code": null, "e": 1943, "s": 1773, "text": "These “deep music videos” have garnered mixed reactions, varying between beautiful, trippy, and horrifying. To be fair, one is wise to fear what lurks in latent space..." }, { "code": null, "e": 2220, "s": 1943, "text": "What other unlikely chimeras, mythical creatures, priceless artworks and familiar dreams reside within BigGAN? To find out, we need to cover more ground. That’s why I built the deep music visualizer, an open source, easy-to-use tool for navigating the latent space with sound." }, { "code": null, "e": 2256, "s": 2220, "text": "A latent spaceship, with bluetooth." }, { "code": null, "e": 2367, "s": 2256, "text": "Take it for a spin and create some cool music videos along the way. Just make sure to share what you discover." }, { "code": null, "e": 2456, "s": 2367, "text": "Clone the GitHub repository and follow the installation instructions in the README file." }, { "code": null, "e": 2467, "s": 2456, "text": "github.com" }, { "code": null, "e": 2502, "s": 2467, "text": "Run this command in your terminal:" }, { "code": null, "e": 2543, "s": 2502, "text": "python visualize.py --song beethoven.mp3" }, { "code": null, "e": 2573, "s": 2543, "text": "That’s it. Here’s the output:" }, { "code": null, "e": 3106, "s": 2573, "text": "What’s going on here? The deep music visualizer syncs pitch with the class vector and volume and tempo with the noise vector, so that pitch controls the objects, shapes, and textures in each frame, while volume and tempo control movement between frames. At each time point in the song, a chromagram of the twelve chromatic notes determines the weights {0 ≤ 1} of up to twelve ImageNet classes in the class vector. Independently, the rate of change of the volume — mainly percussion — controls the rate of change of the noise vector." }, { "code": null, "e": 3123, "s": 3106, "text": "128, 256, or 512" }, { "code": null, "e": 3136, "s": 3123, "text": "Default: 512" }, { "code": null, "e": 3332, "s": 3136, "text": "BigGAN is big, and therefore slow. If you ran the first example on your laptop, it will take ~7 hours to render. With a resolution of 128x128, it would only take 25 minutes (per minute of video)." }, { "code": null, "e": 3390, "s": 3332, "text": "python visualize.py --song beethoven.mp3 --resolution 128" }, { "code": null, "e": 3642, "s": 3390, "text": "However, I recommend you generate high resolution videos by launching a virtual GPU on google cloud to significantly speed up runtime from ~7 hours to a few minutes. While it isn’t free, google awards new users $300 in credit, and a GPU costs $1/hour." }, { "code": null, "e": 3654, "s": 3642, "text": "Integer ≥ 1" }, { "code": null, "e": 3684, "s": 3654, "text": "Default: Full length of audio" }, { "code": null, "e": 3792, "s": 3684, "text": "It can be useful to generate shorter videos to limit runtime while testing out some other input parameters." }, { "code": null, "e": 3805, "s": 3792, "text": "Range: 1–299" }, { "code": null, "e": 3818, "s": 3805, "text": "Default: 220" }, { "code": null, "e": 4048, "s": 3818, "text": "The pitch sensitivity is the sensitivity of the class vector to changes in pitch. At higher pitch sensitivity, the shapes, textures and objects in the video change more rapidly and adhere more precisely to the notes in the music." }, { "code": null, "e": 4061, "s": 4048, "text": "Range: 0 ≤ 1" }, { "code": null, "e": 4075, "s": 4061, "text": "Default: 0.25" }, { "code": null, "e": 4215, "s": 4075, "text": "The tempo sensitivity is the sensitivity of the noise vector to changes in volume and tempo. Higher tempo sensitivity yields more movement." }, { "code": null, "e": 4379, "s": 4215, "text": "In this example, the classes cohere strongly to the pitch because pitch sensitivity is high, but there is little overall movement because tempo sensitivity is low." }, { "code": null, "e": 4480, "s": 4379, "text": "python visualize.py --song moon_river.mp3 --duration 60--pitch_sensitivity 290 --tempo_sensitivity 0" }, { "code": null, "e": 4634, "s": 4480, "text": "In this example, the class mixture hardly changes because pitch sensitivity is low, but there is more overall movement because tempo sensitivity is high." }, { "code": null, "e": 4736, "s": 4634, "text": "python visualize.py --song moon_river.mp3 --duration 60--pitch_sensitivity 10 --tempo_sensitivity 0.6" }, { "code": null, "e": 4741, "s": 4736, "text": "1–12" }, { "code": null, "e": 4753, "s": 4741, "text": "Default: 12" }, { "code": null, "e": 4803, "s": 4753, "text": "Lower the number of classes to mix fewer objects." }, { "code": null, "e": 4871, "s": 4803, "text": "Up to twelve indices {0–999} corresponding to 1000 ImageNet classes" }, { "code": null, "e": 4902, "s": 4871, "text": "Default: Twelve random indices" }, { "code": null, "e": 5029, "s": 4902, "text": "You can choose which classes you want to include in the video. The classes sync with pitches in chromatic order (A, A#, B...)." }, { "code": null, "e": 5130, "s": 5029, "text": "Alternatively, set sort_classes_by_power to 1 if you prefer to enter classes in a prioritized order." }, { "code": null, "e": 5237, "s": 5130, "text": "In this example, the video includes daisy (#985) and jellyfish (#107), but with more daisy than jellyfish:" }, { "code": null, "e": 5395, "s": 5237, "text": "python visualize.py --song cold.mp3 --duration 10 --pitch_sensitivity 260 --tempo_sensitivity 0.8 --num_classes 2 --classes 985 107 --sort_classes_by_power 1" }, { "code": null, "e": 5411, "s": 5395, "text": "Multiples of 64" }, { "code": null, "e": 5424, "s": 5411, "text": "Default: 512" }, { "code": null, "e": 5742, "s": 5424, "text": "The frame length is the number of audio samples per video frame. The default frame length of 512 yields a video frame rate of ~43 fps. Decreasing the frame length increases the frame rate so the image updates more frequently (but the video will take longer to render). This is most useful for visualizing rapid music." }, { "code": null, "e": 5887, "s": 5742, "text": "python visualize.py --song T69_collapse.mp3 --duration 30 --num_classes 4 --classes 527 511 545 611 --sort_classes_by_power 1 --frame_length 128" }, { "code": null, "e": 6033, "s": 5887, "text": "I hope you found this tutorial interesting and informative. If you want to express thanks, tweet me a deep music video you create with this code!" }, { "code": null, "e": 6070, "s": 6033, "text": "You can find more of my videos here." }, { "code": null, "e": 6134, "s": 6070, "text": "What sort of art can GANs not create? Must art imitate reality?" }, { "code": null, "e": 6317, "s": 6134, "text": "Does music have intrinsic visual structure? Are certain sounds, instruments, songs and genres better represented by certain ImageNet classes? Someone with synesthesia might think so." }, { "code": null, "e": 6674, "s": 6317, "text": "Is BigGAN’s artistic ability explained by the representational similarity between deep neural networks and the human visual cortex2? If so, could the latent space represent a topological map of the human imagination?Can BigGAN predict object imageability? For example, picture a wall clock. Did you actually visualize all of the digits? Neither did BigGAN." }, { "code": null, "e": 6735, "s": 6674, "text": "Build a visualizer that responds to live music in real time." }, { "code": null, "e": 6874, "s": 6735, "text": "Use natural language processing to automatically select ImageNet classes based on semantic associations with song lyrics (or audio books)." }, { "code": null, "e": 7011, "s": 6874, "text": "Play music to people in fMRI, and interface the class and noise vectors with neural activity to create deep music videos from the brain." }, { "code": null, "e": 7040, "s": 7011, "text": "All of these simultaneously?" }, { "code": null, "e": 7217, "s": 7040, "text": "[1] A. Brock, J. Donahu and K. Simonyan, Large Scale GAN Training for High Fidelity Natural Image Synthesis (2018), Eighth International Conference on Learning Representations." } ]
LINQ - Dataset
A Dataset offers an extremely useful data representation in memory and is used for a diverse range of data based applications. LINQ to Dataset as one of the technology of LINQ to ADO.NET facilitates performing queries on the data of a Dataset in a hassle-free manner and enhance productivity. LINQ to Dataset has made the task of querying simple for the developers. They don’t need to write queries in a specific query language instead the same can be written in programming language. LINQ to Dataset is also usable for querying where data is consolidated from multiple data sources. This also does not need any LINQ provider just like LINQ to SQL and LINQ to XML for accessing data from in memory collections. Below is a simple example of a LINQ to Dataset query in which a data source is first obtained and then the dataset is filled with two data tables. A relationship is established between both the tables and a LINQ query is created against both tables by the means of join clause. Finally, foreach loop is used to display the desired results. using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQtoDataset { class Program { static void Main(string[] args) { string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString(); string sqlSelect = "SELECT * FROM Department;" + "SELECT * FROM Employee;"; // Create the data adapter to retrieve data from the database SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connectString); // Create table mappings da.TableMappings.Add("Table", "Department"); da.TableMappings.Add("Table1", "Employee"); // Create and fill the DataSet DataSet ds = new DataSet(); da.Fill(ds); DataRelation dr = ds.Relations.Add("FK_Employee_Department", ds.Tables["Department"].Columns["DepartmentId"], ds.Tables["Employee"].Columns["DepartmentId"]); DataTable department = ds.Tables["Department"]; DataTable employee = ds.Tables["Employee"]; var query = from d in department.AsEnumerable() join e in employee.AsEnumerable() on d.Field<int>("DepartmentId") equals e.Field<int>("DepartmentId") select new { EmployeeId = e.Field<int>("EmployeeId"), Name = e.Field<string>("Name"), DepartmentId = d.Field<int>("DepartmentId"), DepartmentName = d.Field<string>("Name") }; foreach (var q in query) { Console.WriteLine("Employee Id = {0} , Name = {1} , Department Name = {2}", q.EmployeeId, q.Name, q.DepartmentName); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } Imports System.Data.SqlClient Imports System.Linq Module LinqToDataSet Sub Main() Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString() Dim sqlSelect As String = "SELECT * FROM Department;" + "SELECT * FROM Employee;" Dim sqlCnn As SqlConnection = New SqlConnection(connectString) sqlCnn.Open() Dim da As New SqlDataAdapter da.SelectCommand = New SqlCommand(sqlSelect, sqlCnn) da.TableMappings.Add("Table", "Department") da.TableMappings.Add("Table1", "Employee") Dim ds As New DataSet() da.Fill(ds) Dim dr As DataRelation = ds.Relations.Add("FK_Employee_Department", ds.Tables("Department").Columns("DepartmentId"), ds.Tables("Employee").Columns("DepartmentId")) Dim department As DataTable = ds.Tables("Department") Dim employee As DataTable = ds.Tables("Employee") Dim query = From d In department.AsEnumerable() Join e In employee.AsEnumerable() On d.Field(Of Integer)("DepartmentId") Equals e.Field(Of Integer)("DepartmentId") Select New Person With { _ .EmployeeId = e.Field(Of Integer)("EmployeeId"), .EmployeeName = e.Field(Of String)("Name"), .DepartmentId = d.Field(Of Integer)("DepartmentId"), .DepartmentName = d.Field(Of String)("Name") } For Each e In query Console.WriteLine("Employee Id = {0} , Name = {1} , Department Name = {2}", e.EmployeeId, e.EmployeeName, e.DepartmentName) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub Class Person Public Property EmployeeId As Integer Public Property EmployeeName As String Public Property DepartmentId As Integer Public Property DepartmentName As String End Class End Module When the above code of C# or VB is compiled and executed, it produces the following result − Employee Id = 1, Name = William, Department Name = Account Employee Id = 2, Name = Benjamin, Department Name = Account Employee Id = 3, Name = Miley, Department Name = Sales Press any key to continue. Before beginning querying a Dataset using LINQ to Dataset, it is vital to load data to a Dataset and this is done by either using DataAdapter class or by LINQ to SQL. Formulation of queries using LINQ to Dataset is quite similar to formulating queries by using LINQ alongside other LINQ enabled data sources. In the following single-table query, all online orders are collected from the SalesOrderHeaderTtable and then order ID, Order date as well as order number are displayed as output. C# using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LinqToDataset { class SingleTable { static void Main(string[] args) { string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString(); string sqlSelect = "SELECT * FROM Department;"; // Create the data adapter to retrieve data from the database SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connectString); // Create table mappings da.TableMappings.Add("Table", "Department"); // Create and fill the DataSet DataSet ds = new DataSet(); da.Fill(ds); DataTable department = ds.Tables["Department"]; var query = from d in department.AsEnumerable() select new { DepartmentId = d.Field<int>("DepartmentId"), DepartmentName = d.Field<string>("Name") }; foreach (var q in query) { Console.WriteLine("Department Id = {0} , Name = {1}", q.DepartmentId, q.DepartmentName); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } VB Imports System.Data.SqlClient Imports System.Linq Module LinqToDataSet Sub Main() Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString() Dim sqlSelect As String = "SELECT * FROM Department;" Dim sqlCnn As SqlConnection = New SqlConnection(connectString) sqlCnn.Open() Dim da As New SqlDataAdapter da.SelectCommand = New SqlCommand(sqlSelect, sqlCnn) da.TableMappings.Add("Table", "Department") Dim ds As New DataSet() da.Fill(ds) Dim department As DataTable = ds.Tables("Department") Dim query = From d In department.AsEnumerable() Select New DepartmentDetail With { .DepartmentId = d.Field(Of Integer)("DepartmentId"), .DepartmentName = d.Field(Of String)("Name") } For Each e In query Console.WriteLine("Department Id = {0} , Name = {1}", e.DepartmentId, e.DepartmentName) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub Public Class DepartmentDetail Public Property DepartmentId As Integer Public Property DepartmentName As String End Class End Module When the above code of C# or VB is compiled and executed, it produces the following result − Department Id = 1, Name = Account Department Id = 2, Name = Sales Department Id = 3, Name = Pre-Sales Department Id = 4, Name = Marketing Press any key to continue. 23 Lectures 1.5 hours Anadi Sharma 37 Lectures 13 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2029, "s": 1736, "text": "A Dataset offers an extremely useful data representation in memory and is used for a diverse range of data based applications. LINQ to Dataset as one of the technology of LINQ to ADO.NET facilitates performing queries on the data of a Dataset in a hassle-free manner and enhance productivity." }, { "code": null, "e": 2447, "s": 2029, "text": "LINQ to Dataset has made the task of querying simple for the developers. They don’t need to write queries in a specific query language instead the same can be written in programming language. LINQ to Dataset is also usable for querying where data is consolidated from multiple data sources. This also does not need any LINQ provider just like LINQ to SQL and LINQ to XML for accessing data from in memory collections." }, { "code": null, "e": 2787, "s": 2447, "text": "Below is a simple example of a LINQ to Dataset query in which a data source is first obtained and then the dataset is filled with two data tables. A relationship is established between both the tables and a LINQ query is created against both tables by the means of join clause. Finally, foreach loop is used to display the desired results." }, { "code": null, "e": 4907, "s": 2787, "text": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace LINQtoDataset {\n class Program {\n static void Main(string[] args) {\n \n string connectString = System.Configuration.ConfigurationManager.ConnectionStrings[\"LinqToSQLDBConnectionString\"].ToString();\n\n string sqlSelect = \"SELECT * FROM Department;\" + \"SELECT * FROM Employee;\";\n\n // Create the data adapter to retrieve data from the database\n SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connectString);\n \n // Create table mappings\n da.TableMappings.Add(\"Table\", \"Department\");\n da.TableMappings.Add(\"Table1\", \"Employee\");\n\n // Create and fill the DataSet\n DataSet ds = new DataSet();\n da.Fill(ds);\n\n DataRelation dr = ds.Relations.Add(\"FK_Employee_Department\",\n ds.Tables[\"Department\"].Columns[\"DepartmentId\"],\n ds.Tables[\"Employee\"].Columns[\"DepartmentId\"]);\n\n DataTable department = ds.Tables[\"Department\"];\n DataTable employee = ds.Tables[\"Employee\"];\n\n var query = from d in department.AsEnumerable()\n join e in employee.AsEnumerable()\n on d.Field<int>(\"DepartmentId\") equals\n e.Field<int>(\"DepartmentId\") \n select new {\n EmployeeId = e.Field<int>(\"EmployeeId\"),\n Name = e.Field<string>(\"Name\"), \n DepartmentId = d.Field<int>(\"DepartmentId\"), \n DepartmentName = d.Field<string>(\"Name\")\n };\n\n foreach (var q in query) {\n Console.WriteLine(\"Employee Id = {0} , Name = {1} , Department Name = {2}\",\n q.EmployeeId, q.Name, q.DepartmentName);\n }\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 6906, "s": 4907, "text": "Imports System.Data.SqlClient\nImports System.Linq\n\nModule LinqToDataSet\n\n Sub Main()\n \n Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings(\"LinqToSQLDBConnectionString\").ToString()\n\n Dim sqlSelect As String = \"SELECT * FROM Department;\" + \"SELECT * FROM Employee;\"\n Dim sqlCnn As SqlConnection = New SqlConnection(connectString)\n sqlCnn.Open()\n\n Dim da As New SqlDataAdapter\n da.SelectCommand = New SqlCommand(sqlSelect, sqlCnn)\n\n da.TableMappings.Add(\"Table\", \"Department\")\n da.TableMappings.Add(\"Table1\", \"Employee\")\n\n Dim ds As New DataSet()\n da.Fill(ds)\n\n Dim dr As DataRelation = ds.Relations.Add(\"FK_Employee_Department\", ds.Tables(\"Department\").Columns(\"DepartmentId\"), ds.Tables(\"Employee\").Columns(\"DepartmentId\"))\n\n Dim department As DataTable = ds.Tables(\"Department\")\n Dim employee As DataTable = ds.Tables(\"Employee\")\n\n Dim query = From d In department.AsEnumerable()\n Join e In employee.AsEnumerable() On d.Field(Of Integer)(\"DepartmentId\") Equals\n e.Field(Of Integer)(\"DepartmentId\")\n Select New Person With { _\n .EmployeeId = e.Field(Of Integer)(\"EmployeeId\"),\n .EmployeeName = e.Field(Of String)(\"Name\"),\n .DepartmentId = d.Field(Of Integer)(\"DepartmentId\"),\n .DepartmentName = d.Field(Of String)(\"Name\")\n }\n\n For Each e In query\n Console.WriteLine(\"Employee Id = {0} , Name = {1} , Department Name = {2}\", e.EmployeeId, e.EmployeeName, e.DepartmentName)\n Next\n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n\t \n End Sub\n \n Class Person\n Public Property EmployeeId As Integer\n Public Property EmployeeName As String\n Public Property DepartmentId As Integer\n Public Property DepartmentName As String\n End Class\n \nEnd Module" }, { "code": null, "e": 6999, "s": 6906, "text": "When the above code of C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 7202, "s": 6999, "text": "Employee Id = 1, Name = William, Department Name = Account\nEmployee Id = 2, Name = Benjamin, Department Name = Account\nEmployee Id = 3, Name = Miley, Department Name = Sales\n\nPress any key to continue.\n" }, { "code": null, "e": 7511, "s": 7202, "text": "Before beginning querying a Dataset using LINQ to Dataset, it is vital to load data to a Dataset and this is done by either using DataAdapter class or by LINQ to SQL. Formulation of queries using LINQ to Dataset is quite similar to formulating queries by using LINQ alongside other LINQ enabled data sources." }, { "code": null, "e": 7691, "s": 7511, "text": "In the following single-table query, all online orders are collected from the SalesOrderHeaderTtable and then order ID, Order date as well as order number are displayed as output." }, { "code": null, "e": 7694, "s": 7691, "text": "C#" }, { "code": null, "e": 9059, "s": 7694, "text": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace LinqToDataset {\n class SingleTable {\n static void Main(string[] args) {\n \n string connectString = System.Configuration.ConfigurationManager.ConnectionStrings[\"LinqToSQLDBConnectionString\"].ToString();\n\n string sqlSelect = \"SELECT * FROM Department;\";\n\n // Create the data adapter to retrieve data from the database\n SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connectString);\n\n // Create table mappings\n da.TableMappings.Add(\"Table\", \"Department\"); \n\n // Create and fill the DataSet\n DataSet ds = new DataSet();\n da.Fill(ds);\n\n DataTable department = ds.Tables[\"Department\"]; \n\n var query = from d in department.AsEnumerable() \n select new {\n DepartmentId = d.Field<int>(\"DepartmentId\"),\n DepartmentName = d.Field<string>(\"Name\")\n };\n\n foreach (var q in query) {\n Console.WriteLine(\"Department Id = {0} , Name = {1}\",\n q.DepartmentId, q.DepartmentName);\n }\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 9062, "s": 9059, "text": "VB" }, { "code": null, "e": 10306, "s": 9062, "text": "Imports System.Data.SqlClient\nImports System.Linq\n\nModule LinqToDataSet\n\n Sub Main()\n \n Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings(\"LinqToSQLDBConnectionString\").ToString()\n\n Dim sqlSelect As String = \"SELECT * FROM Department;\"\n Dim sqlCnn As SqlConnection = New SqlConnection(connectString)\n sqlCnn.Open()\n\n Dim da As New SqlDataAdapter\n da.SelectCommand = New SqlCommand(sqlSelect, sqlCnn)\n\n da.TableMappings.Add(\"Table\", \"Department\")\n Dim ds As New DataSet()\n da.Fill(ds)\n\n Dim department As DataTable = ds.Tables(\"Department\")\n\n Dim query = From d In department.AsEnumerable()\n Select New DepartmentDetail With {\n .DepartmentId = d.Field(Of Integer)(\"DepartmentId\"),\n .DepartmentName = d.Field(Of String)(\"Name\")\n }\n\n For Each e In query\n Console.WriteLine(\"Department Id = {0} , Name = {1}\", e.DepartmentId, e.DepartmentName)\n Next\n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n End Sub\n\n Public Class DepartmentDetail\n Public Property DepartmentId As Integer\n Public Property DepartmentName As String\n End Class\n \nEnd Module" }, { "code": null, "e": 10399, "s": 10306, "text": "When the above code of C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 10566, "s": 10399, "text": "Department Id = 1, Name = Account\nDepartment Id = 2, Name = Sales\nDepartment Id = 3, Name = Pre-Sales\nDepartment Id = 4, Name = Marketing\n\nPress any key to continue.\n" }, { "code": null, "e": 10601, "s": 10566, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10615, "s": 10601, "text": " Anadi Sharma" }, { "code": null, "e": 10649, "s": 10615, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 10667, "s": 10649, "text": " Trevoir Williams" }, { "code": null, "e": 10674, "s": 10667, "text": " Print" }, { "code": null, "e": 10685, "s": 10674, "text": " Add Notes" } ]
java.lang.reflect.Method.getModifiers() Method Example
The java.lang.reflect.Method.getModifiers() method returns the Java language modifiers for the method represented by this Method object, as an integer. The Modifier class should be used to decode the modifiers. Following is the declaration for java.lang.reflect.Method.getModifiers() method. public int getModifiers() the Java language modifiers for the underlying member. The following example shows the usage of java.lang.reflect.Method.getModifiers() method. package com.tutorialspoint; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class MethodDemo { public static void main(String[] args) { Method[] methods = SampleClass.class.getMethods(); for (Method method : methods) { System.out.println("Modifier: " + Modifier.toString(method.getModifiers())); System.out.println("Method: " + method.toGenericString()); } } } class SampleClass { private String sampleField; public String getSampleField() throws ArrayIndexOutOfBoundsException { return sampleField; } public void setSampleField(String sampleField) { this.sampleField = sampleField; } } Let us compile and run the above program, this will produce the following result − Modifier: public Method: public java.lang.String com.tutorialspoint.SampleClass.getSampleField() throws java.lang.ArrayIndexOutOfBoundsException Modifier: public Method: public void com.tutorialspoint.SampleClass.setSampleField(java.lang.String) Modifier: public final Method: public final void java.lang.Object.wait() throws java.lang.InterruptedException Modifier: public final Method: public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException Modifier: public final native Method: public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException Modifier: public Method: public boolean java.lang.Object.equals(java.lang.Object) Modifier: public Method: public java.lang.String java.lang.Object.toString() Modifier: public native Method: public native int java.lang.Object.hashCode() Modifier: public final native Method: public final native java.lang.Class<?> java.lang.Object.getClass() Modifier: public final native Method: public final native void java.lang.Object.notify() Modifier: public final native Method: public final native void java.lang.Object.notifyAll() Print Add Notes Bookmark this page
[ { "code": null, "e": 1665, "s": 1454, "text": "The java.lang.reflect.Method.getModifiers() method returns the Java language modifiers for the method represented by this Method object, as an integer. The Modifier class should be used to decode the modifiers." }, { "code": null, "e": 1746, "s": 1665, "text": "Following is the declaration for java.lang.reflect.Method.getModifiers() method." }, { "code": null, "e": 1773, "s": 1746, "text": "public int getModifiers()\n" }, { "code": null, "e": 1828, "s": 1773, "text": "the Java language modifiers for the underlying member." }, { "code": null, "e": 1917, "s": 1828, "text": "The following example shows the usage of java.lang.reflect.Method.getModifiers() method." }, { "code": null, "e": 2609, "s": 1917, "text": "package com.tutorialspoint;\n\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\n\npublic class MethodDemo {\n\n public static void main(String[] args) {\n\n Method[] methods = SampleClass.class.getMethods();\n for (Method method : methods) {\n System.out.println(\"Modifier: \" + Modifier.toString(method.getModifiers()));\n System.out.println(\"Method: \" + method.toGenericString());\n }\n }\n}\n\nclass SampleClass {\n private String sampleField;\n\n public String getSampleField() throws ArrayIndexOutOfBoundsException {\n return sampleField;\n }\n\n public void setSampleField(String sampleField) {\n this.sampleField = sampleField; \n } \n}" }, { "code": null, "e": 2692, "s": 2609, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3821, "s": 2692, "text": "Modifier: public\nMethod: public java.lang.String com.tutorialspoint.SampleClass.getSampleField() throws java.lang.ArrayIndexOutOfBoundsException\nModifier: public\nMethod: public void com.tutorialspoint.SampleClass.setSampleField(java.lang.String)\nModifier: public final\nMethod: public final void java.lang.Object.wait() throws java.lang.InterruptedException\nModifier: public final\nMethod: public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException\nModifier: public final native\nMethod: public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException\nModifier: public\nMethod: public boolean java.lang.Object.equals(java.lang.Object)\nModifier: public\nMethod: public java.lang.String java.lang.Object.toString()\nModifier: public native\nMethod: public native int java.lang.Object.hashCode()\nModifier: public final native\nMethod: public final native java.lang.Class<?> java.lang.Object.getClass()\nModifier: public final native\nMethod: public final native void java.lang.Object.notify()\nModifier: public final native\nMethod: public final native void java.lang.Object.notifyAll()\n" }, { "code": null, "e": 3828, "s": 3821, "text": " Print" }, { "code": null, "e": 3839, "s": 3828, "text": " Add Notes" } ]
Python String find() Method
Python string method find() determines if string str occurs in string, or in a substring of string if starting index beg and ending index end are given. str.find(str, beg=0, end=len(string)) str − This specifies the string to be searched. str − This specifies the string to be searched. beg − This is the starting index, by default its 0. beg − This is the starting index, by default its 0. end − This is the ending index, by default its equal to the length of the string. end − This is the ending index, by default its equal to the length of the string. Index if found and -1 otherwise. #!/usr/bin/python str1 = "this is string example....wow!!!"; str2 = "exam"; print str1.find(str2) print str1.find(str2, 10) print str1.find(str2, 40) 15 15 -1 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2397, "s": 2244, "text": "Python string method find() determines if string str occurs in string, or in a substring of string if starting index beg and ending index end are given." }, { "code": null, "e": 2436, "s": 2397, "text": "str.find(str, beg=0, end=len(string))\n" }, { "code": null, "e": 2484, "s": 2436, "text": "str − This specifies the string to be searched." }, { "code": null, "e": 2532, "s": 2484, "text": "str − This specifies the string to be searched." }, { "code": null, "e": 2584, "s": 2532, "text": "beg − This is the starting index, by default its 0." }, { "code": null, "e": 2636, "s": 2584, "text": "beg − This is the starting index, by default its 0." }, { "code": null, "e": 2718, "s": 2636, "text": "end − This is the ending index, by default its equal to the length of the string." }, { "code": null, "e": 2800, "s": 2718, "text": "end − This is the ending index, by default its equal to the length of the string." }, { "code": null, "e": 2833, "s": 2800, "text": "Index if found and -1 otherwise." }, { "code": null, "e": 2985, "s": 2833, "text": "#!/usr/bin/python\n\nstr1 = \"this is string example....wow!!!\";\nstr2 = \"exam\";\n\nprint str1.find(str2)\nprint str1.find(str2, 10)\nprint str1.find(str2, 40)" }, { "code": null, "e": 2995, "s": 2985, "text": "15\n15\n-1\n" }, { "code": null, "e": 3032, "s": 2995, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3048, "s": 3032, "text": " Malhar Lathkar" }, { "code": null, "e": 3081, "s": 3048, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3100, "s": 3081, "text": " Arnab Chakraborty" }, { "code": null, "e": 3135, "s": 3100, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3157, "s": 3135, "text": " In28Minutes Official" }, { "code": null, "e": 3191, "s": 3157, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3219, "s": 3191, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3254, "s": 3219, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3268, "s": 3254, "text": " Lets Kode It" }, { "code": null, "e": 3301, "s": 3268, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3318, "s": 3301, "text": " Abhilash Nelson" }, { "code": null, "e": 3325, "s": 3318, "text": " Print" }, { "code": null, "e": 3336, "s": 3325, "text": " Add Notes" } ]
Causal Inference using Difference in Differences, Causal Impact, and Synthetic Control | by Prasanna Rajendran | Towards Data Science
Correlation is not causation. Then what is causation? How can it be measured? Causation is measuring the real impact on Y because of X. E.g., What is the effect of ad campaigns on the sales of a product? It is critical to precisely understand the causal effects of these interventions on the subject. One of the main threats to causal inference is the confounding effect from other variables. In the case of ad campaigns, it could be a reduction in price of the product, change in the overall economy or various other factors that could be inducing the change in sales at the same time. So how do we correctly attribute the change in sales because of the ad campaign? There are two ways to estimate the true causal impact of the intervention on the subject. Randomized experiment: It’s the most reliable method to infer the actual causal impact of the treatment, where we induce a change in the process at random and measure the corresponding change in the outcome variable. However, in most cases, it would be impossible to conduct experiments and control the whole system to be truly at random. Causal Inference in Econometrics: This method involves the application of statistical procedures to the data that is available already to arrive at the causal estimate while controlling for confounders. Some approaches under this method are what we’ll be looking at in this analysis. The following are the approaches: Difference in Differences (DD) Causal Impact Synthetic Control The Basque dataset will be used for demonstration. Using this data, we’ll estimate the true economic impact of terrorist conflict in the Basque country, an autonomous community in Spain, with the help of data from 17 other regions. Let’s look at some facts about the data and the experimental design. The dataset contains information from the year 1955–1997 Information about 18 Spanish regions is available- One of which is average for the whole country of Spain (we’ll remove that) The treatment year is considered to be the year 1975 The treatment region is “Basque Country (Pais Vasco)” The economic impact measurement variable is GDP per capita (in thousands) The analysis has been done in R and the source codes can be found in my GitHub. We’ll get started with the approaches mentioned. Before going into Difference in Differences method, let’s look at First Differences and what it does. Our goal here is to quantify the impact of GDP before and after the terrorist conflict in the Basque country. In a naive way, we can actually achieve this by constructing a first difference regression and observing the estimate. Let’s look at the general trend of GDP per capita for the Basque country. From the graph, we can see how the trend plunges right after the terrorist intervention and then increases back all over again. Our goal is to identify the magnitude of the plunge that we see. The first difference estimate will tell us the difference in GDP before and after the treatment. Let’s construct a first difference equation by having GDP as the dependent variable and pre-post indicator as the independent variable. f_did <- lm(data = basq_fdid, gdpcap ~ post)stargazer(f_did, type=”text”) The coefficient of post indicator suggests that there is an increase in GDP per capita by ~2.5 units being in the post period and that’s not quite what we want because we want to capture the declining trend. That’s because there’s an expected problem as we mentioned earlier. The trend in GDP could have been altered because of a lot of other variables, besides the terrorist conflict, occurring at the same time — otherwise known as confounders. Possible confounders in this case are: Passing of a trade law which would affect local businesses and GDP Mutiny within local groups Perception of corrupt or dysfunctional government The solution to this is to compare the trend to a control region which was not impacted by terrorist conflict. This comparison allows us to remove the confounding effect after the intervention period and arrive at the real causal impact. That’s where the Difference in differences method helps. The underlying assumption of Difference-in-Differences (DD) design is that the trend of the control group provides an adequate proxy for the trend that would have been observed in the treatment group in the absence of treatment. Thus, the difference in change of slope would be the actual treatment effect. The assumption here is that there treatment group and control group must follow the same trend in the pre-period. For this analysis, the control region was identified by spotting for the region that had the lowest variation in % difference of GDP across years between each region and the Basque country. Alternatively, we can look for the control region by eyeballing the GDP trend for treatment and control groups when feasible. In this case, Cataluna region was recognized to be the best control region. Let’s look at the GDP trend for test and control regions below: GDP trend for Cataluna region goes hand in hand with Basque’s GDP with an exception for a few years in the pre-period. Thus, there should be no problem in considering Cataluna to be our control region. Let’s go ahead and fit the regression with GDP as the dependent variable and treatment indicator and a pre-post indicator as independent variables. The critical aspect here is to feed the interaction between treatment and pre-post indicator as we want the estimate to contain the effect of being treated along with being in post-period in comparison to not being treated and being in pre-period. After fitting, let’s look at the regression results below: did <- lm(data = did_data, gdpcap ~ treat*post)stargazer(did, type=”text”) Looking at the estimate of the interaction variable suggests that the GDP in Basque country reduced by 0.85 units because of the terrorist intervention that happened. Now there is a stark difference between estimates provided by First difference method and the DD method. Quantitatively, we can see how the First difference estimates could be deceiving and naive to look at. If you’re interested, you can read more about Difference in difference here. For now, let’s move on to other causal inference methods. Causal Impact is a methodology developed by Google to estimate the causal impact of a treatment in the treated group. The official documentation can be found here. The motivation to use Causal Impact methodology is that the Difference in differences in limited in the following ways: DD is traditionally based on a static regression model that assumes independent and identically distributed data despite the fact that the design has a temporal component Most DD analyses only consider two time points: before and after the intervention. In practice, we also have to consider the manner in which an effect evolves over time, especially its onset and decay structure The idea here is to use the trend in the control group to forecast the trend in the treated group which would be the trend if the treatment had not happened. Then the actual causal estimate would be the difference in the actual trend vs. the counter-factual trend of the treated group that we predicted. Causal Impact uses Bayesian structural time-series models to explain the temporal evolution of an observed outcome. Essentially, Causal Impact methodology is very close to the Synthetic control methodology we are going to see next. Control region, in this case, is considered to be Cataluna again. With the treated and control region’s GDP in place, let’s feed them to the Causal Impact function in R and look at the results. pre.period <- as.Date(c(“1955–01–01”, “1975–01–01”))post.period <- as.Date(c(“1976–01–01”, “1997–01–01”))impact <- CausalImpact(basq_CI, pre.period, post.period)summary(impact) The Absolute effect is the difference in GDP between the actual GDP after the treatment and the counter-factual GDP. From the results, we can see the absolute effect gives us a value of -0.76 which means that the GDP per capita reduced by 0.76 units, i.e., 8.8% because of the terrorist conflict that happened in the Basque country. This is almost equal to the estimate we saw using Difference in Differences method. For those interested in Causal Impact, an exhaustive explanation of the method is given by the authors of this method that can be found here. Synthetic control is a technique which is very similar to Causal Impact in estimating the true impact of a treatment. Both the methods use the help of control groups to construct a counter-factual of the treated group giving us an idea of what the trend is if the treatment had not happened. The counter-factual GDP of the treated group would be predicted by the GDP of the control groups and also other possible covariates in the control group. The synth algorithm predicts the counter-factual by assigning weights to the regressors in the control groups which helps identify individual regressors and their influence in prediction. Ultimately, the true causal impact is the difference in GDP between actual GDP and the counter-factual GDP if the treatment had not happened. The difference between Synthetic Control and Causal Impact is that Synthetic Control uses only pre-treatment variables for matching while Causal Impact uses the full pre and post-treatment time series of predictor variables for matching. Let’s look at a plot for GDP trend in all the 17 other regions in the data. As seen from the plot above, all the control regions have a similar upward trend in GDP as Basque country’s in the pre-period. This suggests that GDP in Basque could be constructed fairly accurately using the data from other regions. The implementation of synthetic control on this problem statement has already been given in the official documentation of the package found here. After execution, Let’s look at the plot between actual GDP and the counter-factual GDP. The path-graph shows how the smooth relationship is between the synthetic and actual trend in the pre-period and how it deviates gradually once the treatment happens. That difference in trends in the post-period would be our average treatment effect. The root mean squared error of the Actual and Synthetic trends were found to be 0.57 units. We can conclude that the true causal impact of terrorist conflict on Basque country is a reduction of GDP by 0.57 units calculated using Synthetic control method. Let’s look at the comparison of results from all three methods below: The magnitude of the causal impact differs only by a small margin between the three methods, and there is no method which will give us the “correct answer.” Most times, the approaches we use will be restricted by the nature of the experiment and what causal threats we are trying to address. Some other techniques useful for inferring causal impact are Propensity score Matching, Fixed Effects Regression, Instrumental variables, and Regression Discontinuity.
[ { "code": null, "e": 250, "s": 172, "text": "Correlation is not causation. Then what is causation? How can it be measured?" }, { "code": null, "e": 376, "s": 250, "text": "Causation is measuring the real impact on Y because of X. E.g., What is the effect of ad campaigns on the sales of a product?" }, { "code": null, "e": 840, "s": 376, "text": "It is critical to precisely understand the causal effects of these interventions on the subject. One of the main threats to causal inference is the confounding effect from other variables. In the case of ad campaigns, it could be a reduction in price of the product, change in the overall economy or various other factors that could be inducing the change in sales at the same time. So how do we correctly attribute the change in sales because of the ad campaign?" }, { "code": null, "e": 930, "s": 840, "text": "There are two ways to estimate the true causal impact of the intervention on the subject." }, { "code": null, "e": 1269, "s": 930, "text": "Randomized experiment: It’s the most reliable method to infer the actual causal impact of the treatment, where we induce a change in the process at random and measure the corresponding change in the outcome variable. However, in most cases, it would be impossible to conduct experiments and control the whole system to be truly at random." }, { "code": null, "e": 1587, "s": 1269, "text": "Causal Inference in Econometrics: This method involves the application of statistical procedures to the data that is available already to arrive at the causal estimate while controlling for confounders. Some approaches under this method are what we’ll be looking at in this analysis. The following are the approaches:" }, { "code": null, "e": 1618, "s": 1587, "text": "Difference in Differences (DD)" }, { "code": null, "e": 1632, "s": 1618, "text": "Causal Impact" }, { "code": null, "e": 1650, "s": 1632, "text": "Synthetic Control" }, { "code": null, "e": 1951, "s": 1650, "text": "The Basque dataset will be used for demonstration. Using this data, we’ll estimate the true economic impact of terrorist conflict in the Basque country, an autonomous community in Spain, with the help of data from 17 other regions. Let’s look at some facts about the data and the experimental design." }, { "code": null, "e": 2008, "s": 1951, "text": "The dataset contains information from the year 1955–1997" }, { "code": null, "e": 2134, "s": 2008, "text": "Information about 18 Spanish regions is available- One of which is average for the whole country of Spain (we’ll remove that)" }, { "code": null, "e": 2187, "s": 2134, "text": "The treatment year is considered to be the year 1975" }, { "code": null, "e": 2241, "s": 2187, "text": "The treatment region is “Basque Country (Pais Vasco)”" }, { "code": null, "e": 2315, "s": 2241, "text": "The economic impact measurement variable is GDP per capita (in thousands)" }, { "code": null, "e": 2444, "s": 2315, "text": "The analysis has been done in R and the source codes can be found in my GitHub. We’ll get started with the approaches mentioned." }, { "code": null, "e": 2849, "s": 2444, "text": "Before going into Difference in Differences method, let’s look at First Differences and what it does. Our goal here is to quantify the impact of GDP before and after the terrorist conflict in the Basque country. In a naive way, we can actually achieve this by constructing a first difference regression and observing the estimate. Let’s look at the general trend of GDP per capita for the Basque country." }, { "code": null, "e": 3275, "s": 2849, "text": "From the graph, we can see how the trend plunges right after the terrorist intervention and then increases back all over again. Our goal is to identify the magnitude of the plunge that we see. The first difference estimate will tell us the difference in GDP before and after the treatment. Let’s construct a first difference equation by having GDP as the dependent variable and pre-post indicator as the independent variable." }, { "code": null, "e": 3349, "s": 3275, "text": "f_did <- lm(data = basq_fdid, gdpcap ~ post)stargazer(f_did, type=”text”)" }, { "code": null, "e": 3557, "s": 3349, "text": "The coefficient of post indicator suggests that there is an increase in GDP per capita by ~2.5 units being in the post period and that’s not quite what we want because we want to capture the declining trend." }, { "code": null, "e": 3835, "s": 3557, "text": "That’s because there’s an expected problem as we mentioned earlier. The trend in GDP could have been altered because of a lot of other variables, besides the terrorist conflict, occurring at the same time — otherwise known as confounders. Possible confounders in this case are:" }, { "code": null, "e": 3902, "s": 3835, "text": "Passing of a trade law which would affect local businesses and GDP" }, { "code": null, "e": 3929, "s": 3902, "text": "Mutiny within local groups" }, { "code": null, "e": 3979, "s": 3929, "text": "Perception of corrupt or dysfunctional government" }, { "code": null, "e": 4274, "s": 3979, "text": "The solution to this is to compare the trend to a control region which was not impacted by terrorist conflict. This comparison allows us to remove the confounding effect after the intervention period and arrive at the real causal impact. That’s where the Difference in differences method helps." }, { "code": null, "e": 4695, "s": 4274, "text": "The underlying assumption of Difference-in-Differences (DD) design is that the trend of the control group provides an adequate proxy for the trend that would have been observed in the treatment group in the absence of treatment. Thus, the difference in change of slope would be the actual treatment effect. The assumption here is that there treatment group and control group must follow the same trend in the pre-period." }, { "code": null, "e": 5151, "s": 4695, "text": "For this analysis, the control region was identified by spotting for the region that had the lowest variation in % difference of GDP across years between each region and the Basque country. Alternatively, we can look for the control region by eyeballing the GDP trend for treatment and control groups when feasible. In this case, Cataluna region was recognized to be the best control region. Let’s look at the GDP trend for test and control regions below:" }, { "code": null, "e": 5353, "s": 5151, "text": "GDP trend for Cataluna region goes hand in hand with Basque’s GDP with an exception for a few years in the pre-period. Thus, there should be no problem in considering Cataluna to be our control region." }, { "code": null, "e": 5808, "s": 5353, "text": "Let’s go ahead and fit the regression with GDP as the dependent variable and treatment indicator and a pre-post indicator as independent variables. The critical aspect here is to feed the interaction between treatment and pre-post indicator as we want the estimate to contain the effect of being treated along with being in post-period in comparison to not being treated and being in pre-period. After fitting, let’s look at the regression results below:" }, { "code": null, "e": 5883, "s": 5808, "text": "did <- lm(data = did_data, gdpcap ~ treat*post)stargazer(did, type=”text”)" }, { "code": null, "e": 6258, "s": 5883, "text": "Looking at the estimate of the interaction variable suggests that the GDP in Basque country reduced by 0.85 units because of the terrorist intervention that happened. Now there is a stark difference between estimates provided by First difference method and the DD method. Quantitatively, we can see how the First difference estimates could be deceiving and naive to look at." }, { "code": null, "e": 6393, "s": 6258, "text": "If you’re interested, you can read more about Difference in difference here. For now, let’s move on to other causal inference methods." }, { "code": null, "e": 6557, "s": 6393, "text": "Causal Impact is a methodology developed by Google to estimate the causal impact of a treatment in the treated group. The official documentation can be found here." }, { "code": null, "e": 6677, "s": 6557, "text": "The motivation to use Causal Impact methodology is that the Difference in differences in limited in the following ways:" }, { "code": null, "e": 6848, "s": 6677, "text": "DD is traditionally based on a static regression model that assumes independent and identically distributed data despite the fact that the design has a temporal component" }, { "code": null, "e": 7059, "s": 6848, "text": "Most DD analyses only consider two time points: before and after the intervention. In practice, we also have to consider the manner in which an effect evolves over time, especially its onset and decay structure" }, { "code": null, "e": 7595, "s": 7059, "text": "The idea here is to use the trend in the control group to forecast the trend in the treated group which would be the trend if the treatment had not happened. Then the actual causal estimate would be the difference in the actual trend vs. the counter-factual trend of the treated group that we predicted. Causal Impact uses Bayesian structural time-series models to explain the temporal evolution of an observed outcome. Essentially, Causal Impact methodology is very close to the Synthetic control methodology we are going to see next." }, { "code": null, "e": 7789, "s": 7595, "text": "Control region, in this case, is considered to be Cataluna again. With the treated and control region’s GDP in place, let’s feed them to the Causal Impact function in R and look at the results." }, { "code": null, "e": 7966, "s": 7789, "text": "pre.period <- as.Date(c(“1955–01–01”, “1975–01–01”))post.period <- as.Date(c(“1976–01–01”, “1997–01–01”))impact <- CausalImpact(basq_CI, pre.period, post.period)summary(impact)" }, { "code": null, "e": 8525, "s": 7966, "text": "The Absolute effect is the difference in GDP between the actual GDP after the treatment and the counter-factual GDP. From the results, we can see the absolute effect gives us a value of -0.76 which means that the GDP per capita reduced by 0.76 units, i.e., 8.8% because of the terrorist conflict that happened in the Basque country. This is almost equal to the estimate we saw using Difference in Differences method. For those interested in Causal Impact, an exhaustive explanation of the method is given by the authors of this method that can be found here." }, { "code": null, "e": 9301, "s": 8525, "text": "Synthetic control is a technique which is very similar to Causal Impact in estimating the true impact of a treatment. Both the methods use the help of control groups to construct a counter-factual of the treated group giving us an idea of what the trend is if the treatment had not happened. The counter-factual GDP of the treated group would be predicted by the GDP of the control groups and also other possible covariates in the control group. The synth algorithm predicts the counter-factual by assigning weights to the regressors in the control groups which helps identify individual regressors and their influence in prediction. Ultimately, the true causal impact is the difference in GDP between actual GDP and the counter-factual GDP if the treatment had not happened." }, { "code": null, "e": 9615, "s": 9301, "text": "The difference between Synthetic Control and Causal Impact is that Synthetic Control uses only pre-treatment variables for matching while Causal Impact uses the full pre and post-treatment time series of predictor variables for matching. Let’s look at a plot for GDP trend in all the 17 other regions in the data." }, { "code": null, "e": 9849, "s": 9615, "text": "As seen from the plot above, all the control regions have a similar upward trend in GDP as Basque country’s in the pre-period. This suggests that GDP in Basque could be constructed fairly accurately using the data from other regions." }, { "code": null, "e": 10083, "s": 9849, "text": "The implementation of synthetic control on this problem statement has already been given in the official documentation of the package found here. After execution, Let’s look at the plot between actual GDP and the counter-factual GDP." }, { "code": null, "e": 10334, "s": 10083, "text": "The path-graph shows how the smooth relationship is between the synthetic and actual trend in the pre-period and how it deviates gradually once the treatment happens. That difference in trends in the post-period would be our average treatment effect." }, { "code": null, "e": 10589, "s": 10334, "text": "The root mean squared error of the Actual and Synthetic trends were found to be 0.57 units. We can conclude that the true causal impact of terrorist conflict on Basque country is a reduction of GDP by 0.57 units calculated using Synthetic control method." }, { "code": null, "e": 10659, "s": 10589, "text": "Let’s look at the comparison of results from all three methods below:" }, { "code": null, "e": 10951, "s": 10659, "text": "The magnitude of the causal impact differs only by a small margin between the three methods, and there is no method which will give us the “correct answer.” Most times, the approaches we use will be restricted by the nature of the experiment and what causal threats we are trying to address." } ]
Multi-Armed Bandits: Thompson Sampling Algorithm with Python Code | Towards Data Science
In this series of posts, we experiment with different bandit algorithms to optimise our movie nights — more specifically, how we select movies and restaurants for food delivery! For newcomers, the name bandit comes from slot machines (known as one-armed bandits). You can think of it as something that can reward you (or not) every time you interact with it (pull its arm). The objective is, given a bunch of bandits that give different rewards, to identify the one that gives the highest ones, as fast as possible. As we start playing and continuously collect data about each bandit, the bandit algorithm helps us choose between exploiting the one that gave us the highest rewards so far and exploring others. medium.com towardsdatascience.com You and your friend have been using bandit algorithms to optimise which restaurants and movies to choose for your weekly movie night. So far, you have tried different bandits algorithms like Epsilon-Greedy, Optimistic Initial Values and Upper Confidence Bounds (UCB). You’ve found the UCB1-Tuned algorithm to work slightly better than the rest, for both Bernoulli and Normal rewards, and have ended up using it for the last few months. Even though your movie nights have been going great with the choices made by UCB1-Tuned, you miss the thrill of trying a new algorithm out. “Have you heard of Thompson Sampling?” your friend asks. Excited you pick up your phone and start reading about it. Thompson Sampling, otherwise known as Bayesian Bandits, is the Bayesian approach to the multi-armed bandits problem. The basic idea is to treat the average reward μ from each bandit as a random variable and use the data we have collected so far to calculate its distribution. Then, at each step, we will sample a point from each bandit’s average reward distribution and select the one whose sample had the highest value. We subsequently get the reward from the selected bandit and update its average reward distribution. How do we calculate/update distributions I hear you ask? The name Bayesian Bandits might have already given this away, but we will use Bayes Theorem. Bayes Theorem P(A|B) = P(B|A) P(A) / P(B)where A, B: events in sample space P(A|B): conditional probability of A given B P(B|A): conditional probability of B given A P(A): probability of A P(B): probability of B The above definition is for discrete variables, for continuous variables it is defined for probability density functions. In our case, for each bandit, we want to calculate their P( μ | data ), i.e., how likely different values of μ are, given the data we have collected so far. P( μ | data ) = P(data | μ) P(μ) / P(data) ∝ P(data | μ) P(μ) posterior ∝ likelihood x prior Bandits with many data points will have a narrow distribution hence the data point we sample will have a high chance of being close to the real mean. Bandits with few data points, however, will have a wide distribution giving high values a good chance of being selected. This mechanism is what balances exploration vs exploitation. Now, calculating P( μ | data ) is tricky unless the likelihood and prior are conjugate priors. This means, that when we combine the likelihood and the prior we get a posterior distribution from the same family as the prior. This is convenient for two reasons: We can avoid nasty calculations for finding out what the posterior is since there is a closed-form expression for it. We can use the posterior from step i-1 as the prior for step i. This makes going from P( μ | data up to step i-1) to P( μ | data up to step i) easy and ensures we only work with conjugate priors. For the rest of this post, we will assume that a bandit gives a reward of 1 with probability μ and 0 otherwise, i.e. ith bandit rewards ~ Bernoulli(prob = μ_i) Now we need to choose a prior distribution for μ. Since μ is the probability of success, it can only take values between 0 to 1. Hence we need a distribution with support [0, 1]. One such distribution is the Beta distribution with parameters a and b. Before we collect any data, all values of μ are equally likely, hence a uniform prior over [0, 1] would make sense. Choosing a = 1 and b = 1 gives us exactly that. Next, we need to pick a likelihood and preferably one for which the Beta distribution is a conjugate prior. The Binomial distribution satisfies this and it also makes sense for our use case as it models the probability of getting k successes (sum of a bandit’s rewards) out of N trials (number of times we played the bandit) with a probability of success p (this is the μ we are trying to estimate). If Prior is μ ~ Beta(α, β) Likelihood is k | μ ~ Binomial(N, μ)Then Posterior is μ ~ Beta(α + successes, β + failures)Where N = successes + failures This is a simple update rule, if the reward from a bandit is 1 we increment its a if it is 0 we increment its b. We have defined the base classes you will see here in the previous posts, but they are included again for completeness. The code below defines the class BernoulliBandit that represents the bandits, the base class Agent to represent agents and the helper class BanditRewardsLog that will keep track of the rewards. Now, the only thing left is to subclass the Agent class and implement Thompson Sampling. ... and we are done! Now, let’s see how it holds up against the algorithms from the previous posts, namely, Epsilon-Greedy, Optimistic Initial Values and Upper Confidence Bounds (UCB). We will use the following code to compare the different algorithms. First, let’s define our bandits. probs = [0.6, 0.7, 0.8, 0.9]bernoulli_bandits = [BernoulliBandit(p) for p in probs] After this, we can simply run compare_agents( get_agents(), bernoulli_bandits, iterations=500, show_plot=True,) which gives us the following. Hmm ... it’s not very clear, but it seems like Epsilon-Greedy and Bayesian Bandits have similar performances. To find the best one, let us repeat the above experiment and count how many times each algorithm got the best result. wins = run_comparison(bernoulli_bandits)for g, w in zip(get_agents(), wins): print(g, w) My results were 397 wins for Epsilon-Greedy, 0 for UCB1, 220 for UCB1-Tuned and 383 for Thompson Sampling. It looks like Thompson Sampling and Epsilon-Greedy are the winners for our specific setting. UCB1-Tuned coming in third place is a bit surprising given that in previous experiments it outperformed the Epsilon-Greedy algorithm. This could be due to the fact that Thompson Sampling is stealing some of its wins, but this needs more investigation. In this post, we have looked into how the Thompson Sampling algorithm works and implemented it for Bernoulli bandits. We then compared it to other multi-armed bandits algorithms and saw that it performed about the same as Epsilon-Greedy. Become a member of Medium and get full access to all stories. Your membership fee directly supports the writers you read. From the same author. towardsdatascience.com medium.com [1] A Tutorial on Thompson Sampling. (n.d.). Retrieved September 25, 2021, from https://web.stanford.edu/~bvr/pubs/TS_Tutorial.pdf.
[ { "code": null, "e": 350, "s": 172, "text": "In this series of posts, we experiment with different bandit algorithms to optimise our movie nights — more specifically, how we select movies and restaurants for food delivery!" }, { "code": null, "e": 883, "s": 350, "text": "For newcomers, the name bandit comes from slot machines (known as one-armed bandits). You can think of it as something that can reward you (or not) every time you interact with it (pull its arm). The objective is, given a bunch of bandits that give different rewards, to identify the one that gives the highest ones, as fast as possible. As we start playing and continuously collect data about each bandit, the bandit algorithm helps us choose between exploiting the one that gave us the highest rewards so far and exploring others." }, { "code": null, "e": 894, "s": 883, "text": "medium.com" }, { "code": null, "e": 917, "s": 894, "text": "towardsdatascience.com" }, { "code": null, "e": 1353, "s": 917, "text": "You and your friend have been using bandit algorithms to optimise which restaurants and movies to choose for your weekly movie night. So far, you have tried different bandits algorithms like Epsilon-Greedy, Optimistic Initial Values and Upper Confidence Bounds (UCB). You’ve found the UCB1-Tuned algorithm to work slightly better than the rest, for both Bernoulli and Normal rewards, and have ended up using it for the last few months." }, { "code": null, "e": 1493, "s": 1353, "text": "Even though your movie nights have been going great with the choices made by UCB1-Tuned, you miss the thrill of trying a new algorithm out." }, { "code": null, "e": 1550, "s": 1493, "text": "“Have you heard of Thompson Sampling?” your friend asks." }, { "code": null, "e": 1609, "s": 1550, "text": "Excited you pick up your phone and start reading about it." }, { "code": null, "e": 2130, "s": 1609, "text": "Thompson Sampling, otherwise known as Bayesian Bandits, is the Bayesian approach to the multi-armed bandits problem. The basic idea is to treat the average reward μ from each bandit as a random variable and use the data we have collected so far to calculate its distribution. Then, at each step, we will sample a point from each bandit’s average reward distribution and select the one whose sample had the highest value. We subsequently get the reward from the selected bandit and update its average reward distribution." }, { "code": null, "e": 2280, "s": 2130, "text": "How do we calculate/update distributions I hear you ask? The name Bayesian Bandits might have already given this away, but we will use Bayes Theorem." }, { "code": null, "e": 2492, "s": 2280, "text": "Bayes Theorem P(A|B) = P(B|A) P(A) / P(B)where A, B: events in sample space P(A|B): conditional probability of A given B P(B|A): conditional probability of B given A P(A): probability of A P(B): probability of B" }, { "code": null, "e": 2614, "s": 2492, "text": "The above definition is for discrete variables, for continuous variables it is defined for probability density functions." }, { "code": null, "e": 2771, "s": 2614, "text": "In our case, for each bandit, we want to calculate their P( μ | data ), i.e., how likely different values of μ are, given the data we have collected so far." }, { "code": null, "e": 2880, "s": 2771, "text": "P( μ | data ) = P(data | μ) P(μ) / P(data) ∝ P(data | μ) P(μ) posterior ∝ likelihood x prior" }, { "code": null, "e": 3212, "s": 2880, "text": "Bandits with many data points will have a narrow distribution hence the data point we sample will have a high chance of being close to the real mean. Bandits with few data points, however, will have a wide distribution giving high values a good chance of being selected. This mechanism is what balances exploration vs exploitation." }, { "code": null, "e": 3472, "s": 3212, "text": "Now, calculating P( μ | data ) is tricky unless the likelihood and prior are conjugate priors. This means, that when we combine the likelihood and the prior we get a posterior distribution from the same family as the prior. This is convenient for two reasons:" }, { "code": null, "e": 3590, "s": 3472, "text": "We can avoid nasty calculations for finding out what the posterior is since there is a closed-form expression for it." }, { "code": null, "e": 3786, "s": 3590, "text": "We can use the posterior from step i-1 as the prior for step i. This makes going from P( μ | data up to step i-1) to P( μ | data up to step i) easy and ensures we only work with conjugate priors." }, { "code": null, "e": 3903, "s": 3786, "text": "For the rest of this post, we will assume that a bandit gives a reward of 1 with probability μ and 0 otherwise, i.e." }, { "code": null, "e": 3946, "s": 3903, "text": "ith bandit rewards ~ Bernoulli(prob = μ_i)" }, { "code": null, "e": 4361, "s": 3946, "text": "Now we need to choose a prior distribution for μ. Since μ is the probability of success, it can only take values between 0 to 1. Hence we need a distribution with support [0, 1]. One such distribution is the Beta distribution with parameters a and b. Before we collect any data, all values of μ are equally likely, hence a uniform prior over [0, 1] would make sense. Choosing a = 1 and b = 1 gives us exactly that." }, { "code": null, "e": 4761, "s": 4361, "text": "Next, we need to pick a likelihood and preferably one for which the Beta distribution is a conjugate prior. The Binomial distribution satisfies this and it also makes sense for our use case as it models the probability of getting k successes (sum of a bandit’s rewards) out of N trials (number of times we played the bandit) with a probability of success p (this is the μ we are trying to estimate)." }, { "code": null, "e": 4914, "s": 4761, "text": "If Prior is μ ~ Beta(α, β) Likelihood is k | μ ~ Binomial(N, μ)Then Posterior is μ ~ Beta(α + successes, β + failures)Where N = successes + failures" }, { "code": null, "e": 5027, "s": 4914, "text": "This is a simple update rule, if the reward from a bandit is 1 we increment its a if it is 0 we increment its b." }, { "code": null, "e": 5147, "s": 5027, "text": "We have defined the base classes you will see here in the previous posts, but they are included again for completeness." }, { "code": null, "e": 5341, "s": 5147, "text": "The code below defines the class BernoulliBandit that represents the bandits, the base class Agent to represent agents and the helper class BanditRewardsLog that will keep track of the rewards." }, { "code": null, "e": 5430, "s": 5341, "text": "Now, the only thing left is to subclass the Agent class and implement Thompson Sampling." }, { "code": null, "e": 5615, "s": 5430, "text": "... and we are done! Now, let’s see how it holds up against the algorithms from the previous posts, namely, Epsilon-Greedy, Optimistic Initial Values and Upper Confidence Bounds (UCB)." }, { "code": null, "e": 5683, "s": 5615, "text": "We will use the following code to compare the different algorithms." }, { "code": null, "e": 5716, "s": 5683, "text": "First, let’s define our bandits." }, { "code": null, "e": 5800, "s": 5716, "text": "probs = [0.6, 0.7, 0.8, 0.9]bernoulli_bandits = [BernoulliBandit(p) for p in probs]" }, { "code": null, "e": 5830, "s": 5800, "text": "After this, we can simply run" }, { "code": null, "e": 5919, "s": 5830, "text": "compare_agents( get_agents(), bernoulli_bandits, iterations=500, show_plot=True,)" }, { "code": null, "e": 5949, "s": 5919, "text": "which gives us the following." }, { "code": null, "e": 6177, "s": 5949, "text": "Hmm ... it’s not very clear, but it seems like Epsilon-Greedy and Bayesian Bandits have similar performances. To find the best one, let us repeat the above experiment and count how many times each algorithm got the best result." }, { "code": null, "e": 6269, "s": 6177, "text": "wins = run_comparison(bernoulli_bandits)for g, w in zip(get_agents(), wins): print(g, w)" }, { "code": null, "e": 6721, "s": 6269, "text": "My results were 397 wins for Epsilon-Greedy, 0 for UCB1, 220 for UCB1-Tuned and 383 for Thompson Sampling. It looks like Thompson Sampling and Epsilon-Greedy are the winners for our specific setting. UCB1-Tuned coming in third place is a bit surprising given that in previous experiments it outperformed the Epsilon-Greedy algorithm. This could be due to the fact that Thompson Sampling is stealing some of its wins, but this needs more investigation." }, { "code": null, "e": 6959, "s": 6721, "text": "In this post, we have looked into how the Thompson Sampling algorithm works and implemented it for Bernoulli bandits. We then compared it to other multi-armed bandits algorithms and saw that it performed about the same as Epsilon-Greedy." }, { "code": null, "e": 7081, "s": 6959, "text": "Become a member of Medium and get full access to all stories. Your membership fee directly supports the writers you read." }, { "code": null, "e": 7103, "s": 7081, "text": "From the same author." }, { "code": null, "e": 7126, "s": 7103, "text": "towardsdatascience.com" }, { "code": null, "e": 7137, "s": 7126, "text": "medium.com" } ]
Hot Reload in ElectronJS - GeeksforGeeks
22 Oct, 2021 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. Several powerful frameworks such as Angular, AngularJS 1.x, React, React-Native, etc implement a tool like Webpack. Webpack is a static module bundler for modern JavaScript applications. It is a powerful tool that provides utilities to make the development process faster and better. One of the most useful features provided by webpack is Hot Reloading Capability. Hot Reloading capability lets the developer modify project source code to instantly reflect changes in the output/browser without updating the entire state of the application. The electron does not provide any in-built hot reloading module however, we can still implement hot reloading capability using open-source packages. This tutorial will demonstrate how to implement hot reloading in Electron using electron-reload npm package and electron-reloader npm package. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Project Structure: Example: We will start by building the basic Electron Application by following the given steps. Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --saveThis command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key. Install electron-reload using npm and save it as a dev dependency.npm install electron-reload --save-devInstall electron-reloader using npm and save it as a dev dependency.npm install electron-reloader --save-devBoth of these respective packages can be used to implement Hot Reload in Electron.package.json:{ "name": "electron-hot", "version": "1.0.0", "description": "Hot Reload for Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.2.5" }, "devDependencies": { "electron-reload": "^1.5.0", "electron-reloader": "^1.0.1" } } npm init To generate the package.json file. Install Electron using npm if it is not installed. npm install electron --save This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key. Install electron-reload using npm and save it as a dev dependency. npm install electron-reload --save-dev Install electron-reloader using npm and save it as a dev dependency. npm install electron-reloader --save-dev Both of these respective packages can be used to implement Hot Reload in Electron. package.json: { "name": "electron-hot", "version": "1.0.0", "description": "Hot Reload for Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.2.5" }, "devDependencies": { "electron-reload": "^1.5.0", "electron-reloader": "^1.0.1" } } Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link.main.js:const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here. main.js: const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here. Step 3: Create the index.html file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link.index.html:<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. </body></html> <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. </body></html> Output: To launch the Electron Application, run the Command:npm start npm start Hot Reload in Electron: Hot Reloading should only be implemented in the development environment. Therefore we need to have control over the application environment before implementing this feature. NodeJS provides us with a way by which we can control the application environment via code using Environment Variables. main.js: Add the following snippet in that file. const env = process.env.NODE_ENV || 'development'; The NODE_ENV is an Environment Variable which stands for node environment in NodeJS. When a Node application is launched, it can check this environment variable and based on the value perform additional tasks and code logic. According to convention there should be only two values defined for the NODE_ENV variable i.e. either production or development however we can define as many values as required. We can define additional value such as test to execute automated test cases within the application. If we have not set the environment variable and have not explicitly defined the value within code then it will default to undefined. To set the NODE_ENV in Windows from Windows Powershell use:$env:NODE_ENV="production" $env:NODE_ENV="production" To set the NODE_ENV in Windows from CMD use:set NODE_ENV=production set NODE_ENV=production To set the NODE_ENV in Linux and macOS use:export NODE_ENV=production export NODE_ENV=production Note: The NODE_ENV variable will be reset on System Reboot if set using the above methods. To persist this value in the System, set it in the System Environment Variables via Control Panel in Windows. We can also set NODE_ENV on application startup from package.json by updating the start script. package.json:/.. "start": "set NODE_ENV=development&&electron ." ../ /.. "start": "set NODE_ENV=development&&electron ." ../ In the code, we have set the NODE_ENV to development. We can implement Hot Reload in Electron by following any of the two approaches: Approach 1: Using electron-reload npm package.This package is used to load the contents of all active BrowserWindow Instances within Electron when the source files are changed. The require(‘electron-reload’)(path, options) takes in the following parameters. For more detailed Information, Refer this link.path: String The desired file path to watch to let it refresh the BrowserWindow Instances on source code change.options: Object (Optional) It takes in the following parameterselectron: String To implement a hard reset (Starting a new Electron Process) on reload, we can specify the path pointing to electron executables.hardResetMethod: String If the electron application overrides the default quit or close behaviour such as not closing all BrowserWindow Instances, then electron-reload can leave multiple instances of the app running. In such cases we can specify this property to change the default behavior of electron-reload to exit instead of quit.main.js: Add the following snippet in that file.const path = require('path')const env = process.env.NODE_ENV || 'development'; // If development environmentif (env === 'development') { require('electron-reload')(__dirname, { electron: path.join(__dirname, 'node_modules', '.bin', 'electron'), hardResetMethod: 'exit' });}Output: path: String The desired file path to watch to let it refresh the BrowserWindow Instances on source code change. options: Object (Optional) It takes in the following parameterselectron: String To implement a hard reset (Starting a new Electron Process) on reload, we can specify the path pointing to electron executables.hardResetMethod: String If the electron application overrides the default quit or close behaviour such as not closing all BrowserWindow Instances, then electron-reload can leave multiple instances of the app running. In such cases we can specify this property to change the default behavior of electron-reload to exit instead of quit. electron: String To implement a hard reset (Starting a new Electron Process) on reload, we can specify the path pointing to electron executables. hardResetMethod: String If the electron application overrides the default quit or close behaviour such as not closing all BrowserWindow Instances, then electron-reload can leave multiple instances of the app running. In such cases we can specify this property to change the default behavior of electron-reload to exit instead of quit. main.js: Add the following snippet in that file. const path = require('path')const env = process.env.NODE_ENV || 'development'; // If development environmentif (env === 'development') { require('electron-reload')(__dirname, { electron: path.join(__dirname, 'node_modules', '.bin', 'electron'), hardResetMethod: 'exit' });} Output: Approach 2: Using electron-reloader npm package. This package requires Electron 5+.According to the default behaviour of electron-reloader package, when source code of the files used in the Main Process are changed then the app is restarted, and when the source code of files used in the BrowserWindow Instance or Renderer Process are changed then the page is reloaded. The require(‘electron-reloader’)(module, options) takes in the following parameters. This package also watches the dist folder which is created when we build the application. For more detailed Information, Refer this link.module: Object The global module Object. This object is passed so that the package can read the module graph and find out which files belong to the Main Process.options: Object (Optional) It takes in the following parametersdebug: Boolean Prints the watched paths and file information such as file name of the files being watched on source code change. Default value is false.ignore: String[] It is a String Array of Regex Expressions. The Regex Expressions represent the pattern of the files/directories to be ignored by the package. By default, files/directories starting with a ., .map files, and node_modules dependencies are ignored. Additional patterns specified will be added to these default patterns.watchRenderer: Boolean Watch files used in the Renderer Process and reload the respective window on source code change. Default value is true.Note: The try/catch is needed so that it does not throw the following Error in production Environment.Cannot find module 'electron-reloader'main.js: Add the following snippet in that file.const env = process.env.NODE_ENV || 'development'; // If development environmentif (env === 'development') { try { require('electron-reloader')(module, { debug: true, watchRenderer: true }); } catch (_) { console.log('Error'); } }Output:Console Output: According to the default behaviour of electron-reloader package, when source code of the files used in the Main Process are changed then the app is restarted, and when the source code of files used in the BrowserWindow Instance or Renderer Process are changed then the page is reloaded. The require(‘electron-reloader’)(module, options) takes in the following parameters. This package also watches the dist folder which is created when we build the application. For more detailed Information, Refer this link. module: Object The global module Object. This object is passed so that the package can read the module graph and find out which files belong to the Main Process. options: Object (Optional) It takes in the following parametersdebug: Boolean Prints the watched paths and file information such as file name of the files being watched on source code change. Default value is false.ignore: String[] It is a String Array of Regex Expressions. The Regex Expressions represent the pattern of the files/directories to be ignored by the package. By default, files/directories starting with a ., .map files, and node_modules dependencies are ignored. Additional patterns specified will be added to these default patterns.watchRenderer: Boolean Watch files used in the Renderer Process and reload the respective window on source code change. Default value is true. debug: Boolean Prints the watched paths and file information such as file name of the files being watched on source code change. Default value is false. ignore: String[] It is a String Array of Regex Expressions. The Regex Expressions represent the pattern of the files/directories to be ignored by the package. By default, files/directories starting with a ., .map files, and node_modules dependencies are ignored. Additional patterns specified will be added to these default patterns. watchRenderer: Boolean Watch files used in the Renderer Process and reload the respective window on source code change. Default value is true. Note: The try/catch is needed so that it does not throw the following Error in production Environment. Cannot find module 'electron-reloader' main.js: Add the following snippet in that file. const env = process.env.NODE_ENV || 'development'; // If development environmentif (env === 'development') { try { require('electron-reloader')(module, { debug: true, watchRenderer: true }); } catch (_) { console.log('Error'); } } Output: Console Output: arorakashish0911 ElectronJS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24242, "s": 24214, "text": "\n22 Oct, 2021" }, { "code": null, "e": 24542, "s": 24242, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 25375, "s": 24542, "text": "Several powerful frameworks such as Angular, AngularJS 1.x, React, React-Native, etc implement a tool like Webpack. Webpack is a static module bundler for modern JavaScript applications. It is a powerful tool that provides utilities to make the development process faster and better. One of the most useful features provided by webpack is Hot Reloading Capability. Hot Reloading capability lets the developer modify project source code to instantly reflect changes in the output/browser without updating the entire state of the application. The electron does not provide any in-built hot reloading module however, we can still implement hot reloading capability using open-source packages. This tutorial will demonstrate how to implement hot reloading in Electron using electron-reload npm package and electron-reloader npm package." }, { "code": null, "e": 25545, "s": 25375, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 25564, "s": 25545, "text": "Project Structure:" }, { "code": null, "e": 25660, "s": 25564, "text": "Example: We will start by building the basic Electron Application by following the given steps." }, { "code": null, "e": 26812, "s": 25660, "text": "Step 1: Navigate to an Empty Directory to setup the project, and run the following command,npm initTo generate the package.json file. Install Electron using npm if it is not installed.npm install electron --saveThis command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key. Install electron-reload using npm and save it as a dev dependency.npm install electron-reload --save-devInstall electron-reloader using npm and save it as a dev dependency.npm install electron-reloader --save-devBoth of these respective packages can be used to implement Hot Reload in Electron.package.json:{\n \"name\": \"electron-hot\",\n \"version\": \"1.0.0\",\n \"description\": \"Hot Reload for Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.2.5\"\n },\n \"devDependencies\": {\n \"electron-reload\": \"^1.5.0\",\n \"electron-reloader\": \"^1.0.1\"\n }\n}\n" }, { "code": null, "e": 26821, "s": 26812, "text": "npm init" }, { "code": null, "e": 26907, "s": 26821, "text": "To generate the package.json file. Install Electron using npm if it is not installed." }, { "code": null, "e": 26935, "s": 26907, "text": "npm install electron --save" }, { "code": null, "e": 27242, "s": 26935, "text": "This command will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key. Install electron-reload using npm and save it as a dev dependency." }, { "code": null, "e": 27281, "s": 27242, "text": "npm install electron-reload --save-dev" }, { "code": null, "e": 27350, "s": 27281, "text": "Install electron-reloader using npm and save it as a dev dependency." }, { "code": null, "e": 27391, "s": 27350, "text": "npm install electron-reloader --save-dev" }, { "code": null, "e": 27474, "s": 27391, "text": "Both of these respective packages can be used to implement Hot Reload in Electron." }, { "code": null, "e": 27488, "s": 27474, "text": "package.json:" }, { "code": null, "e": 27882, "s": 27488, "text": "{\n \"name\": \"electron-hot\",\n \"version\": \"1.0.0\",\n \"description\": \"Hot Reload for Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.2.5\"\n },\n \"devDependencies\": {\n \"electron-reload\": \"^1.5.0\",\n \"electron-reloader\": \"^1.0.1\"\n }\n}\n" }, { "code": null, "e": 29448, "s": 27882, "text": "Step 2: Create a main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link.main.js:const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here." }, { "code": null, "e": 29457, "s": 29448, "text": "main.js:" }, { "code": "const { app, BrowserWindow } = require('electron') function createWindow() { // Create the browser window. const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html of the app. win.loadFile('index.html') // Open the DevTools. win.webContents.openDevTools()} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.// This method is equivalent to 'app.on('ready', function())'app.whenReady().then(createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their // menu bar to stay active until the user quits // explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the // app when the dock icon is clicked and there are no // other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() }}) // In this file, you can include the rest of your // app's specific main process code. You can also // put them in separate files and require them here.", "e": 30792, "s": 29457, "text": null }, { "code": null, "e": 31567, "s": 30792, "text": "Step 3: Create the index.html file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link.index.html:<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. </body></html>" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title>Hello World!</title> <!-- https://electronjs.org/docs/tutorial /security#csp-meta-tag --> <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" /> </head> <body> <h1>Hello World!</h1> We are using node <script> document.write(process.versions.node) </script>, Chrome <script> document.write(process.versions.chrome) </script>, and Electron <script> document.write(process.versions.electron) </script>. </body></html>", "e": 32177, "s": 31567, "text": null }, { "code": null, "e": 32247, "s": 32177, "text": "Output: To launch the Electron Application, run the Command:npm start" }, { "code": null, "e": 32257, "s": 32247, "text": "npm start" }, { "code": null, "e": 32575, "s": 32257, "text": "Hot Reload in Electron: Hot Reloading should only be implemented in the development environment. Therefore we need to have control over the application environment before implementing this feature. NodeJS provides us with a way by which we can control the application environment via code using Environment Variables." }, { "code": null, "e": 32624, "s": 32575, "text": "main.js: Add the following snippet in that file." }, { "code": null, "e": 32675, "s": 32624, "text": "const env = process.env.NODE_ENV || 'development';" }, { "code": null, "e": 33311, "s": 32675, "text": "The NODE_ENV is an Environment Variable which stands for node environment in NodeJS. When a Node application is launched, it can check this environment variable and based on the value perform additional tasks and code logic. According to convention there should be only two values defined for the NODE_ENV variable i.e. either production or development however we can define as many values as required. We can define additional value such as test to execute automated test cases within the application. If we have not set the environment variable and have not explicitly defined the value within code then it will default to undefined." }, { "code": null, "e": 33397, "s": 33311, "text": "To set the NODE_ENV in Windows from Windows Powershell use:$env:NODE_ENV=\"production\"" }, { "code": null, "e": 33424, "s": 33397, "text": "$env:NODE_ENV=\"production\"" }, { "code": null, "e": 33492, "s": 33424, "text": "To set the NODE_ENV in Windows from CMD use:set NODE_ENV=production" }, { "code": null, "e": 33516, "s": 33492, "text": "set NODE_ENV=production" }, { "code": null, "e": 33586, "s": 33516, "text": "To set the NODE_ENV in Linux and macOS use:export NODE_ENV=production" }, { "code": null, "e": 33613, "s": 33586, "text": "export NODE_ENV=production" }, { "code": null, "e": 33910, "s": 33613, "text": "Note: The NODE_ENV variable will be reset on System Reboot if set using the above methods. To persist this value in the System, set it in the System Environment Variables via Control Panel in Windows. We can also set NODE_ENV on application startup from package.json by updating the start script." }, { "code": null, "e": 33979, "s": 33910, "text": "package.json:/..\n\"start\": \"set NODE_ENV=development&&electron .\"\n../" }, { "code": null, "e": 34035, "s": 33979, "text": "/..\n\"start\": \"set NODE_ENV=development&&electron .\"\n../" }, { "code": null, "e": 34169, "s": 34035, "text": "In the code, we have set the NODE_ENV to development. We can implement Hot Reload in Electron by following any of the two approaches:" }, { "code": null, "e": 35478, "s": 34169, "text": "Approach 1: Using electron-reload npm package.This package is used to load the contents of all active BrowserWindow Instances within Electron when the source files are changed. The require(‘electron-reload’)(path, options) takes in the following parameters. For more detailed Information, Refer this link.path: String The desired file path to watch to let it refresh the BrowserWindow Instances on source code change.options: Object (Optional) It takes in the following parameterselectron: String To implement a hard reset (Starting a new Electron Process) on reload, we can specify the path pointing to electron executables.hardResetMethod: String If the electron application overrides the default quit or close behaviour such as not closing all BrowserWindow Instances, then electron-reload can leave multiple instances of the app running. In such cases we can specify this property to change the default behavior of electron-reload to exit instead of quit.main.js: Add the following snippet in that file.const path = require('path')const env = process.env.NODE_ENV || 'development'; // If development environmentif (env === 'development') { require('electron-reload')(__dirname, { electron: path.join(__dirname, 'node_modules', '.bin', 'electron'), hardResetMethod: 'exit' });}Output:" }, { "code": null, "e": 35591, "s": 35478, "text": "path: String The desired file path to watch to let it refresh the BrowserWindow Instances on source code change." }, { "code": null, "e": 36134, "s": 35591, "text": "options: Object (Optional) It takes in the following parameterselectron: String To implement a hard reset (Starting a new Electron Process) on reload, we can specify the path pointing to electron executables.hardResetMethod: String If the electron application overrides the default quit or close behaviour such as not closing all BrowserWindow Instances, then electron-reload can leave multiple instances of the app running. In such cases we can specify this property to change the default behavior of electron-reload to exit instead of quit." }, { "code": null, "e": 36280, "s": 36134, "text": "electron: String To implement a hard reset (Starting a new Electron Process) on reload, we can specify the path pointing to electron executables." }, { "code": null, "e": 36615, "s": 36280, "text": "hardResetMethod: String If the electron application overrides the default quit or close behaviour such as not closing all BrowserWindow Instances, then electron-reload can leave multiple instances of the app running. In such cases we can specify this property to change the default behavior of electron-reload to exit instead of quit." }, { "code": null, "e": 36664, "s": 36615, "text": "main.js: Add the following snippet in that file." }, { "code": "const path = require('path')const env = process.env.NODE_ENV || 'development'; // If development environmentif (env === 'development') { require('electron-reload')(__dirname, { electron: path.join(__dirname, 'node_modules', '.bin', 'electron'), hardResetMethod: 'exit' });}", "e": 36959, "s": 36664, "text": null }, { "code": null, "e": 36967, "s": 36959, "text": "Output:" }, { "code": null, "e": 38897, "s": 36967, "text": "Approach 2: Using electron-reloader npm package. This package requires Electron 5+.According to the default behaviour of electron-reloader package, when source code of the files used in the Main Process are changed then the app is restarted, and when the source code of files used in the BrowserWindow Instance or Renderer Process are changed then the page is reloaded. The require(‘electron-reloader’)(module, options) takes in the following parameters. This package also watches the dist folder which is created when we build the application. For more detailed Information, Refer this link.module: Object The global module Object. This object is passed so that the package can read the module graph and find out which files belong to the Main Process.options: Object (Optional) It takes in the following parametersdebug: Boolean Prints the watched paths and file information such as file name of the files being watched on source code change. Default value is false.ignore: String[] It is a String Array of Regex Expressions. The Regex Expressions represent the pattern of the files/directories to be ignored by the package. By default, files/directories starting with a ., .map files, and node_modules dependencies are ignored. Additional patterns specified will be added to these default patterns.watchRenderer: Boolean Watch files used in the Renderer Process and reload the respective window on source code change. Default value is true.Note: The try/catch is needed so that it does not throw the following Error in production Environment.Cannot find module 'electron-reloader'main.js: Add the following snippet in that file.const env = process.env.NODE_ENV || 'development'; // If development environmentif (env === 'development') { try { require('electron-reloader')(module, { debug: true, watchRenderer: true }); } catch (_) { console.log('Error'); } }Output:Console Output:" }, { "code": null, "e": 39407, "s": 38897, "text": "According to the default behaviour of electron-reloader package, when source code of the files used in the Main Process are changed then the app is restarted, and when the source code of files used in the BrowserWindow Instance or Renderer Process are changed then the page is reloaded. The require(‘electron-reloader’)(module, options) takes in the following parameters. This package also watches the dist folder which is created when we build the application. For more detailed Information, Refer this link." }, { "code": null, "e": 39569, "s": 39407, "text": "module: Object The global module Object. This object is passed so that the package can read the module graph and find out which files belong to the Main Process." }, { "code": null, "e": 40260, "s": 39569, "text": "options: Object (Optional) It takes in the following parametersdebug: Boolean Prints the watched paths and file information such as file name of the files being watched on source code change. Default value is false.ignore: String[] It is a String Array of Regex Expressions. The Regex Expressions represent the pattern of the files/directories to be ignored by the package. By default, files/directories starting with a ., .map files, and node_modules dependencies are ignored. Additional patterns specified will be added to these default patterns.watchRenderer: Boolean Watch files used in the Renderer Process and reload the respective window on source code change. Default value is true." }, { "code": null, "e": 40413, "s": 40260, "text": "debug: Boolean Prints the watched paths and file information such as file name of the files being watched on source code change. Default value is false." }, { "code": null, "e": 40747, "s": 40413, "text": "ignore: String[] It is a String Array of Regex Expressions. The Regex Expressions represent the pattern of the files/directories to be ignored by the package. By default, files/directories starting with a ., .map files, and node_modules dependencies are ignored. Additional patterns specified will be added to these default patterns." }, { "code": null, "e": 40890, "s": 40747, "text": "watchRenderer: Boolean Watch files used in the Renderer Process and reload the respective window on source code change. Default value is true." }, { "code": null, "e": 40993, "s": 40890, "text": "Note: The try/catch is needed so that it does not throw the following Error in production Environment." }, { "code": null, "e": 41032, "s": 40993, "text": "Cannot find module 'electron-reloader'" }, { "code": null, "e": 41081, "s": 41032, "text": "main.js: Add the following snippet in that file." }, { "code": "const env = process.env.NODE_ENV || 'development'; // If development environmentif (env === 'development') { try { require('electron-reloader')(module, { debug: true, watchRenderer: true }); } catch (_) { console.log('Error'); } }", "e": 41358, "s": 41081, "text": null }, { "code": null, "e": 41366, "s": 41358, "text": "Output:" }, { "code": null, "e": 41382, "s": 41366, "text": "Console Output:" }, { "code": null, "e": 41399, "s": 41382, "text": "arorakashish0911" }, { "code": null, "e": 41410, "s": 41399, "text": "ElectronJS" }, { "code": null, "e": 41421, "s": 41410, "text": "JavaScript" }, { "code": null, "e": 41438, "s": 41421, "text": "Web Technologies" }, { "code": null, "e": 41536, "s": 41438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41545, "s": 41536, "text": "Comments" }, { "code": null, "e": 41558, "s": 41545, "text": "Old Comments" }, { "code": null, "e": 41619, "s": 41558, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 41691, "s": 41619, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 41736, "s": 41691, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 41788, "s": 41736, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 41829, "s": 41788, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 41871, "s": 41829, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 41904, "s": 41871, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 41966, "s": 41904, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 42009, "s": 41966, "text": "How to fetch data from an API in ReactJS ?" } ]
Count of subarrays forming an Arithmetic Progression (AP) - GeeksforGeeks
18 Apr, 2022 Given an array arr[] of size N, the task is to find the count of subarrays of at least length 2, such that the difference between the consecutive elements of those subarrays remains the same throughout i.e. the elements of the subarray forms an AP. Examples: Input: arr[] = {8, 7, 4, 1, 0} Output: 5 Explanation: All subarrays of size greater than 1 which form an AP are [8, 7], [7, 4], [4, 1], [1, 0], [7, 4, 1] Input: arr[] = {4, 2} Output: 1 Approach: The idea is to generate all possible subarrays from the given array and for each subarray, check if the difference between adjacent elements is the same or not for the generated subarrays. Below are the steps: Iterate over each subarray of length at least 2 using two loops.Let i be the start index of the subarray and j be the end index of the subarray.If the difference between every adjacent pair of elements of the array from index i to j is the same then increment the total count.Otherwise, repeat the above process with the next subarray. Iterate over each subarray of length at least 2 using two loops. Let i be the start index of the subarray and j be the end index of the subarray. If the difference between every adjacent pair of elements of the array from index i to j is the same then increment the total count. Otherwise, repeat the above process with the next subarray. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of// the above approach#include <iostream>using namespace std; // Function to find the// total count of subarraysint calcSubarray(int A[], int N){ int count = 0; // Iterate over each subarray for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { bool flag = true; // Difference between first // two terms of subarray int comm_diff = A[i + 1] - A[i]; // Iterate over the subarray // from i to j for (int k = i; k < j; k++) { // Check if the difference // of all adjacent elements // is same if (A[k + 1] - A[k] == comm_diff) { continue; } else { flag = false; break; } } if (flag) { count++; } } } return count;} // Driver Codeint main(){ // Given array int A[5] = { 8, 7, 4, 1, 0 }; int N = sizeof(A) / sizeof(int); // Function Call cout << calcSubarray(A, N);} // Java implementation of// the above approachimport java.util.*;class GFG{ // Function to find the// total count of subarraysstatic int calcSubarray(int A[], int N){ int count = 0; // Iterate over each subarray for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { boolean flag = true; // Difference between first // two terms of subarray int comm_diff = A[i + 1] - A[i]; // Iterate over the subarray // from i to j for (int k = i; k < j; k++) { // Check if the difference // of all adjacent elements // is same if (A[k + 1] - A[k] == comm_diff) { continue; } else { flag = false; break; } } if (flag) { count++; } } } return count;} // Driver Codepublic static void main(String[] args){ // Given array int []A = {8, 7, 4, 1, 0}; int N = A.length; // Function Call System.out.print(calcSubarray(A, N));}} // This code is contributed by Rajput-Ji # Python3 implementation of# the above approach # Function to find the# total count of subarraysdef calcSubarray(A, N): count = 0 # Iterate over each subarray for i in range(N): for j in range(i + 1, N): flag = True # Difference between first # two terms of subarray comm_diff = A[i + 1] - A[i] # Iterate over the subarray # from i to j for k in range(i, j): # Check if the difference # of all adjacent elements # is same if (A[k + 1] - A[k] == comm_diff): continue else: flag = False break if (flag): count += 1 return count # Driver Codeif __name__ == '__main__': # Given array A = [ 8, 7, 4, 1, 0 ] N = len(A) # Function call print(calcSubarray(A, N)) # This code is contributed by mohit kumar 29 // C# implementation of// the above approachusing System;class GFG{ // Function to find the// total count of subarraysstatic int calcSubarray(int []A, int N){ int count = 0; // Iterate over each subarray for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { bool flag = true; // Difference between first // two terms of subarray int comm_diff = A[i + 1] - A[i]; // Iterate over the subarray // from i to j for (int k = i; k < j; k++) { // Check if the difference // of all adjacent elements // is same if (A[k + 1] - A[k] == comm_diff) { continue; } else { flag = false; break; } } if (flag) { count++; } } } return count;} // Driver Codepublic static void Main(String[] args){ // Given array int []A = {8, 7, 4, 1, 0}; int N = A.Length; // Function Call Console.Write(calcSubarray(A, N));}} // This code is contributed by 29AjayKumar <script> // Javascript implementation of// the above approach // Function to find the// total count of subarraysfunction calcSubarray(A, N){ let count = 0; // Iterate over each subarray for (let i = 0; i < N; i++) { for (let j = i + 1; j < N; j++) { let flag = true; // Difference between first // two terms of subarray let comm_diff = A[i + 1] - A[i]; // Iterate over the subarray // from i to j for (let k = i; k < j; k++) { // Check if the difference // of all adjacent elements // is same if (A[k + 1] - A[k] == comm_diff) { continue; } else { flag = false; break; } } if (flag) { count++; } } } return count;} // Driver Code // Given array let A = [ 8, 7, 4, 1, 0 ]; let N = A.length; // Function Call document.write(calcSubarray(A, N)); // This code is contributed by Mayank Tyagi </script> 5 Time Complexity: O(N3) Auxiliary Space: O(1) Method 2: (Iterate over array only once) Approach: The idea is to iterate on the array only once while comparing the difference between adjacent elements and counting the number of elements in each largest subarray for that difference which is stored in the variable t. For example, consider the array – {1, 2, 3, 7}. Here the largest subarray with difference = 1 is {1, 2, 3}. So here t = 3 and possible subarrays of length at least 2 are {1, 2, 3}, {1, 2} & {2, 3}. Similarly, the largest subarray with difference = 4 is {3, 7}. So here t = 2 and possible subarrays of length at least 2 are {3, 7}. Therefore, total arithmetic subarrays with length at least 2 are 3 + 1 = 4. To derive possible subarrays for a particular difference we will use the math formula as follows: (t * (t + 1) ) / 2 – t. Let us understand how we got this formula. Suppose this is a subarray {1, 2, 3, 4, 5} of some other larger array. Total subarrays with arithmetic difference and length at least 2 using this subarray will be as follows, {1, 2, 3, 4, 5} = 1 {1, 2, 3, 4}, {2, 3, 4, 5} = 2 {1, 2, 3}, {2, 3, 4}, {3, 4, 5} = 3 {1, 2}, {2, 3}, {3, 4}, {4, 5} = 4 And total number of subarrays = 1 + 2 + 3 + 4 This is nothing but sum of first (t – 1) consecutive numbers = (t * (t + 1)) / 2 – t. Similarly, if we had to find arithmetic subarrays with length at least 3, then we will consider the below, {1, 2, 3, 4, 5} = 1 {1, 2, 3, 4}, {2, 3, 4, 5} = 2 {1, 2, 3}, {2, 3, 4}, {3, 4, 5} = 3 And total number of subarrays in this case = 1 + 2 + 3 for t = 5 The math formula will exclude 4 i.e. (t – 1) and 5 i.e. t from its sum, so formula will be (t * (t + 1)) / 2 – (t – 1) – (t) = (t * (t + 1)) / 2 – (2 * t) + 1 To count the maximum number of elements in a subarray with a particular difference, we use the variable num. d variable tracks the difference. d is initialized to the difference between 2nd and 1st element and num will be 1 since for subarrays with 2 elements, the total possible subarrays for that difference will be 1. Then i is incremented to 1 and we start iterating on the array. If the difference between adjacent elements matches the difference in variable d, we simply increment the num.If the difference between adjacent elements does not match the variable d, then we got the subarray with the maximum number of elements for that difference. The value of t i.e. maximum number of elements for that difference will be (num + 1). So we use the math formula to add the number of subarrays for length t.We reset the num to 1 for a new subarray and d to the new difference for next comparison and continue to Step 1. If the difference between adjacent elements matches the difference in variable d, we simply increment the num. If the difference between adjacent elements does not match the variable d, then we got the subarray with the maximum number of elements for that difference. The value of t i.e. maximum number of elements for that difference will be (num + 1). So we use the math formula to add the number of subarrays for length t. We reset the num to 1 for a new subarray and d to the new difference for next comparison and continue to Step 1. Below is the implementation of the above approach: C++ Python3 Javascript // C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // Function to find the// total count of subarraysint calcSubarray(int A[], int N){ // If size of array is smaller than 2, // then count will be zero if (N < 2) { return 0; } int i = 0; int num, d, count = 0, t; // Difference between first two adjacent array elements d = A[i + 1] - A[i]; // num stores the total number of elements in a subarray // for a particular difference num = 1; // After calculating difference, move to next element // and iterate over the array i = 1; while (i < N - 1) { // If Difference between adjacent elements is same // as d, increment num if (A[i + 1] - A[i] == d) { num++; } else { // Update the count if number of elements // in subarray is greater than 1 if (num >= 1) { t = num + 1; count = count + (t * (t + 1)) / 2 - t; } // Reset num num = 1; // Update with new difference d = A[i + 1] - A[i]; } i++; } if (num >= 1) { t = num + 1; count = count + (t * (t + 1)) / 2 - t; } return count;} // Driver Codeint main(){ // Given Array int A[5] = { 8, 7, 4, 1, 0 }; int N = sizeof(A) / sizeof(int); // Function Call cout << calcSubarray(A, N); return 0; // This code is contributed by Snigdha Patil} # Python implementation of# the above approach # Function to find the# total count of subarraysdef calcSubarray(A,N): # If size of array is smaller than 2, # then count will be zero if (N < 2): return 0 i = 0 num = 0 count = 0 t = 0 # Difference between first two adjacent array elements d = A[i + 1] - A[i] # num stores the total number of elements in a subarray # for a particular difference num = 1 # After calculating difference, move to next element # and iterate over the array i = 1 while (i < N - 1): # If Difference between adjacent elements is same # as d, increment num if (A[i + 1] - A[i] == d): num += 1 else: # Update the count if number of elements # in subarray is greater than 1 if (num >= 1): t = num + 1 count = count + (t * (t + 1)) // 2 - t # Reset num num = 1 # Update with new difference d = A[i + 1] - A[i] i += 1 if (num >= 1): t = num + 1 count = count + (t * (t + 1)) // 2 - t return count # Driver Code # Given ArrayA = [ 8, 7, 4, 1, 0 ]N = len(A) # Function Callprint(calcSubarray(A, N)) # This code is contributed by Shinjanpatra <script> // JavaScript implementation of// the above approach // Function to find the// total count of subarraysfunction calcSubarray(A, N){ // If size of array is smaller than 2, // then count will be zero if (N < 2) { return 0; } let i = 0; let num, d, count = 0, t; // Difference between first two adjacent array elements d = A[i + 1] - A[i]; // num stores the total number of elements in a subarray // for a particular difference num = 1; // After calculating difference, move to next element // and iterate over the array i = 1; while (i < N - 1) { // If Difference between adjacent elements is same // as d, increment num if (A[i + 1] - A[i] == d) { num++; } else { // Update the count if number of elements // in subarray is greater than 1 if (num >= 1) { t = num + 1; count = count + Math.floor((t * (t + 1)) / 2) - t; } // Reset num num = 1; // Update with new difference d = A[i + 1] - A[i]; } i++; } if (num >= 1) { t = num + 1; count = count + Math.floor((t * (t + 1)) / 2) - t; } return count;} // Driver Code // Given Arraylet A = [ 8, 7, 4, 1, 0 ];let N = A.length; // Function Calldocument.write(calcSubarray(A, N)); // This code is contributed by Shinjanpatra </script> 5 Time Complexity: O(N) Auxiliary Space: O(1) mohit kumar 29 Rajput-Ji 29AjayKumar mayanktyagi1709 sniggy shinjanpatra arithmetic progression subarray Arrays Mathematical Searching Arrays Searching Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find sum of elements in a given array Trapping Rain Water Reversal algorithm for array rotation Move all negative numbers to beginning and positive to end with constant extra space Window Sliding Technique 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) Program to find sum of elements in a given array
[ { "code": null, "e": 24405, "s": 24377, "text": "\n18 Apr, 2022" }, { "code": null, "e": 24664, "s": 24405, "text": "Given an array arr[] of size N, the task is to find the count of subarrays of at least length 2, such that the difference between the consecutive elements of those subarrays remains the same throughout i.e. the elements of the subarray forms an AP. Examples:" }, { "code": null, "e": 24818, "s": 24664, "text": "Input: arr[] = {8, 7, 4, 1, 0} Output: 5 Explanation: All subarrays of size greater than 1 which form an AP are [8, 7], [7, 4], [4, 1], [1, 0], [7, 4, 1]" }, { "code": null, "e": 24850, "s": 24818, "text": "Input: arr[] = {4, 2} Output: 1" }, { "code": null, "e": 25070, "s": 24850, "text": "Approach: The idea is to generate all possible subarrays from the given array and for each subarray, check if the difference between adjacent elements is the same or not for the generated subarrays. Below are the steps:" }, { "code": null, "e": 25406, "s": 25070, "text": "Iterate over each subarray of length at least 2 using two loops.Let i be the start index of the subarray and j be the end index of the subarray.If the difference between every adjacent pair of elements of the array from index i to j is the same then increment the total count.Otherwise, repeat the above process with the next subarray." }, { "code": null, "e": 25471, "s": 25406, "text": "Iterate over each subarray of length at least 2 using two loops." }, { "code": null, "e": 25552, "s": 25471, "text": "Let i be the start index of the subarray and j be the end index of the subarray." }, { "code": null, "e": 25685, "s": 25552, "text": "If the difference between every adjacent pair of elements of the array from index i to j is the same then increment the total count." }, { "code": null, "e": 25745, "s": 25685, "text": "Otherwise, repeat the above process with the next subarray." }, { "code": null, "e": 25796, "s": 25745, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25800, "s": 25796, "text": "C++" }, { "code": null, "e": 25805, "s": 25800, "text": "Java" }, { "code": null, "e": 25813, "s": 25805, "text": "Python3" }, { "code": null, "e": 25816, "s": 25813, "text": "C#" }, { "code": null, "e": 25827, "s": 25816, "text": "Javascript" }, { "code": "// C++ implementation of// the above approach#include <iostream>using namespace std; // Function to find the// total count of subarraysint calcSubarray(int A[], int N){ int count = 0; // Iterate over each subarray for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { bool flag = true; // Difference between first // two terms of subarray int comm_diff = A[i + 1] - A[i]; // Iterate over the subarray // from i to j for (int k = i; k < j; k++) { // Check if the difference // of all adjacent elements // is same if (A[k + 1] - A[k] == comm_diff) { continue; } else { flag = false; break; } } if (flag) { count++; } } } return count;} // Driver Codeint main(){ // Given array int A[5] = { 8, 7, 4, 1, 0 }; int N = sizeof(A) / sizeof(int); // Function Call cout << calcSubarray(A, N);}", "e": 26961, "s": 25827, "text": null }, { "code": "// Java implementation of// the above approachimport java.util.*;class GFG{ // Function to find the// total count of subarraysstatic int calcSubarray(int A[], int N){ int count = 0; // Iterate over each subarray for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { boolean flag = true; // Difference between first // two terms of subarray int comm_diff = A[i + 1] - A[i]; // Iterate over the subarray // from i to j for (int k = i; k < j; k++) { // Check if the difference // of all adjacent elements // is same if (A[k + 1] - A[k] == comm_diff) { continue; } else { flag = false; break; } } if (flag) { count++; } } } return count;} // Driver Codepublic static void main(String[] args){ // Given array int []A = {8, 7, 4, 1, 0}; int N = A.length; // Function Call System.out.print(calcSubarray(A, N));}} // This code is contributed by Rajput-Ji", "e": 28024, "s": 26961, "text": null }, { "code": "# Python3 implementation of# the above approach # Function to find the# total count of subarraysdef calcSubarray(A, N): count = 0 # Iterate over each subarray for i in range(N): for j in range(i + 1, N): flag = True # Difference between first # two terms of subarray comm_diff = A[i + 1] - A[i] # Iterate over the subarray # from i to j for k in range(i, j): # Check if the difference # of all adjacent elements # is same if (A[k + 1] - A[k] == comm_diff): continue else: flag = False break if (flag): count += 1 return count # Driver Codeif __name__ == '__main__': # Given array A = [ 8, 7, 4, 1, 0 ] N = len(A) # Function call print(calcSubarray(A, N)) # This code is contributed by mohit kumar 29", "e": 29038, "s": 28024, "text": null }, { "code": "// C# implementation of// the above approachusing System;class GFG{ // Function to find the// total count of subarraysstatic int calcSubarray(int []A, int N){ int count = 0; // Iterate over each subarray for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { bool flag = true; // Difference between first // two terms of subarray int comm_diff = A[i + 1] - A[i]; // Iterate over the subarray // from i to j for (int k = i; k < j; k++) { // Check if the difference // of all adjacent elements // is same if (A[k + 1] - A[k] == comm_diff) { continue; } else { flag = false; break; } } if (flag) { count++; } } } return count;} // Driver Codepublic static void Main(String[] args){ // Given array int []A = {8, 7, 4, 1, 0}; int N = A.Length; // Function Call Console.Write(calcSubarray(A, N));}} // This code is contributed by 29AjayKumar", "e": 30089, "s": 29038, "text": null }, { "code": "<script> // Javascript implementation of// the above approach // Function to find the// total count of subarraysfunction calcSubarray(A, N){ let count = 0; // Iterate over each subarray for (let i = 0; i < N; i++) { for (let j = i + 1; j < N; j++) { let flag = true; // Difference between first // two terms of subarray let comm_diff = A[i + 1] - A[i]; // Iterate over the subarray // from i to j for (let k = i; k < j; k++) { // Check if the difference // of all adjacent elements // is same if (A[k + 1] - A[k] == comm_diff) { continue; } else { flag = false; break; } } if (flag) { count++; } } } return count;} // Driver Code // Given array let A = [ 8, 7, 4, 1, 0 ]; let N = A.length; // Function Call document.write(calcSubarray(A, N)); // This code is contributed by Mayank Tyagi </script>", "e": 31227, "s": 30089, "text": null }, { "code": null, "e": 31229, "s": 31227, "text": "5" }, { "code": null, "e": 31275, "s": 31229, "text": "Time Complexity: O(N3) Auxiliary Space: O(1) " }, { "code": null, "e": 31316, "s": 31275, "text": "Method 2: (Iterate over array only once)" }, { "code": null, "e": 31326, "s": 31316, "text": "Approach:" }, { "code": null, "e": 31545, "s": 31326, "text": "The idea is to iterate on the array only once while comparing the difference between adjacent elements and counting the number of elements in each largest subarray for that difference which is stored in the variable t." }, { "code": null, "e": 31745, "s": 31545, "text": "For example, consider the array – {1, 2, 3, 7}. Here the largest subarray with difference = 1 is {1, 2, 3}. So here t = 3 and possible subarrays of length at least 2 are {1, 2, 3}, {1, 2} & {2, 3}. " }, { "code": null, "e": 31878, "s": 31745, "text": "Similarly, the largest subarray with difference = 4 is {3, 7}. So here t = 2 and possible subarrays of length at least 2 are {3, 7}." }, { "code": null, "e": 31954, "s": 31878, "text": "Therefore, total arithmetic subarrays with length at least 2 are 3 + 1 = 4." }, { "code": null, "e": 32052, "s": 31954, "text": "To derive possible subarrays for a particular difference we will use the math formula as follows:" }, { "code": null, "e": 32078, "s": 32052, "text": "(t * (t + 1) ) / 2 – t. " }, { "code": null, "e": 32123, "s": 32078, "text": "Let us understand how we got this formula. " }, { "code": null, "e": 32299, "s": 32123, "text": "Suppose this is a subarray {1, 2, 3, 4, 5} of some other larger array. Total subarrays with arithmetic difference and length at least 2 using this subarray will be as follows," }, { "code": null, "e": 32319, "s": 32299, "text": "{1, 2, 3, 4, 5} = 1" }, { "code": null, "e": 32350, "s": 32319, "text": "{1, 2, 3, 4}, {2, 3, 4, 5} = 2" }, { "code": null, "e": 32386, "s": 32350, "text": "{1, 2, 3}, {2, 3, 4}, {3, 4, 5} = 3" }, { "code": null, "e": 32421, "s": 32386, "text": "{1, 2}, {2, 3}, {3, 4}, {4, 5} = 4" }, { "code": null, "e": 32469, "s": 32421, "text": "And total number of subarrays = 1 + 2 + 3 + 4 " }, { "code": null, "e": 32555, "s": 32469, "text": "This is nothing but sum of first (t – 1) consecutive numbers = (t * (t + 1)) / 2 – t." }, { "code": null, "e": 32662, "s": 32555, "text": "Similarly, if we had to find arithmetic subarrays with length at least 3, then we will consider the below," }, { "code": null, "e": 32682, "s": 32662, "text": "{1, 2, 3, 4, 5} = 1" }, { "code": null, "e": 32713, "s": 32682, "text": "{1, 2, 3, 4}, {2, 3, 4, 5} = 2" }, { "code": null, "e": 32749, "s": 32713, "text": "{1, 2, 3}, {2, 3, 4}, {3, 4, 5} = 3" }, { "code": null, "e": 32814, "s": 32749, "text": "And total number of subarrays in this case = 1 + 2 + 3 for t = 5" }, { "code": null, "e": 32905, "s": 32814, "text": "The math formula will exclude 4 i.e. (t – 1) and 5 i.e. t from its sum, so formula will be" }, { "code": null, "e": 32973, "s": 32905, "text": "(t * (t + 1)) / 2 – (t – 1) – (t) = (t * (t + 1)) / 2 – (2 * t) + 1" }, { "code": null, "e": 33082, "s": 32973, "text": "To count the maximum number of elements in a subarray with a particular difference, we use the variable num." }, { "code": null, "e": 33294, "s": 33082, "text": "d variable tracks the difference. d is initialized to the difference between 2nd and 1st element and num will be 1 since for subarrays with 2 elements, the total possible subarrays for that difference will be 1." }, { "code": null, "e": 33358, "s": 33294, "text": "Then i is incremented to 1 and we start iterating on the array." }, { "code": null, "e": 33896, "s": 33358, "text": "If the difference between adjacent elements matches the difference in variable d, we simply increment the num.If the difference between adjacent elements does not match the variable d, then we got the subarray with the maximum number of elements for that difference. The value of t i.e. maximum number of elements for that difference will be (num + 1). So we use the math formula to add the number of subarrays for length t.We reset the num to 1 for a new subarray and d to the new difference for next comparison and continue to Step 1." }, { "code": null, "e": 34007, "s": 33896, "text": "If the difference between adjacent elements matches the difference in variable d, we simply increment the num." }, { "code": null, "e": 34166, "s": 34007, "text": "If the difference between adjacent elements does not match the variable d, then we got the subarray with the maximum number of elements for that difference. " }, { "code": null, "e": 34324, "s": 34166, "text": "The value of t i.e. maximum number of elements for that difference will be (num + 1). So we use the math formula to add the number of subarrays for length t." }, { "code": null, "e": 34437, "s": 34324, "text": "We reset the num to 1 for a new subarray and d to the new difference for next comparison and continue to Step 1." }, { "code": null, "e": 34488, "s": 34437, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 34492, "s": 34488, "text": "C++" }, { "code": null, "e": 34500, "s": 34492, "text": "Python3" }, { "code": null, "e": 34511, "s": 34500, "text": "Javascript" }, { "code": "// C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // Function to find the// total count of subarraysint calcSubarray(int A[], int N){ // If size of array is smaller than 2, // then count will be zero if (N < 2) { return 0; } int i = 0; int num, d, count = 0, t; // Difference between first two adjacent array elements d = A[i + 1] - A[i]; // num stores the total number of elements in a subarray // for a particular difference num = 1; // After calculating difference, move to next element // and iterate over the array i = 1; while (i < N - 1) { // If Difference between adjacent elements is same // as d, increment num if (A[i + 1] - A[i] == d) { num++; } else { // Update the count if number of elements // in subarray is greater than 1 if (num >= 1) { t = num + 1; count = count + (t * (t + 1)) / 2 - t; } // Reset num num = 1; // Update with new difference d = A[i + 1] - A[i]; } i++; } if (num >= 1) { t = num + 1; count = count + (t * (t + 1)) / 2 - t; } return count;} // Driver Codeint main(){ // Given Array int A[5] = { 8, 7, 4, 1, 0 }; int N = sizeof(A) / sizeof(int); // Function Call cout << calcSubarray(A, N); return 0; // This code is contributed by Snigdha Patil}", "e": 36022, "s": 34511, "text": null }, { "code": "# Python implementation of# the above approach # Function to find the# total count of subarraysdef calcSubarray(A,N): # If size of array is smaller than 2, # then count will be zero if (N < 2): return 0 i = 0 num = 0 count = 0 t = 0 # Difference between first two adjacent array elements d = A[i + 1] - A[i] # num stores the total number of elements in a subarray # for a particular difference num = 1 # After calculating difference, move to next element # and iterate over the array i = 1 while (i < N - 1): # If Difference between adjacent elements is same # as d, increment num if (A[i + 1] - A[i] == d): num += 1 else: # Update the count if number of elements # in subarray is greater than 1 if (num >= 1): t = num + 1 count = count + (t * (t + 1)) // 2 - t # Reset num num = 1 # Update with new difference d = A[i + 1] - A[i] i += 1 if (num >= 1): t = num + 1 count = count + (t * (t + 1)) // 2 - t return count # Driver Code # Given ArrayA = [ 8, 7, 4, 1, 0 ]N = len(A) # Function Callprint(calcSubarray(A, N)) # This code is contributed by Shinjanpatra", "e": 37321, "s": 36022, "text": null }, { "code": "<script> // JavaScript implementation of// the above approach // Function to find the// total count of subarraysfunction calcSubarray(A, N){ // If size of array is smaller than 2, // then count will be zero if (N < 2) { return 0; } let i = 0; let num, d, count = 0, t; // Difference between first two adjacent array elements d = A[i + 1] - A[i]; // num stores the total number of elements in a subarray // for a particular difference num = 1; // After calculating difference, move to next element // and iterate over the array i = 1; while (i < N - 1) { // If Difference between adjacent elements is same // as d, increment num if (A[i + 1] - A[i] == d) { num++; } else { // Update the count if number of elements // in subarray is greater than 1 if (num >= 1) { t = num + 1; count = count + Math.floor((t * (t + 1)) / 2) - t; } // Reset num num = 1; // Update with new difference d = A[i + 1] - A[i]; } i++; } if (num >= 1) { t = num + 1; count = count + Math.floor((t * (t + 1)) / 2) - t; } return count;} // Driver Code // Given Arraylet A = [ 8, 7, 4, 1, 0 ];let N = A.length; // Function Calldocument.write(calcSubarray(A, N)); // This code is contributed by Shinjanpatra </script>", "e": 38774, "s": 37321, "text": null }, { "code": null, "e": 38776, "s": 38774, "text": "5" }, { "code": null, "e": 38799, "s": 38776, "text": "Time Complexity: O(N) " }, { "code": null, "e": 38822, "s": 38799, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 38837, "s": 38822, "text": "mohit kumar 29" }, { "code": null, "e": 38847, "s": 38837, "text": "Rajput-Ji" }, { "code": null, "e": 38859, "s": 38847, "text": "29AjayKumar" }, { "code": null, "e": 38875, "s": 38859, "text": "mayanktyagi1709" }, { "code": null, "e": 38882, "s": 38875, "text": "sniggy" }, { "code": null, "e": 38895, "s": 38882, "text": "shinjanpatra" }, { "code": null, "e": 38918, "s": 38895, "text": "arithmetic progression" }, { "code": null, "e": 38927, "s": 38918, "text": "subarray" }, { "code": null, "e": 38934, "s": 38927, "text": "Arrays" }, { "code": null, "e": 38947, "s": 38934, "text": "Mathematical" }, { "code": null, "e": 38957, "s": 38947, "text": "Searching" }, { "code": null, "e": 38964, "s": 38957, "text": "Arrays" }, { "code": null, "e": 38974, "s": 38964, "text": "Searching" }, { "code": null, "e": 38987, "s": 38974, "text": "Mathematical" }, { "code": null, "e": 39085, "s": 38987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39094, "s": 39085, "text": "Comments" }, { "code": null, "e": 39107, "s": 39094, "text": "Old Comments" }, { "code": null, "e": 39156, "s": 39107, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 39176, "s": 39156, "text": "Trapping Rain Water" }, { "code": null, "e": 39214, "s": 39176, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 39299, "s": 39214, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 39324, "s": 39299, "text": "Window Sliding Technique" }, { "code": null, "e": 39354, "s": 39324, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 39414, "s": 39354, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 39429, "s": 39414, "text": "C++ Data Types" }, { "code": null, "e": 39472, "s": 39429, "text": "Set in C++ Standard Template Library (STL)" } ]
Match element in array of MongoDB?
You can use $or operator along with limit(1) to match element in array. Let us first create a collection with documents − > db.matchElementInArrayDemo.insertOne( ... { ... "StudentName" : "Chris" , ... "StudentOtherDetails" : ... [ ... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"}, ... {"StudentCountryName" : "UK" , "StudentSkills" : "Java"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd423282cba06f46efe9ee2") } > db.matchElementInArrayDemo.insertOne( ... { ... "StudentName" : "Chris" , ... "StudentOtherDetails" : ... [ ... {"StudentCountryName" : "AUS" , "StudentSkills" : "PHP"}, ... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd423412cba06f46efe9ee3") } Following is the query to display all documents from a collection with the help of find() method − > db.matchElementInArrayDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5cd423282cba06f46efe9ee2"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" }, { "StudentCountryName" : "UK", "StudentSkills" : "Java" } ] } { "_id" : ObjectId("5cd423412cba06f46efe9ee3"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "AUS", "StudentSkills" : "PHP" }, { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" } ] } Here is the query to match element in array of MongoDB − > db.matchElementInArrayDemo.find( { $or : [ {"StudentOtherDetails.StudentCountryName": "US" } ,{"StudentOtherDetails.StudentSkills": "MongoDB" } ] } ).limit(1); This will produce the following output − { "_id" : ObjectId("5cd423282cba06f46efe9ee2"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" }, { "StudentCountryName" : "UK", "StudentSkills" : "Java" } ] }
[ { "code": null, "e": 1184, "s": 1062, "text": "You can use $or operator along with limit(1) to match element in array. Let us first create a collection with documents −" }, { "code": null, "e": 1945, "s": 1184, "text": "> db.matchElementInArrayDemo.insertOne(\n... {\n... \"StudentName\" : \"Chris\" ,\n... \"StudentOtherDetails\" :\n... [\n... {\"StudentCountryName\" : \"US\" , \"StudentSkills\" : \"MongoDB\"},\n... {\"StudentCountryName\" : \"UK\" , \"StudentSkills\" : \"Java\"}\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd423282cba06f46efe9ee2\")\n}\n> db.matchElementInArrayDemo.insertOne(\n... {\n... \"StudentName\" : \"Chris\" ,\n... \"StudentOtherDetails\" :\n... [\n... {\"StudentCountryName\" : \"AUS\" , \"StudentSkills\" : \"PHP\"},\n... {\"StudentCountryName\" : \"US\" , \"StudentSkills\" : \"MongoDB\"}\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd423412cba06f46efe9ee3\")\n}" }, { "code": null, "e": 2044, "s": 1945, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2090, "s": 2044, "text": "> db.matchElementInArrayDemo.find().pretty();" }, { "code": null, "e": 2131, "s": 2090, "text": "This will produce the following output −" }, { "code": null, "e": 2721, "s": 2131, "text": "{\n \"_id\" : ObjectId(\"5cd423282cba06f46efe9ee2\"),\n \"StudentName\" : \"Chris\",\n \"StudentOtherDetails\" : [\n {\n \"StudentCountryName\" : \"US\",\n \"StudentSkills\" : \"MongoDB\"\n },\n {\n \"StudentCountryName\" : \"UK\",\n \"StudentSkills\" : \"Java\"\n }\n ]\n}\n{\n \"_id\" : ObjectId(\"5cd423412cba06f46efe9ee3\"),\n \"StudentName\" : \"Chris\",\n \"StudentOtherDetails\" : [\n {\n \"StudentCountryName\" : \"AUS\",\n \"StudentSkills\" : \"PHP\"\n },\n {\n \"StudentCountryName\" : \"US\",\n \"StudentSkills\" : \"MongoDB\"\n }\n ]\n}" }, { "code": null, "e": 2778, "s": 2721, "text": "Here is the query to match element in array of MongoDB −" }, { "code": null, "e": 2940, "s": 2778, "text": "> db.matchElementInArrayDemo.find( { $or : [ {\"StudentOtherDetails.StudentCountryName\": \"US\" } ,{\"StudentOtherDetails.StudentSkills\": \"MongoDB\" } ] } ).limit(1);" }, { "code": null, "e": 2981, "s": 2940, "text": "This will produce the following output −" }, { "code": null, "e": 3204, "s": 2981, "text": "{ \"_id\" : ObjectId(\"5cd423282cba06f46efe9ee2\"), \"StudentName\" : \"Chris\", \"StudentOtherDetails\" : [ { \"StudentCountryName\" : \"US\", \"StudentSkills\" : \"MongoDB\" }, { \"StudentCountryName\" : \"UK\", \"StudentSkills\" : \"Java\" } ] }" } ]
Arduino - Keyboard Message
In this example, when the button is pressed, a text string is sent to the computer as keyboard input. The string reports the number of times the button is pressed. Once you have the Leonardo programmed and wired up, open your favorite text editor to see the results. Warning − When you use the Keyboard.print() command, the Arduino takes over your computer's keyboard. To ensure you do not lose control of your computer while running a sketch with this function, set up a reliable control system before you call Keyboard.print(). This sketch includes a pushbutton to toggle the keyboard, so that it only runs after the button is pressed. You will need the following components − 1 × Breadboard 1 × Arduino Leonardo, Micro, or Due board 1 × momentary pushbutton 1 × 10k ohm resistor Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below. Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. /* Keyboard Message test For the Arduino Leonardo and Micro, Sends a text string when a button is pressed. The circuit: * pushbutton attached from pin 4 to +5V * 10-kilohm resistor attached from pin 4 to ground */ #include "Keyboard.h" const int buttonPin = 4; // input pin for pushbutton int previousButtonState = HIGH; // for checking the state of a pushButton int counter = 0; // button push counter void setup() { pinMode(buttonPin, INPUT); // make the pushButton pin an input: Keyboard.begin(); // initialize control over the keyboard: } void loop() { int buttonState = digitalRead(buttonPin); // read the pushbutton: if ((buttonState != previousButtonState)&& (buttonState == HIGH)) // and it's currently pressed: { // increment the button counter counter++; // type out a message Keyboard.print("You pressed the button "); Keyboard.print(counter); Keyboard.println(" times."); } // save the current button state for comparison next time: previousButtonState = buttonState; } Attach one terminal of the pushbutton to pin 4 on Arduino. Attach the other pin to 5V. Use the resistor as a pull-down, providing a reference to the ground, by attaching it from pin 4 to the ground. Once you have programmed your board, unplug the USB cable, open a text editor and put the text cursor in the typing area. Connect the board to your computer through USB again and press the button to write in the document. By using any text editor, it will display the text sent via Arduino. 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3137, "s": 2870, "text": "In this example, when the button is pressed, a text string is sent to the computer as keyboard input. The string reports the number of times the button is pressed. Once you have the Leonardo programmed and wired up, open your favorite text editor to see the results." }, { "code": null, "e": 3508, "s": 3137, "text": "Warning − When you use the Keyboard.print() command, the Arduino takes over your computer's keyboard. To ensure you do not lose control of your computer while running a sketch with this function, set up a reliable control system before you call Keyboard.print(). This sketch includes a pushbutton to toggle the keyboard, so that it only runs after the button is pressed." }, { "code": null, "e": 3549, "s": 3508, "text": "You will need the following components −" }, { "code": null, "e": 3564, "s": 3549, "text": "1 × Breadboard" }, { "code": null, "e": 3606, "s": 3564, "text": "1 × Arduino Leonardo, Micro, or Due board" }, { "code": null, "e": 3631, "s": 3606, "text": "1 × momentary pushbutton" }, { "code": null, "e": 3652, "s": 3631, "text": "1 × 10k ohm resistor" }, { "code": null, "e": 3759, "s": 3652, "text": "Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below." }, { "code": null, "e": 3905, "s": 3759, "text": "Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New." }, { "code": null, "e": 4965, "s": 3905, "text": "/*\n Keyboard Message test For the Arduino Leonardo and Micro,\n Sends a text string when a button is pressed.\n The circuit:\n * pushbutton attached from pin 4 to +5V\n * 10-kilohm resistor attached from pin 4 to ground\n*/\n\n#include \"Keyboard.h\"\nconst int buttonPin = 4; // input pin for pushbutton\nint previousButtonState = HIGH; // for checking the state of a pushButton\nint counter = 0; // button push counter\n\nvoid setup() {\n pinMode(buttonPin, INPUT); // make the pushButton pin an input:\n Keyboard.begin(); // initialize control over the keyboard:\n}\n\nvoid loop() {\n int buttonState = digitalRead(buttonPin); // read the pushbutton:\n if ((buttonState != previousButtonState)&& (buttonState == HIGH)) // and it's currently pressed: {\n // increment the button counter\n counter++;\n // type out a message\n Keyboard.print(\"You pressed the button \");\n Keyboard.print(counter);\n Keyboard.println(\" times.\");\n }\n // save the current button state for comparison next time:\n previousButtonState = buttonState;\n}" }, { "code": null, "e": 5164, "s": 4965, "text": "Attach one terminal of the pushbutton to pin 4 on Arduino. Attach the other pin to 5V. Use the resistor as a pull-down, providing a reference to the ground, by attaching it from pin 4 to the ground." }, { "code": null, "e": 5386, "s": 5164, "text": "Once you have programmed your board, unplug the USB cable, open a text editor and put the text cursor in the typing area. Connect the board to your computer through USB again and press the button to write in the document." }, { "code": null, "e": 5455, "s": 5386, "text": "By using any text editor, it will display the text sent via Arduino." }, { "code": null, "e": 5490, "s": 5455, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5501, "s": 5490, "text": " Amit Rana" }, { "code": null, "e": 5534, "s": 5501, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 5545, "s": 5534, "text": " Amit Rana" }, { "code": null, "e": 5578, "s": 5545, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5591, "s": 5578, "text": " Ashraf Said" }, { "code": null, "e": 5626, "s": 5591, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5639, "s": 5626, "text": " Ashraf Said" }, { "code": null, "e": 5671, "s": 5639, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 5684, "s": 5671, "text": " Ashraf Said" }, { "code": null, "e": 5715, "s": 5684, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 5728, "s": 5715, "text": " Ashraf Said" }, { "code": null, "e": 5735, "s": 5728, "text": " Print" }, { "code": null, "e": 5746, "s": 5735, "text": " Add Notes" } ]
Can we cast an object reference to an interface reference in java? If so when?
Yes, you can. If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference. But, using this you can access the methods of the interface only, if you try to access the methods of the class a compile time error is generated. In the following Java example, we have an interface named MyInterface with an abstract method display(). We have a class with name InterfaceExample with a method (show()). In addition to it, we are implementing the display() method of the interface. In the main method we are assigning the object of the class to the reference variable of the interface and trying to invoke both the method. interface MyInterface{ public static int num = 100; public void display(); } public class InterfaceExample implements MyInterface{ public void display() { System.out.println("This is the implementation of the display method"); } public void show() { System.out.println("This is the implementation of the show method"); } public static void main(String args[]) { MyInterface obj = new InterfaceExample(); obj.display(); obj.show(); } } On compiling, the above program generates the following compile time error − InterfaceExample.java:16: error: cannot find symbol obj.show(); ^ symbol: method show() location: variable obj of type MyInterface 1 error To make this program work you need to remove the line calling the method of the class as − Live Demo interface MyInterface{ public static int num = 100; public void display(); } public class InterfaceExample implements MyInterface{ public void display() { System.out.println("This is the implementation of the display method"); } public void show() { System.out.println("This is the implementation of the show method"); } public static void main(String args[]) { MyInterface obj = new InterfaceExample(); obj.display(); //obj.show(); } } Now, the program gets compiled and executed successfully. This is the implementation of the display method Therefore, you need to cast an object reference to an interface reference. Whenever you need to call the methods of the interface only.
[ { "code": null, "e": 1076, "s": 1062, "text": "Yes, you can." }, { "code": null, "e": 1293, "s": 1076, "text": "If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference." }, { "code": null, "e": 1440, "s": 1293, "text": "But, using this you can access the methods of the interface only, if you try to access the methods of the class a compile time error is generated." }, { "code": null, "e": 1545, "s": 1440, "text": "In the following Java example, we have an interface named MyInterface with an abstract method display()." }, { "code": null, "e": 1690, "s": 1545, "text": "We have a class with name InterfaceExample with a method (show()). In addition to it, we are implementing the display() method of the interface." }, { "code": null, "e": 1831, "s": 1690, "text": "In the main method we are assigning the object of the class to the reference variable of the interface and trying to invoke both the method." }, { "code": null, "e": 2320, "s": 1831, "text": "interface MyInterface{\n public static int num = 100;\n public void display();\n}\npublic class InterfaceExample implements MyInterface{\n public void display() {\n System.out.println(\"This is the implementation of the display method\");\n }\n public void show() {\n System.out.println(\"This is the implementation of the show method\");\n }\n public static void main(String args[]) {\n MyInterface obj = new InterfaceExample();\n obj.display();\n obj.show();\n }\n}" }, { "code": null, "e": 2397, "s": 2320, "text": "On compiling, the above program generates the following compile time error −" }, { "code": null, "e": 2545, "s": 2397, "text": "InterfaceExample.java:16: error: cannot find symbol\n obj.show();\n ^\nsymbol: method show()\nlocation: variable obj of type MyInterface\n1 error" }, { "code": null, "e": 2636, "s": 2545, "text": "To make this program work you need to remove the line calling the method of the class as −" }, { "code": null, "e": 2647, "s": 2636, "text": " Live Demo" }, { "code": null, "e": 3138, "s": 2647, "text": "interface MyInterface{\n public static int num = 100;\n public void display();\n}\npublic class InterfaceExample implements MyInterface{\n public void display() {\n System.out.println(\"This is the implementation of the display method\");\n }\n public void show() {\n System.out.println(\"This is the implementation of the show method\");\n }\n public static void main(String args[]) {\n MyInterface obj = new InterfaceExample();\n obj.display();\n //obj.show();\n }\n}" }, { "code": null, "e": 3196, "s": 3138, "text": "Now, the program gets compiled and executed successfully." }, { "code": null, "e": 3245, "s": 3196, "text": "This is the implementation of the display method" }, { "code": null, "e": 3381, "s": 3245, "text": "Therefore, you need to cast an object reference to an interface reference. Whenever you need to call the methods of the interface only." } ]
Root to leaf path sum | Practice | GeeksforGeeks
Given a binary tree and an integer S, check whether there is root to leaf path with its sum as S. Example 1: Input: Tree = 1 / \ 2 3 S = 2 Output: 0 Explanation: There is no root to leaf path with sum 2. Example 2: Input: Tree = 1 / \ 2 3 S = 4 Output: 1 Explanation: The sum of path from leaf node 3 to root 1 is 4. Your Task: You dont need to read input or print anything. Complete the function hasPathSum() which takes root node and target sum S as input parameter and returns true if path exists otherwise it returns false. Expected Time Complexity: O(N) Expected Auxiliary Space: O(height of tree) Constraints: 1 ≤ N ≤ 10^4 1 ≤ S ≤ 10^6 0 harshscode1 week ago if(root==NULL or root->data>s) return 0; if(root->left==NULL and root->right==NULL and root->data==s) return true; return hasPathSum(root->left,s-root->data) || hasPathSum(root->right,s-root->data); 0 detroix07 This comment was deleted. 0 roopsaisurampudi1 month ago boolean hasPathSum(Node root, int S) { // Your code here if (root == null) return false; if (root.data > S) return false; if (root.left == null && root.right == null) return (S==root.data); return hasPathSum(root.left, S-root.data) || hasPathSum(root.right, S-root.data); } 0 shankarmudiraj8271 month ago JAVA SOLUTION class Solution { /*you are required to complete this function */ static int sum=0; static boolean f=false; boolean hasPathSum(Node root, int S) { sum=0; f=false; Solution s=new Solution(); if(root==null) return true; check(root,sum,S); return f; } void check(Node root,int sum,int s){ if(root==null) return; if((root.left==null && root.right==null)&& (sum+root.data==s)) { f=true; } check(root.left,sum+root.data,s); check(root.right,sum+root.data,s); }} 0 ankukumar74242 months ago bool hasPathSum(Node *root, int S) { if(root==NULL) return false; int subsum=S-root->data; if(!root->left && !root->right && subsum==0) return true; bool a=hasPathSum(root->left,S-root->data); bool b=hasPathSum(root->right,S-root->data); return a||b;} +1 gulashanshashishekhar292 months ago bool hasPathSum(Node *root, int S) { // Your code here if (!root || root->data > S) return false; if (!root->left && !root->right && S == root->data) return true; return hasPathSum(root->left, S - root->data) || hasPathSum(root->right, S - root->data); } 0 mohankumarit20012 months ago bool hasPathSum(Node *root, int S) { if(!root)return false; if(!root->left && !root->right && ((S-root->data)==0))return true; return hasPathSum(root->left,S-root->data) || hasPathSum(root->right,S-root->data); } +1 aloksinghbais022 months ago C++ solution having time complexity as O(N) and space complexity as O(Height) is as follows :- Execution Time :- 0.2 / 1.5 sec bool helper(Node *node,int s,int target){ if(!node) return (false); if(helper(node->left,node->data + s,target)) return (true); if(helper(node->right,node->data + s,target)) return (true); if(!node->left && !node->right && node->data + s == target) return (true); return (false); } bool hasPathSum(Node *root, int S){ return helper(root,0,S); } -1 goodluckji20013 months ago bool solve(Node *root , int sum){ if(root==NULL || sum < 0) return false; if(sum==root->data){ if(!root->right and !root->left) return true; else return false; } sum = sum - root->data; return (solve(root->left,sum) or solve(root->right,sum)); } bool hasPathSum(Node *root, int S) { return solve(root,S);} 0 manjaykumardpcse193 months ago class Solution { boolean hasPathSum(Node root, int s) { if(root == null) return false; if(root.left == null && root.right == null && s - root.data == 0) return true; return hasPathSum(root.left , s - root.data) || hasPathSum(root.right , s - root.data); } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 336, "s": 238, "text": "Given a binary tree and an integer S, check whether there is root to leaf path with its sum as S." }, { "code": null, "e": 347, "s": 336, "text": "Example 1:" }, { "code": null, "e": 482, "s": 347, "text": "Input:\nTree = \n 1\n / \\\n 2 3\nS = 2\n\nOutput: 0\n\nExplanation:\nThere is no root to leaf path with sum 2." }, { "code": null, "e": 493, "s": 482, "text": "Example 2:" }, { "code": null, "e": 635, "s": 493, "text": "Input:\nTree = \n 1\n / \\\n 2 3\nS = 4\n\nOutput: 1\n\nExplanation:\nThe sum of path from leaf node 3 to root 1 is 4." }, { "code": null, "e": 849, "s": 635, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function hasPathSum() which takes root node and target sum S as input parameter and returns true if path exists otherwise it returns false." }, { "code": null, "e": 925, "s": 849, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(height of tree)" }, { "code": null, "e": 964, "s": 925, "text": "Constraints:\n1 ≤ N ≤ 10^4\n1 ≤ S ≤ 10^6" }, { "code": null, "e": 966, "s": 964, "text": "0" }, { "code": null, "e": 987, "s": 966, "text": "harshscode1 week ago" }, { "code": null, "e": 1231, "s": 987, "text": "if(root==NULL or root->data>s) return 0; if(root->left==NULL and root->right==NULL and root->data==s) return true; return hasPathSum(root->left,s-root->data) || hasPathSum(root->right,s-root->data); " }, { "code": null, "e": 1233, "s": 1231, "text": "0" }, { "code": null, "e": 1243, "s": 1233, "text": "detroix07" }, { "code": null, "e": 1269, "s": 1243, "text": "This comment was deleted." }, { "code": null, "e": 1271, "s": 1269, "text": "0" }, { "code": null, "e": 1299, "s": 1271, "text": "roopsaisurampudi1 month ago" }, { "code": null, "e": 1617, "s": 1299, "text": "boolean hasPathSum(Node root, int S) {\n // Your code here\n if (root == null) return false;\n if (root.data > S) return false;\n if (root.left == null && root.right == null) return (S==root.data);\n return hasPathSum(root.left, S-root.data) || hasPathSum(root.right, S-root.data);\n }" }, { "code": null, "e": 1619, "s": 1617, "text": "0" }, { "code": null, "e": 1648, "s": 1619, "text": "shankarmudiraj8271 month ago" }, { "code": null, "e": 1662, "s": 1648, "text": "JAVA SOLUTION" }, { "code": null, "e": 1780, "s": 1662, "text": " class Solution { /*you are required to complete this function */ static int sum=0; static boolean f=false;" }, { "code": null, "e": 2137, "s": 1780, "text": " boolean hasPathSum(Node root, int S) { sum=0; f=false; Solution s=new Solution(); if(root==null) return true; check(root,sum,S); return f; } void check(Node root,int sum,int s){ if(root==null) return; if((root.left==null && root.right==null)&& (sum+root.data==s)) { f=true;" }, { "code": null, "e": 2232, "s": 2137, "text": " } check(root.left,sum+root.data,s); check(root.right,sum+root.data,s); }}" }, { "code": null, "e": 2234, "s": 2232, "text": "0" }, { "code": null, "e": 2260, "s": 2234, "text": "ankukumar74242 months ago" }, { "code": null, "e": 2560, "s": 2260, "text": " bool hasPathSum(Node *root, int S) { if(root==NULL) return false; int subsum=S-root->data; if(!root->left && !root->right && subsum==0) return true; bool a=hasPathSum(root->left,S-root->data); bool b=hasPathSum(root->right,S-root->data); return a||b;}" }, { "code": null, "e": 2563, "s": 2560, "text": "+1" }, { "code": null, "e": 2599, "s": 2563, "text": "gulashanshashishekhar292 months ago" }, { "code": null, "e": 2918, "s": 2599, "text": "bool hasPathSum(Node *root, int S) {\n // Your code here\n if (!root || root->data > S) return false;\n if (!root->left && !root->right && \n \tS == root->data) return true;\n return hasPathSum(root->left, S - root->data) || \n hasPathSum(root->right, S - root->data);\n }" }, { "code": null, "e": 2920, "s": 2918, "text": "0" }, { "code": null, "e": 2949, "s": 2920, "text": "mohankumarit20012 months ago" }, { "code": null, "e": 3190, "s": 2949, "text": "bool hasPathSum(Node *root, int S) {\n if(!root)return false;\n if(!root->left && !root->right && ((S-root->data)==0))return true;\n return hasPathSum(root->left,S-root->data) || hasPathSum(root->right,S-root->data);\n }" }, { "code": null, "e": 3193, "s": 3190, "text": "+1" }, { "code": null, "e": 3221, "s": 3193, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 3317, "s": 3221, "text": "C++ solution having time complexity as O(N) and space complexity as O(Height) is as follows :- " }, { "code": null, "e": 3351, "s": 3319, "text": "Execution Time :- 0.2 / 1.5 sec" }, { "code": null, "e": 3757, "s": 3353, "text": "bool helper(Node *node,int s,int target){ if(!node) return (false); if(helper(node->left,node->data + s,target)) return (true); if(helper(node->right,node->data + s,target)) return (true); if(!node->left && !node->right && node->data + s == target) return (true); return (false); } bool hasPathSum(Node *root, int S){ return helper(root,0,S); }" }, { "code": null, "e": 3760, "s": 3757, "text": "-1" }, { "code": null, "e": 3787, "s": 3760, "text": "goodluckji20013 months ago" }, { "code": null, "e": 4195, "s": 3787, "text": " bool solve(Node *root , int sum){ if(root==NULL || sum < 0) return false; if(sum==root->data){ if(!root->right and !root->left) return true; else return false; } sum = sum - root->data; return (solve(root->left,sum) or solve(root->right,sum)); } bool hasPathSum(Node *root, int S) { return solve(root,S);}" }, { "code": null, "e": 4197, "s": 4195, "text": "0" }, { "code": null, "e": 4228, "s": 4197, "text": "manjaykumardpcse193 months ago" }, { "code": null, "e": 4522, "s": 4228, "text": "\n\nclass Solution {\n boolean hasPathSum(Node root, int s) {\n if(root == null) return false;\n if(root.left == null && root.right == null && s - root.data == 0) return true;\n return hasPathSum(root.left , s - root.data) || hasPathSum(root.right , s - root.data);\n }\n}" }, { "code": null, "e": 4668, "s": 4522, "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": 4704, "s": 4668, "text": " Login to access your submissions. " }, { "code": null, "e": 4714, "s": 4704, "text": "\nProblem\n" }, { "code": null, "e": 4724, "s": 4714, "text": "\nContest\n" }, { "code": null, "e": 4787, "s": 4724, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4935, "s": 4787, "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": 5143, "s": 4935, "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": 5249, "s": 5143, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Find one extra character in a string using C++.
Suppose we have two strings S and T, the length of S is n, and the length of T is n + 1. The T will hold all characters that are present in S, but it will hold one extra character. Our task is to find the extra character using some efficient approach. To solve this problem, we will take one empty hash table, and insert all characters of the second string, then remove each character from the first string, the remaining character is an extra character. Live Demo #include<iostream> #include<unordered_map> using namespace std; char getExtraCharacter(string S, string T) { unordered_map<char, int> char_map; for (int i = 0; i < T.length(); i++) char_map[T[i]]++; for (int i = 0; i < S.length(); i++) char_map[S[i]]--; for (auto item = char_map.begin(); item != char_map.end(); item++) { if (item->second == 1) return item->first; } } int main() { string S = "PQRST"; string T = "TUQPRS"; cout << "Extra character: " << getExtraCharacter(S, T); } Extra character: U
[ { "code": null, "e": 1314, "s": 1062, "text": "Suppose we have two strings S and T, the length of S is n, and the length of T is n + 1. The T will hold all characters that are present in S, but it will hold one extra character. Our task is to find the extra character using some efficient approach." }, { "code": null, "e": 1517, "s": 1314, "text": "To solve this problem, we will take one empty hash table, and insert all characters of the second string, then remove each character from the first string, the remaining character is an extra character." }, { "code": null, "e": 1528, "s": 1517, "text": " Live Demo" }, { "code": null, "e": 2058, "s": 1528, "text": "#include<iostream>\n#include<unordered_map>\nusing namespace std;\nchar getExtraCharacter(string S, string T) {\n unordered_map<char, int> char_map;\n for (int i = 0; i < T.length(); i++)\n char_map[T[i]]++;\n for (int i = 0; i < S.length(); i++)\n char_map[S[i]]--;\n for (auto item = char_map.begin(); item != char_map.end(); item++) {\n if (item->second == 1)\n return item->first;\n }\n}\nint main() {\n string S = \"PQRST\";\n string T = \"TUQPRS\";\n cout << \"Extra character: \" << getExtraCharacter(S, T);\n}" }, { "code": null, "e": 2077, "s": 2058, "text": "Extra character: U" } ]
\cdot - Tex Command
\cdot - Used to draw centered dot. { \cdot } \cdot command draws centered dot. a\cdot b a⋅b a\cdotp b a⋅b a\centerdot b a⋅b a\cdot b a⋅b a\cdot b a\cdotp b a⋅b a\cdotp b a\centerdot b a⋅b a\centerdot b 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8021, "s": 7986, "text": "\\cdot - Used to draw centered dot." }, { "code": null, "e": 8031, "s": 8021, "text": "{ \\cdot }" }, { "code": null, "e": 8065, "s": 8031, "text": "\\cdot command draws centered dot." }, { "code": null, "e": 8124, "s": 8065, "text": "\na\\cdot b \n\na⋅b\n\n\na\\cdotp b \n\na⋅b\n\n\na\\centerdot b \n\na⋅b\n\n\n" }, { "code": null, "e": 8141, "s": 8124, "text": "a\\cdot b \n\na⋅b\n\n" }, { "code": null, "e": 8151, "s": 8141, "text": "a\\cdot b " }, { "code": null, "e": 8169, "s": 8151, "text": "a\\cdotp b \n\na⋅b\n\n" }, { "code": null, "e": 8180, "s": 8169, "text": "a\\cdotp b " }, { "code": null, "e": 8202, "s": 8180, "text": "a\\centerdot b \n\na⋅b\n\n" }, { "code": null, "e": 8217, "s": 8202, "text": "a\\centerdot b " }, { "code": null, "e": 8249, "s": 8217, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8262, "s": 8249, "text": " Ashraf Said" }, { "code": null, "e": 8295, "s": 8262, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8308, "s": 8295, "text": " Ashraf Said" }, { "code": null, "e": 8340, "s": 8308, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8376, "s": 8340, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8411, "s": 8376, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8428, "s": 8411, "text": " Mohammad Nauman" }, { "code": null, "e": 8461, "s": 8428, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8475, "s": 8461, "text": " Daniel Stern" }, { "code": null, "e": 8507, "s": 8475, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8522, "s": 8507, "text": " Nishant Kumar" }, { "code": null, "e": 8529, "s": 8522, "text": " Print" }, { "code": null, "e": 8540, "s": 8529, "text": " Add Notes" } ]
Assertions in C/C++ - GeeksforGeeks
28 Feb, 2022 Assertions are statements used to test assumptions made by programmers. For example, we may use assertion to check if the pointer returned by malloc() is NULL or not. Following is the syntax for assertion. void assert( int expression ); If the expression evaluates to 0 (false), then the expression, sourcecode filename, and line number are sent to the standard error, and then abort() function is called. For example, consider the following program. C #include <stdio.h>#include <assert.h> int main(){ int x = 7; /* Some big code in between and let's say x is accidentally changed to 9 */ x = 9; // Programmer assumes x to be 7 in rest of the code assert(x==7); /* Rest of the code */ return 0;} Output Assertion failed: x==7, file test.cpp, line 13 This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. Assertion Vs Normal Error Handling Assertions are mainly used to check logically impossible situations. For example, they can be used to check the state of a code which is expected before it starts running, or the state after it finishes running. Unlike normal error handling, assertions are generally disabled at run-time. Therefore, it is not a good idea to write statements in assert() that can cause side effects. For example, writing something like assert(x = 5) is not a good idea as x is changed and this change won’t happen when assertions are disabled. See this for more details.Ignoring Assertions In C/C++, we can completely remove assertions at compile time using the preprocessor NDEBUG. C // The below program runs fine because NDEBUG is defined# define NDEBUG# include <assert.h> int main(){ int x = 7; assert (x==5); return 0;} The above program compiles and runs fine. In Java, assertions are not enabled by default and we must pass an option to the run-time engine to enable them.Reference: http://en.wikipedia.org/wiki/Assertion_%28software_development%29Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Jaideep Kaiwart bbsusheelkumar syedmuhammadalimustafa srinathvarda C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ Core Dump (Segmentation fault) in C/C++ fork() in C Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 24724, "s": 24696, "text": "\n28 Feb, 2022" }, { "code": null, "e": 24931, "s": 24724, "text": "Assertions are statements used to test assumptions made by programmers. For example, we may use assertion to check if the pointer returned by malloc() is NULL or not. Following is the syntax for assertion. " }, { "code": null, "e": 24963, "s": 24931, "text": "void assert( int expression ); " }, { "code": null, "e": 25179, "s": 24963, "text": "If the expression evaluates to 0 (false), then the expression, sourcecode filename, and line number are sent to the standard error, and then abort() function is called. For example, consider the following program. " }, { "code": null, "e": 25181, "s": 25179, "text": "C" }, { "code": "#include <stdio.h>#include <assert.h> int main(){ int x = 7; /* Some big code in between and let's say x is accidentally changed to 9 */ x = 9; // Programmer assumes x to be 7 in rest of the code assert(x==7); /* Rest of the code */ return 0;}", "e": 25458, "s": 25181, "text": null }, { "code": null, "e": 25466, "s": 25458, "text": "Output " }, { "code": null, "e": 25661, "s": 25466, "text": "Assertion failed: x==7, file test.cpp, line 13 \nThis application has requested the Runtime to terminate it in an unusual \nway. Please contact the application's support team for more information." }, { "code": null, "e": 26364, "s": 25661, "text": "Assertion Vs Normal Error Handling Assertions are mainly used to check logically impossible situations. For example, they can be used to check the state of a code which is expected before it starts running, or the state after it finishes running. Unlike normal error handling, assertions are generally disabled at run-time. Therefore, it is not a good idea to write statements in assert() that can cause side effects. For example, writing something like assert(x = 5) is not a good idea as x is changed and this change won’t happen when assertions are disabled. See this for more details.Ignoring Assertions In C/C++, we can completely remove assertions at compile time using the preprocessor NDEBUG. " }, { "code": null, "e": 26366, "s": 26364, "text": "C" }, { "code": "// The below program runs fine because NDEBUG is defined# define NDEBUG# include <assert.h> int main(){ int x = 7; assert (x==5); return 0;}", "e": 26516, "s": 26366, "text": null }, { "code": null, "e": 26872, "s": 26516, "text": "The above program compiles and runs fine. In Java, assertions are not enabled by default and we must pass an option to the run-time engine to enable them.Reference: http://en.wikipedia.org/wiki/Assertion_%28software_development%29Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 26888, "s": 26872, "text": "Jaideep Kaiwart" }, { "code": null, "e": 26903, "s": 26888, "text": "bbsusheelkumar" }, { "code": null, "e": 26926, "s": 26903, "text": "syedmuhammadalimustafa" }, { "code": null, "e": 26939, "s": 26926, "text": "srinathvarda" }, { "code": null, "e": 26950, "s": 26939, "text": "C Language" }, { "code": null, "e": 26954, "s": 26950, "text": "C++" }, { "code": null, "e": 26958, "s": 26954, "text": "CPP" }, { "code": null, "e": 27056, "s": 26958, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27091, "s": 27056, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27119, "s": 27091, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27165, "s": 27119, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27205, "s": 27165, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 27217, "s": 27205, "text": "fork() in C" }, { "code": null, "e": 27235, "s": 27217, "text": "Vector in C++ STL" }, { "code": null, "e": 27281, "s": 27235, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 27300, "s": 27281, "text": "Inheritance in C++" }, { "code": null, "e": 27343, "s": 27300, "text": "Map in C++ Standard Template Library (STL)" } ]
How to convert angular 4 application to desktop application using electron ? - GeeksforGeeks
13 Dec, 2021 Using Electron JS, we can convert our existing angular project into a desktop application very easily. In this post, we will create a sample Angular project and convert it into a Desktop application step by step. Prerequisites: NPM Must be installed Environment Setup: Install Angular CLI: npm install -g @angular/cli Create a new Angular Project. Here our project name is “electron-sample“: ng new electron-sample cd electron-sample Now run the project and open http://localhost:4200 to check whether the installation was successful or not. ng serve -o Install Electron JS as a development dependency: npm install electron --save-dev We also need a package called electron-packager. This package will bundle our app and produce the desktop app files. Install it globally: npm install -g electron-packager Example: In the root directory, create a file main.js that will be the entry point for the electron. Add the following code inside main.js: Javascript const { app, BrowserWindow } = require("electron");const path = require("path");const url = require("url"); let win;function createWindow() { win = new BrowserWindow({ width: 700, height: 700 }); // load the dist folder from Angular win.loadURL( url.format({ // compiled version of our app pathname: path.join(__dirname, '/dist/index.html'), protocol: "file:", slashes: true }) ); win.on("closed", () => { win = null; });}app.on("ready", createWindow);// If you are using MACOS, we have to quit the app manually app.on("window-all-closed", () => { if (process.platform !== "darwin") { app.quit(); }}); In the above code, we have simply opened the complied version of our Angular app that is present in the dist/ directory. Note that we have provided the dist folder directly so that this code works on any application. But the file index.html lies in a subdirectory. Hence, in angular.json, change the value in outputPath key as follows. ... "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { // Make changes in this line "outputPath": "dist", "index": "src/index.html", .... This will save the compiled files into dist folder instead of a sub-directory. In src/index.html, change the line <base href=”/”> to <base href=”./”> as follows. <head> <meta charset="utf-8"> <title>ElectronSample</title> <base href="./"> <!-- Change this line --> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> Now in package.json, we have to add some commands for the development and testing of our app as well as to point to the starting point of the electron app. Add the following lines in package.json. { "name": "electron-sample", "version": "0.0.0", // This line will provide an entry // point for the electron app "main": "main.js", "scripts": { // Runs the app after compilation "electron": "electron .", // Compiles and runs the app "electron-build": "ng build --prod && electron .", "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, ... ... Now we can test the app by running it/ npm run electron-build Note that we can run the commands directly if we had installed electron globally. You should see the below output : Output: For compiled app, we can run the app directly using npm run electron When we have created the final app, we can generate the compiled files that can be used directly on our system without installing the dependency. The electron-packager module helps us to build the binaries. electron-packager . --platform=linux Here we can choose our platform among darwin, Linux, Mac, and win32. Executing the above command will create a new folder with app and OS name. In this directory open the terminal: sudo chmod +x electron-sample ./electron-sample This will open the app, and you should see the following output: Output: singghakshay sumitgumber28 ElectronJS Picked AngularJS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers Introduction to AngularJS AngularJS | ng-src Directive ng-content in Angular How to force redirect to a particular route in angular? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Hide or show elements in HTML using display property Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ?
[ { "code": null, "e": 24744, "s": 24716, "text": "\n13 Dec, 2021" }, { "code": null, "e": 24957, "s": 24744, "text": "Using Electron JS, we can convert our existing angular project into a desktop application very easily. In this post, we will create a sample Angular project and convert it into a Desktop application step by step." }, { "code": null, "e": 24973, "s": 24957, "text": "Prerequisites: " }, { "code": null, "e": 24995, "s": 24973, "text": "NPM Must be installed" }, { "code": null, "e": 25014, "s": 24995, "text": "Environment Setup:" }, { "code": null, "e": 25035, "s": 25014, "text": "Install Angular CLI:" }, { "code": null, "e": 25063, "s": 25035, "text": "npm install -g @angular/cli" }, { "code": null, "e": 25137, "s": 25063, "text": "Create a new Angular Project. Here our project name is “electron-sample“:" }, { "code": null, "e": 25179, "s": 25137, "text": "ng new electron-sample\ncd electron-sample" }, { "code": null, "e": 25287, "s": 25179, "text": "Now run the project and open http://localhost:4200 to check whether the installation was successful or not." }, { "code": null, "e": 25299, "s": 25287, "text": "ng serve -o" }, { "code": null, "e": 25348, "s": 25299, "text": "Install Electron JS as a development dependency:" }, { "code": null, "e": 25380, "s": 25348, "text": "npm install electron --save-dev" }, { "code": null, "e": 25518, "s": 25380, "text": "We also need a package called electron-packager. This package will bundle our app and produce the desktop app files. Install it globally:" }, { "code": null, "e": 25551, "s": 25518, "text": "npm install -g electron-packager" }, { "code": null, "e": 25691, "s": 25551, "text": "Example: In the root directory, create a file main.js that will be the entry point for the electron. Add the following code inside main.js:" }, { "code": null, "e": 25702, "s": 25691, "text": "Javascript" }, { "code": "const { app, BrowserWindow } = require(\"electron\");const path = require(\"path\");const url = require(\"url\"); let win;function createWindow() { win = new BrowserWindow({ width: 700, height: 700 }); // load the dist folder from Angular win.loadURL( url.format({ // compiled version of our app pathname: path.join(__dirname, '/dist/index.html'), protocol: \"file:\", slashes: true }) ); win.on(\"closed\", () => { win = null; });}app.on(\"ready\", createWindow);// If you are using MACOS, we have to quit the app manually app.on(\"window-all-closed\", () => { if (process.platform !== \"darwin\") { app.quit(); }});", "e": 26352, "s": 25702, "text": null }, { "code": null, "e": 26688, "s": 26352, "text": "In the above code, we have simply opened the complied version of our Angular app that is present in the dist/ directory. Note that we have provided the dist folder directly so that this code works on any application. But the file index.html lies in a subdirectory. Hence, in angular.json, change the value in outputPath key as follows." }, { "code": null, "e": 26938, "s": 26688, "text": "...\n\"architect\": {\n \"build\": {\n \"builder\": \"@angular-devkit/build-angular:browser\",\n \"options\": {\n // Make changes in this line\n \"outputPath\": \"dist\", \n \"index\": \"src/index.html\",\n ...." }, { "code": null, "e": 27100, "s": 26938, "text": "This will save the compiled files into dist folder instead of a sub-directory. In src/index.html, change the line <base href=”/”> to <base href=”./”> as follows." }, { "code": null, "e": 27344, "s": 27100, "text": "<head>\n <meta charset=\"utf-8\">\n <title>ElectronSample</title>\n <base href=\"./\"> <!-- Change this line -->\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\">\n</head>" }, { "code": null, "e": 27541, "s": 27344, "text": "Now in package.json, we have to add some commands for the development and testing of our app as well as to point to the starting point of the electron app. Add the following lines in package.json." }, { "code": null, "e": 27987, "s": 27541, "text": "{\n \"name\": \"electron-sample\",\n \"version\": \"0.0.0\",\n // This line will provide an entry \n // point for the electron app\n \"main\": \"main.js\",\n \"scripts\": {\n // Runs the app after compilation\n \"electron\": \"electron .\", \n // Compiles and runs the app\n \"electron-build\": \"ng build --prod && electron .\",\n \"ng\": \"ng\",\n \"start\": \"ng serve\",\n \"build\": \"ng build\",\n \"test\": \"ng test\",\n \"lint\": \"ng lint\",\n \"e2e\": \"ng e2e\"\n },\n ...\n ..." }, { "code": null, "e": 28026, "s": 27987, "text": "Now we can test the app by running it/" }, { "code": null, "e": 28049, "s": 28026, "text": "npm run electron-build" }, { "code": null, "e": 28165, "s": 28049, "text": "Note that we can run the commands directly if we had installed electron globally. You should see the below output :" }, { "code": null, "e": 28173, "s": 28165, "text": "Output:" }, { "code": null, "e": 28226, "s": 28173, "text": "For compiled app, we can run the app directly using " }, { "code": null, "e": 28243, "s": 28226, "text": "npm run electron" }, { "code": null, "e": 28450, "s": 28243, "text": "When we have created the final app, we can generate the compiled files that can be used directly on our system without installing the dependency. The electron-packager module helps us to build the binaries." }, { "code": null, "e": 28487, "s": 28450, "text": "electron-packager . --platform=linux" }, { "code": null, "e": 28668, "s": 28487, "text": "Here we can choose our platform among darwin, Linux, Mac, and win32. Executing the above command will create a new folder with app and OS name. In this directory open the terminal:" }, { "code": null, "e": 28716, "s": 28668, "text": "sudo chmod +x electron-sample\n./electron-sample" }, { "code": null, "e": 28781, "s": 28716, "text": "This will open the app, and you should see the following output:" }, { "code": null, "e": 28789, "s": 28781, "text": "Output:" }, { "code": null, "e": 28802, "s": 28789, "text": "singghakshay" }, { "code": null, "e": 28816, "s": 28802, "text": "sumitgumber28" }, { "code": null, "e": 28827, "s": 28816, "text": "ElectronJS" }, { "code": null, "e": 28834, "s": 28827, "text": "Picked" }, { "code": null, "e": 28844, "s": 28834, "text": "AngularJS" }, { "code": null, "e": 28855, "s": 28844, "text": "JavaScript" }, { "code": null, "e": 28872, "s": 28855, "text": "Web Technologies" }, { "code": null, "e": 28970, "s": 28872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28979, "s": 28970, "text": "Comments" }, { "code": null, "e": 28992, "s": 28979, "text": "Old Comments" }, { "code": null, "e": 29036, "s": 28992, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 29062, "s": 29036, "text": "Introduction to AngularJS" }, { "code": null, "e": 29091, "s": 29062, "text": "AngularJS | ng-src Directive" }, { "code": null, "e": 29113, "s": 29091, "text": "ng-content in Angular" }, { "code": null, "e": 29169, "s": 29113, "text": "How to force redirect to a particular route in angular?" }, { "code": null, "e": 29214, "s": 29169, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29283, "s": 29214, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 29336, "s": 29283, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29408, "s": 29336, "text": "Differences between Functional Components and Class Components in React" } ]
DateTimeField - Django Models - GeeksforGeeks
12 Feb, 2020 DateTimeField is a date and time field which stores date, represented in Python by a datetime.datetime instance. As the name suggests, this field is used to store an object of datetime created in python. The default form widget for this field is a TextInput. The admin uses two separate TextInput widgets with JavaScript shortcuts. Syntax field_name = models.DateTimeField(**options) DateTimeField.auto_nowAutomatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that. Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that. DateTimeField.auto_now_addAutomatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True:For DateTimeField: default=datetime.now – from datetime.now()For DateTimeField: default=timezone.now – from django.utils.timezone.now() Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True: For DateTimeField: default=datetime.now – from datetime.now() For DateTimeField: default=timezone.now – from django.utils.timezone.now() Note: The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error. Illustration of DateTimeField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into models.py file of geeks app. from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.DateTimeField() Add the geeks app to INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now when we run makemigrations command from the terminal, Python manage.py makemigrations A new folder named migrations would be created in geeks directory with a file named 0001_initial.py # Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.DateTimeField()), ], ), ] Now run, Python manage.py migrate Thus, an geeks_field DateTimeField is created when you run migrations on the project. It is a field to store datetime.datetime python object. DateTimeField is used for storing python datetime.datetime instance in the database. One can store any type of date and time using the same in the database. Let’s try storing a date in model created above. # importing the model# from geeks appfrom geeks.models import GeeksModel # importing datetime moduleimport datetime # creating an instance of # datetime.dated = datetime(2015, 10, 09, 23, 55, 59, 342380) # creating an instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save() Now let’s check it in admin server. We have created an instance of GeeksModel. Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to DateTimeField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an DateTimeField can use. NaveenArora Django-models Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24274, "s": 24246, "text": "\n12 Feb, 2020" }, { "code": null, "e": 24606, "s": 24274, "text": "DateTimeField is a date and time field which stores date, represented in Python by a datetime.datetime instance. As the name suggests, this field is used to store an object of datetime created in python. The default form widget for this field is a TextInput. The admin uses two separate TextInput widgets with JavaScript shortcuts." }, { "code": null, "e": 24613, "s": 24606, "text": "Syntax" }, { "code": null, "e": 24658, "s": 24613, "text": "field_name = models.DateTimeField(**options)" }, { "code": null, "e": 25125, "s": 24658, "text": "DateTimeField.auto_nowAutomatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that." }, { "code": null, "e": 25570, "s": 25125, "text": "Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that." }, { "code": null, "e": 26112, "s": 25570, "text": "DateTimeField.auto_now_addAutomatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True:For DateTimeField: default=datetime.now – from datetime.now()For DateTimeField: default=timezone.now – from django.utils.timezone.now()" }, { "code": null, "e": 26493, "s": 26112, "text": "Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True:" }, { "code": null, "e": 26555, "s": 26493, "text": "For DateTimeField: default=datetime.now – from datetime.now()" }, { "code": null, "e": 26630, "s": 26555, "text": "For DateTimeField: default=timezone.now – from django.utils.timezone.now()" }, { "code": null, "e": 26766, "s": 26630, "text": "Note: The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error." }, { "code": null, "e": 26880, "s": 26766, "text": "Illustration of DateTimeField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 26967, "s": 26880, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 27018, "s": 26967, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 27051, "s": 27018, "text": "How to Create an App in Django ?" }, { "code": null, "e": 27110, "s": 27051, "text": "Enter the following code into models.py file of geeks app." }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.DateTimeField()", "e": 27265, "s": 27110, "text": null }, { "code": null, "e": 27301, "s": 27265, "text": "Add the geeks app to INSTALLED_APPS" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 27539, "s": 27301, "text": null }, { "code": null, "e": 27597, "s": 27539, "text": "Now when we run makemigrations command from the terminal," }, { "code": null, "e": 27629, "s": 27597, "text": "Python manage.py makemigrations" }, { "code": null, "e": 27729, "s": 27629, "text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py" }, { "code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.DateTimeField()), ], ), ]", "e": 28319, "s": 27729, "text": null }, { "code": null, "e": 28328, "s": 28319, "text": "Now run," }, { "code": null, "e": 28353, "s": 28328, "text": "Python manage.py migrate" }, { "code": null, "e": 28495, "s": 28353, "text": "Thus, an geeks_field DateTimeField is created when you run migrations on the project. It is a field to store datetime.datetime python object." }, { "code": null, "e": 28701, "s": 28495, "text": "DateTimeField is used for storing python datetime.datetime instance in the database. One can store any type of date and time using the same in the database. Let’s try storing a date in model created above." }, { "code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # importing datetime moduleimport datetime # creating an instance of # datetime.dated = datetime(2015, 10, 09, 23, 55, 59, 342380) # creating an instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()", "e": 29021, "s": 28701, "text": null }, { "code": null, "e": 29100, "s": 29021, "text": "Now let’s check it in admin server. We have created an instance of GeeksModel." }, { "code": null, "e": 29454, "s": 29100, "text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to DateTimeField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an DateTimeField can use." }, { "code": null, "e": 29466, "s": 29454, "text": "NaveenArora" }, { "code": null, "e": 29480, "s": 29466, "text": "Django-models" }, { "code": null, "e": 29494, "s": 29480, "text": "Python Django" }, { "code": null, "e": 29501, "s": 29494, "text": "Python" }, { "code": null, "e": 29599, "s": 29501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29617, "s": 29599, "text": "Python Dictionary" }, { "code": null, "e": 29652, "s": 29617, "text": "Read a file line by line in Python" }, { "code": null, "e": 29674, "s": 29652, "text": "Enumerate() in Python" }, { "code": null, "e": 29706, "s": 29674, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29736, "s": 29706, "text": "Iterate over a list in Python" }, { "code": null, "e": 29778, "s": 29736, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29804, "s": 29778, "text": "Python String | replace()" }, { "code": null, "e": 29841, "s": 29804, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29884, "s": 29841, "text": "Python program to convert a list to string" } ]