title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
JBoss Fuse - AMQ With Camel
In this chapter, we will learn the basics of how ActiveMQ works with Camel. Before we can use ActiveMQ queue or topic in our code we have to configure ActiveMQComponent. Minimal configuration of ActiveMQComponent can be done as shown in the following program − <bean id = "activemq" class = "org.apache.activemq.camel.component.ActiveMQComponent"> <property name = "brokerURL" value = "tcp://localhost:61616"/> <property name = "userName" value = "admin"/> <property name = "password" value = "admin"/> </bean> brokerURL − Specifies host and port for AMQ Broker. brokerURL − Specifies host and port for AMQ Broker. username − Specifies username to use for connecting to AMQ Broker. username − Specifies username to use for connecting to AMQ Broker. password − specifies password for connecting to AMQ Broker. password − specifies password for connecting to AMQ Broker. Now that we have configured ActiveMQComponent, we can use it in our CamelContext as endpoint. We will use AMQ endpoint in the following format − Activemq:[queue|topic]:[queueName|topicName] <?xml version = "1.0" encoding="UTF-8"?> <!-- Configures the Camel Context--> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> After deploying this bundle in Fuse container, you should be able to see messages posted to AMQ which were placed as files in D:/src/data. Input D:/src/data/input.txt Test me Output <?xml version = "1.0" encoding = "UTF-8"?> <!-- Configures the Camel Context--> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <camelContext xmlns = "http://camel.apache.org/schema/spring"> <!-- here is a sample which processes the input files (leaving them in place - see the 'noop' flag) then performs content based routing on the message using XPath --> <route> <from uri = "activemq:queue:TestQ"/> <to uri = "file:///d:/src"/> </route> </camelContext> <bean id = "activemq" class = "org.apache.activemq.camel.component.ActiveMQComponent"> <property name = "brokerURL" value = "tcp://localhost:61616"/> <property name = "userName" value = "admin"/> <property name = "password" value = "admin"/> </bean> </beans> Input After deploying this bundle, you should see a file being generated in D:/src and messages are consumed. Also Consumer should be shown for that Queue. Output D:/src Test me <?xml version = "1.0" encoding = "UTF-8"?> <!-- Configures the Camel Context--> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <camelContext xmlns = "http://camel.apache.org/schema/spring"> <!-- here is a sample which processes the input files (leaving them in place - see the 'noop' flag) then performs content based routing on the message using XPath --> <route> <from uri = "file:///d:/src"/> <to uri = "activemq:topic:TestTopic” /> </route> </camelContext> <bean id = "activemq" class = "org.apache.activemq.camel.component.ActiveMQComponent"> <property name = "brokerURL" value = "tcp://localhost:61616"/> <property name = "userName" value = "admin"/> <property name = "password" value = "admin"/> </bean> </beans> <?xml version = "1.0" encoding = "UTF-8"?> <!-- Configures the Camel Context--> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <camelContext xmlns = "http://camel.apache.org/schema/spring"> <!-- here is a sample which processes the input files (leaving them in place - see the 'noop' flag) then performs content based routing on the message using XPath --> <route> <from uri = "activemq:topic:TestTopic"/> <to uri = "file:///d:/src2"/> </route> </camelContext> <bean id = "activemq" class = "org.apache.activemq.camel.component.ActiveMQComponent"> <property name = "brokerURL" value="tcp://localhost:61616"/> <property name = "userName" value = "admin"/> <property name = "password" value = "admin"/> </bean> </beans> Input D:/src/file1.xml <order> <data> <value>value1</value> </data> </order> <order> <data> <value>value2</value> </data> </order> <order> <data> <value>value3</value> </data> </order> Output D:/src/ <order> <data> <value>value1</value> </data> </order> <order> <data> <value>value2</value> </data> </order> <order> <data> <value>value3</value> </data> </order> Print Add Notes Bookmark this page
[ { "code": null, "e": 1992, "s": 1916, "text": "In this chapter, we will learn the basics of how ActiveMQ works with Camel." }, { "code": null, "e": 2177, "s": 1992, "text": "Before we can use ActiveMQ queue or topic in our code we have to configure ActiveMQComponent. Minimal configuration of ActiveMQComponent can be done as shown in the following program −" }, { "code": null, "e": 2436, "s": 2177, "text": "<bean id = \"activemq\" class = \"org.apache.activemq.camel.component.ActiveMQComponent\">\n <property name = \"brokerURL\" value = \"tcp://localhost:61616\"/>\n <property name = \"userName\" value = \"admin\"/>\n <property name = \"password\" value = \"admin\"/>\n</bean>" }, { "code": null, "e": 2488, "s": 2436, "text": "brokerURL − Specifies host and port for AMQ Broker." }, { "code": null, "e": 2540, "s": 2488, "text": "brokerURL − Specifies host and port for AMQ Broker." }, { "code": null, "e": 2607, "s": 2540, "text": "username − Specifies username to use for connecting to AMQ Broker." }, { "code": null, "e": 2674, "s": 2607, "text": "username − Specifies username to use for connecting to AMQ Broker." }, { "code": null, "e": 2734, "s": 2674, "text": "password − specifies password for connecting to AMQ Broker." }, { "code": null, "e": 2794, "s": 2734, "text": "password − specifies password for connecting to AMQ Broker." }, { "code": null, "e": 2888, "s": 2794, "text": "Now that we have configured ActiveMQComponent, we can use it in our CamelContext as endpoint." }, { "code": null, "e": 2939, "s": 2888, "text": "We will use AMQ endpoint in the following format −" }, { "code": null, "e": 2985, "s": 2939, "text": "Activemq:[queue|topic]:[queueName|topicName]\n" }, { "code": null, "e": 3417, "s": 2985, "text": "<?xml version = \"1.0\" encoding=\"UTF-8\"?>\n<!-- Configures the Camel Context-->\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans.xsd\n http://camel.apache.org/schema/spring\n http://camel.apache.org/schema/spring/camel-spring.xsd\">" }, { "code": null, "e": 3556, "s": 3417, "text": "After deploying this bundle in Fuse container, you should be able to see messages posted to AMQ which were placed as files in D:/src/data." }, { "code": null, "e": 3562, "s": 3556, "text": "Input" }, { "code": null, "e": 3584, "s": 3562, "text": "D:/src/data/input.txt" }, { "code": null, "e": 3593, "s": 3584, "text": "Test me\n" }, { "code": null, "e": 3600, "s": 3593, "text": "Output" }, { "code": null, "e": 4723, "s": 3600, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!-- Configures the Camel Context-->\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans.xsd\n http://camel.apache.org/schema/spring\n http://camel.apache.org/schema/spring/camel-spring.xsd\">\n\t\n <camelContext xmlns = \"http://camel.apache.org/schema/spring\">\n <!-- here is a sample which processes the input files\n (leaving them in place - see the 'noop' flag)\n then performs content based routing on the message using XPath -->\n\t\t\t \n <route>\n <from uri = \"activemq:queue:TestQ\"/>\n <to uri = \"file:///d:/src\"/>\n </route>\n </camelContext>\n\t\n <bean id = \"activemq\" class = \"org.apache.activemq.camel.component.ActiveMQComponent\">\n <property name = \"brokerURL\" value = \"tcp://localhost:61616\"/>\n <property name = \"userName\" value = \"admin\"/>\n <property name = \"password\" value = \"admin\"/>\n </bean>\n\t\n</beans>" }, { "code": null, "e": 4729, "s": 4723, "text": "Input" }, { "code": null, "e": 4879, "s": 4729, "text": "After deploying this bundle, you should see a file being generated in D:/src and messages are consumed. Also Consumer should be shown for that Queue." }, { "code": null, "e": 4886, "s": 4879, "text": "Output" }, { "code": null, "e": 4893, "s": 4886, "text": "D:/src" }, { "code": null, "e": 4902, "s": 4893, "text": "Test me\n" }, { "code": null, "e": 6027, "s": 4902, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!-- Configures the Camel Context-->\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans.xsd\n http://camel.apache.org/schema/spring \n http://camel.apache.org/schema/spring/camel-spring.xsd\">\n\t\n <camelContext xmlns = \"http://camel.apache.org/schema/spring\">\n <!-- here is a sample which processes the input files\n (leaving them in place - see the 'noop' flag)\n then performs content based routing on the message using XPath -->\n\t\t\t \n <route>\n <from uri = \"file:///d:/src\"/>\n <to uri = \"activemq:topic:TestTopic” />\n </route>\n </camelContext>\n\t\n <bean id = \"activemq\" class = \"org.apache.activemq.camel.component.ActiveMQComponent\">\n <property name = \"brokerURL\" value = \"tcp://localhost:61616\"/>\n <property name = \"userName\" value = \"admin\"/>\n <property name = \"password\" value = \"admin\"/>\n </bean>\n\t\n</beans>" }, { "code": null, "e": 7152, "s": 6027, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!-- Configures the Camel Context-->\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans.xsd\n http://camel.apache.org/schema/spring \n http://camel.apache.org/schema/spring/camel-spring.xsd\">\n\t\n <camelContext xmlns = \"http://camel.apache.org/schema/spring\">\n <!-- here is a sample which processes the input files\n (leaving them in place - see the 'noop' flag)\n then performs content based routing on the message using XPath -->\n\t\t\t\n <route>\n <from uri = \"activemq:topic:TestTopic\"/>\n <to uri = \"file:///d:/src2\"/>\n </route>\n </camelContext>\n\t\n <bean id = \"activemq\" class = \"org.apache.activemq.camel.component.ActiveMQComponent\">\n <property name = \"brokerURL\" value=\"tcp://localhost:61616\"/>\n <property name = \"userName\" value = \"admin\"/>\n <property name = \"password\" value = \"admin\"/>\n </bean>\n\t\n</beans>" }, { "code": null, "e": 7158, "s": 7152, "text": "Input" }, { "code": null, "e": 7175, "s": 7158, "text": "D:/src/file1.xml" }, { "code": null, "e": 7375, "s": 7175, "text": "<order>\n <data>\n <value>value1</value>\n </data>\n</order>\n\n<order>\n <data>\n <value>value2</value>\n </data>\n</order>\n\n<order>\n <data>\n <value>value3</value>\n </data>\n</order>" }, { "code": null, "e": 7382, "s": 7375, "text": "Output" }, { "code": null, "e": 7390, "s": 7382, "text": "D:/src/" }, { "code": null, "e": 7591, "s": 7390, "text": "<order>\n <data>\n <value>value1</value>\n </data>\n</order>\n\n<order>\n <data>\n <value>value2</value>\n </data>\n</order>\n\n<order>\n <data>\n <value>value3</value>\n </data>\n</order>\n" }, { "code": null, "e": 7598, "s": 7591, "text": " Print" }, { "code": null, "e": 7609, "s": 7598, "text": " Add Notes" } ]
How to change the underline color in CSS? - GeeksforGeeks
25 May, 2021 Styling is implemented to HTML text to make it catchy and attractive. The text can be made italic, underline, and bold as per requirement. Underline tag: To change the color of the underline, we need to add some styling using CSS (inline/internal/external). By default, the color of the underline is black. In CSS, we will use text-decoration property to style underline.Syntax:<u> Some Text Here </u> Underline tag: To change the color of the underline, we need to add some styling using CSS (inline/internal/external). By default, the color of the underline is black. In CSS, we will use text-decoration property to style underline. Syntax: <u> Some Text Here </u> CSS text-decoration-color Property: This property is used to specify the color of decorations (overlines, underlines, and line-throughs) over the text.Syntax:text-decoration-color: color | initial | inherit ; CSS text-decoration-color Property: This property is used to specify the color of decorations (overlines, underlines, and line-throughs) over the text. Syntax: text-decoration-color: color | initial | inherit ; Below examples illustrate the approach of changing the underline color by CSS Example 1: HTML <!DOCTYPE html><html><body> <u style="text-decoration-color:red"> Geeksforgeeks A Computer Science Portal for Geeks </u></body></html> Output: Example 2: HTML <!DOCTYPE html><html> <head> <style> u { text-decoration-color: red; } </style> </head> <body> <h2> Geeksforgeeks <u>A Computer Science Portal for Geeks</u> </h2> </body></html> Output: CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? 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": 25011, "s": 24983, "text": "\n25 May, 2021" }, { "code": null, "e": 25150, "s": 25011, "text": "Styling is implemented to HTML text to make it catchy and attractive. The text can be made italic, underline, and bold as per requirement." }, { "code": null, "e": 25413, "s": 25150, "text": "Underline tag: To change the color of the underline, we need to add some styling using CSS (inline/internal/external). By default, the color of the underline is black. In CSS, we will use text-decoration property to style underline.Syntax:<u> Some Text Here </u>" }, { "code": null, "e": 25646, "s": 25413, "text": "Underline tag: To change the color of the underline, we need to add some styling using CSS (inline/internal/external). By default, the color of the underline is black. In CSS, we will use text-decoration property to style underline." }, { "code": null, "e": 25654, "s": 25646, "text": "Syntax:" }, { "code": null, "e": 25678, "s": 25654, "text": "<u> Some Text Here </u>" }, { "code": null, "e": 25887, "s": 25678, "text": "CSS text-decoration-color Property: This property is used to specify the color of decorations (overlines, underlines, and line-throughs) over the text.Syntax:text-decoration-color: color | initial | inherit ;" }, { "code": null, "e": 26039, "s": 25887, "text": "CSS text-decoration-color Property: This property is used to specify the color of decorations (overlines, underlines, and line-throughs) over the text." }, { "code": null, "e": 26047, "s": 26039, "text": "Syntax:" }, { "code": null, "e": 26098, "s": 26047, "text": "text-decoration-color: color | initial | inherit ;" }, { "code": null, "e": 26176, "s": 26098, "text": "Below examples illustrate the approach of changing the underline color by CSS" }, { "code": null, "e": 26187, "s": 26176, "text": "Example 1:" }, { "code": null, "e": 26192, "s": 26187, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <u style=\"text-decoration-color:red\"> Geeksforgeeks A Computer Science Portal for Geeks </u></body></html>", "e": 26345, "s": 26192, "text": null }, { "code": null, "e": 26353, "s": 26345, "text": "Output:" }, { "code": null, "e": 26364, "s": 26353, "text": "Example 2:" }, { "code": null, "e": 26369, "s": 26364, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> u { text-decoration-color: red; } </style> </head> <body> <h2> Geeksforgeeks <u>A Computer Science Portal for Geeks</u> </h2> </body></html>", "e": 26590, "s": 26369, "text": null }, { "code": null, "e": 26598, "s": 26590, "text": "Output:" }, { "code": null, "e": 26613, "s": 26598, "text": "CSS-Properties" }, { "code": null, "e": 26620, "s": 26613, "text": "Picked" }, { "code": null, "e": 26624, "s": 26620, "text": "CSS" }, { "code": null, "e": 26641, "s": 26624, "text": "Web Technologies" }, { "code": null, "e": 26739, "s": 26641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26748, "s": 26739, "text": "Comments" }, { "code": null, "e": 26761, "s": 26748, "text": "Old Comments" }, { "code": null, "e": 26798, "s": 26761, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26827, "s": 26798, "text": "Form validation using jQuery" }, { "code": null, "e": 26866, "s": 26827, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 26908, "s": 26866, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 26943, "s": 26908, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 26999, "s": 26943, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27032, "s": 26999, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27075, "s": 27032, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27136, "s": 27075, "text": "Difference between var, let and const keywords in JavaScript" } ]
How to replace all words with another words in HTML ? - GeeksforGeeks
11 Jun, 2020 The JavaScript replace() method is used to replace any occurrence of a character in a string or the entire string. It searches for a string corresponding to either a particular value or regular expression and returns a new string with the modified values. One can also use regular expressions instead of strings for defining the character or string to be replaced. A regular expression is a string that contains special symbols and characters to find and extract the information needed from the given data. Regular expressions are basically strings containing characters and special symbols that can help to select the required values. One has to note that the replace() function will replace only the first occurrence of the specified value. In order to replace all occurrences, one has to use the global modifier. Syntax: string.replace(valueToBeReplaced, newValue) where ‘valueToBeReplaced’ can either be a string value or a regular expression. Example 1: The replace() function will be used to replace the string ‘Hello’ with ‘Hi’ html <!DOCTYPE html><html> <head> <title>Replace Example</title></head> <body> <h1>Hello welcome to our blog!</h1> <p> Hello today we shall learn about replace() function in JavaScript Click on the button below to replace hello with hi. </p> <button onclick="rep()">Replace</button> <script> // Replace the first "Hello" // in the page with "Hi" function rep() { document.body.innerHTML = document.body.innerHTML .replace("Hello", "Hi"); } </script></body> </html> Output: Before clicking the button: Before clicking the button: After clicking the button: After clicking the button: As seen in the above output, only the first occurrence of ‘Hello’ was substituted with ‘Hi’. To substitute all occurrences, a global modifier has to be used. Example 2: Use the replace() function to replace all occurrences of the string ‘Hello’ with ‘Hi’ html <!DOCTYPE html><html> <head> <title>Replace Example</title></head> <body> <h1>Hello welcome to our blog!</h1> <p>Hello today we shall learn about replace() function in JavaScript Click on the button below to replace hello with hi. </p> <button onclick="rep()">Replace</button> <script> // Replace all the "Hello" // in the page with "Hi" function rep() { document.body.innerHTML = document.body.innerHTML .replace(/Hello/g, "Hi"); } </script></body> </html> Output: Before clicking the button: Before clicking the button: After clicking the button: After clicking the button: In the next example, both the global modifier and “i” modifier are used to ensure that all occurrences of the given word are replaced irrespective of their case. Example 3: Using the replace() function to replace all occurrences of the string ‘Hello’ with ‘Hi’ irrespective of their case. html <!DOCTYPE html><html> <head> <title>Replace Example</title></head> <body> <h1>Hello welcome to our blog!</h1> <p> Hello today we shall learn about replace() function in JavaScript Click on the button below to replace hello with hi. </p> <button onclick="rep()"> Replace </button> <script> // Replace all the "Hello" in the // page with "Hi" irrespective of // the case function rep() { document.body.innerHTML = document.body.innerHTML .replace(/Hello/gi, "Hi"); } </script></body> </html> Output: Before clicking the button: Before clicking the button: After clicking the button: After clicking the button: Example 4: Using the replace() function to replace all occurrences of the string ‘Hello’ with ‘Hi’ on a particular tag. html <!DOCTYPE html><html> <head> <title>Replace Example</title></head> <body> <h1>Hello welcome to our blog!</h1> <p>Hello today we shall learn about replace() function in JavaScript Click on the button below to replace hello with hi. </p> <button onclick="rep()">Replace</button> <script> // Replace all the "Hello" in the // page with "Hi" irrespective of the case // with the h1 tag function rep() { document.getElementById('h1').innerHTML = document.getElementById('h1') .innerHTML.replace(/Hello/g, "Hi"); } </script></body> </html> Output: Before clicking the button: Before clicking the button: After clicking the button: After clicking the button: As seen in the output, only the occurrences of ‘Hello’ in the h1 tag section of the code are replaced with ‘Hi’. HTML-Misc JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to filter object array based on attributes? Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25300, "s": 25272, "text": "\n11 Jun, 2020" }, { "code": null, "e": 25556, "s": 25300, "text": "The JavaScript replace() method is used to replace any occurrence of a character in a string or the entire string. It searches for a string corresponding to either a particular value or regular expression and returns a new string with the modified values." }, { "code": null, "e": 25936, "s": 25556, "text": "One can also use regular expressions instead of strings for defining the character or string to be replaced. A regular expression is a string that contains special symbols and characters to find and extract the information needed from the given data. Regular expressions are basically strings containing characters and special symbols that can help to select the required values." }, { "code": null, "e": 26116, "s": 25936, "text": "One has to note that the replace() function will replace only the first occurrence of the specified value. In order to replace all occurrences, one has to use the global modifier." }, { "code": null, "e": 26124, "s": 26116, "text": "Syntax:" }, { "code": null, "e": 26168, "s": 26124, "text": "string.replace(valueToBeReplaced, newValue)" }, { "code": null, "e": 26248, "s": 26168, "text": "where ‘valueToBeReplaced’ can either be a string value or a regular expression." }, { "code": null, "e": 26335, "s": 26248, "text": "Example 1: The replace() function will be used to replace the string ‘Hello’ with ‘Hi’" }, { "code": null, "e": 26340, "s": 26335, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Replace Example</title></head> <body> <h1>Hello welcome to our blog!</h1> <p> Hello today we shall learn about replace() function in JavaScript Click on the button below to replace hello with hi. </p> <button onclick=\"rep()\">Replace</button> <script> // Replace the first \"Hello\" // in the page with \"Hi\" function rep() { document.body.innerHTML = document.body.innerHTML .replace(\"Hello\", \"Hi\"); } </script></body> </html>", "e": 26933, "s": 26340, "text": null }, { "code": null, "e": 26941, "s": 26933, "text": "Output:" }, { "code": null, "e": 26970, "s": 26941, "text": "Before clicking the button: " }, { "code": null, "e": 26999, "s": 26970, "text": "Before clicking the button: " }, { "code": null, "e": 27027, "s": 26999, "text": "After clicking the button: " }, { "code": null, "e": 27055, "s": 27027, "text": "After clicking the button: " }, { "code": null, "e": 27213, "s": 27055, "text": "As seen in the above output, only the first occurrence of ‘Hello’ was substituted with ‘Hi’. To substitute all occurrences, a global modifier has to be used." }, { "code": null, "e": 27310, "s": 27213, "text": "Example 2: Use the replace() function to replace all occurrences of the string ‘Hello’ with ‘Hi’" }, { "code": null, "e": 27315, "s": 27310, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Replace Example</title></head> <body> <h1>Hello welcome to our blog!</h1> <p>Hello today we shall learn about replace() function in JavaScript Click on the button below to replace hello with hi. </p> <button onclick=\"rep()\">Replace</button> <script> // Replace all the \"Hello\" // in the page with \"Hi\" function rep() { document.body.innerHTML = document.body.innerHTML .replace(/Hello/g, \"Hi\"); } </script></body> </html>", "e": 27898, "s": 27315, "text": null }, { "code": null, "e": 27906, "s": 27898, "text": "Output:" }, { "code": null, "e": 27934, "s": 27906, "text": "Before clicking the button:" }, { "code": null, "e": 27962, "s": 27934, "text": "Before clicking the button:" }, { "code": null, "e": 27990, "s": 27962, "text": "After clicking the button: " }, { "code": null, "e": 28018, "s": 27990, "text": "After clicking the button: " }, { "code": null, "e": 28180, "s": 28018, "text": "In the next example, both the global modifier and “i” modifier are used to ensure that all occurrences of the given word are replaced irrespective of their case." }, { "code": null, "e": 28307, "s": 28180, "text": "Example 3: Using the replace() function to replace all occurrences of the string ‘Hello’ with ‘Hi’ irrespective of their case." }, { "code": null, "e": 28312, "s": 28307, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Replace Example</title></head> <body> <h1>Hello welcome to our blog!</h1> <p> Hello today we shall learn about replace() function in JavaScript Click on the button below to replace hello with hi. </p> <button onclick=\"rep()\"> Replace </button> <script> // Replace all the \"Hello\" in the // page with \"Hi\" irrespective of // the case function rep() { document.body.innerHTML = document.body.innerHTML .replace(/Hello/gi, \"Hi\"); } </script></body> </html>", "e": 28948, "s": 28312, "text": null }, { "code": null, "e": 28956, "s": 28948, "text": "Output:" }, { "code": null, "e": 28985, "s": 28956, "text": "Before clicking the button: " }, { "code": null, "e": 29014, "s": 28985, "text": "Before clicking the button: " }, { "code": null, "e": 29041, "s": 29014, "text": "After clicking the button:" }, { "code": null, "e": 29068, "s": 29041, "text": "After clicking the button:" }, { "code": null, "e": 29188, "s": 29068, "text": "Example 4: Using the replace() function to replace all occurrences of the string ‘Hello’ with ‘Hi’ on a particular tag." }, { "code": null, "e": 29193, "s": 29188, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Replace Example</title></head> <body> <h1>Hello welcome to our blog!</h1> <p>Hello today we shall learn about replace() function in JavaScript Click on the button below to replace hello with hi. </p> <button onclick=\"rep()\">Replace</button> <script> // Replace all the \"Hello\" in the // page with \"Hi\" irrespective of the case // with the h1 tag function rep() { document.getElementById('h1').innerHTML = document.getElementById('h1') .innerHTML.replace(/Hello/g, \"Hi\"); } </script></body> </html>", "e": 29864, "s": 29193, "text": null }, { "code": null, "e": 29872, "s": 29864, "text": "Output:" }, { "code": null, "e": 29900, "s": 29872, "text": "Before clicking the button:" }, { "code": null, "e": 29928, "s": 29900, "text": "Before clicking the button:" }, { "code": null, "e": 29956, "s": 29928, "text": "After clicking the button: " }, { "code": null, "e": 29984, "s": 29956, "text": "After clicking the button: " }, { "code": null, "e": 30097, "s": 29984, "text": "As seen in the output, only the occurrences of ‘Hello’ in the h1 tag section of the code are replaced with ‘Hi’." }, { "code": null, "e": 30107, "s": 30097, "text": "HTML-Misc" }, { "code": null, "e": 30123, "s": 30107, "text": "JavaScript-Misc" }, { "code": null, "e": 30130, "s": 30123, "text": "Picked" }, { "code": null, "e": 30141, "s": 30130, "text": "JavaScript" }, { "code": null, "e": 30158, "s": 30141, "text": "Web Technologies" }, { "code": null, "e": 30185, "s": 30158, "text": "Web technologies Questions" }, { "code": null, "e": 30283, "s": 30185, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30344, "s": 30283, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30384, "s": 30344, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30425, "s": 30384, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30479, "s": 30425, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30527, "s": 30479, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 30569, "s": 30527, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30631, "s": 30569, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30674, "s": 30631, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30707, "s": 30674, "text": "Installation of Node.js on Linux" } ]
C Program to check if a number is divisible by any of its digits
Given a number n, task is to find that any of the digit in the number divides the number completely or not. Like we are given a number 128625 is divisible by 5 which is also present in the number. Input: 53142 Output: yes Explanation: This number is divisible by 1, 2 and 3 which are the digits of the number Input: 223 Output: No Explanation: The number is not divisible by either 2 or 3 The approach used below is as follows − We will start from the unit place and take the unit place’s number. Check whether the number is divisible or not Divide the number with 10 Goto step 1 until the number is 0 Start In function int divisible(long long int n) Step 1-> Declare and initialize temp = n Step 2 -> Loop while n { Set k as n % 10 If temp % k == 0 then, Return 1 Set n = n/ 10 End loop Return 0 In Function int main() Step 1-> Declare and initialize n = 654123 Step 2-> If (divisible(n)) then, Print "Yes” Step 3-> Else Print "No” Live Demo #include <stdio.h> int divisible(long long int n) { long long int temp = n; // check if any of digit divides n while (n) { int k = n % 10; if (temp % k == 0) return 1; n /= 10; } return 0; } int main() { long long int n = 654123; if (divisible(n)) { printf("Yes\n"); } else printf("No\n"); return 0; } If run the above code it will generate the following output − Yes
[ { "code": null, "e": 1259, "s": 1062, "text": "Given a number n, task is to find that any of the digit in the number divides the number completely or not. Like we are given a number 128625 is divisible by 5 which is also present in the number." }, { "code": null, "e": 1451, "s": 1259, "text": "Input: 53142\nOutput: yes\nExplanation: This number is divisible by 1, 2 and 3\nwhich are the digits of the number\nInput: 223\nOutput: No\nExplanation: The number is not divisible by either 2 or 3" }, { "code": null, "e": 1491, "s": 1451, "text": "The approach used below is as follows −" }, { "code": null, "e": 1559, "s": 1491, "text": "We will start from the unit place and take the unit place’s number." }, { "code": null, "e": 1604, "s": 1559, "text": "Check whether the number is divisible or not" }, { "code": null, "e": 1630, "s": 1604, "text": "Divide the number with 10" }, { "code": null, "e": 1664, "s": 1630, "text": "Goto step 1 until the number is 0" }, { "code": null, "e": 2052, "s": 1664, "text": "Start\nIn function int divisible(long long int n)\n Step 1-> Declare and initialize temp = n\n Step 2 -> Loop while n {\n Set k as n % 10\n If temp % k == 0 then,\n Return 1\n Set n = n/ 10\n End loop\n Return 0\nIn Function int main()\n Step 1-> Declare and initialize n = 654123\n Step 2-> If (divisible(n)) then,\n Print \"Yes”\n Step 3-> Else\n Print \"No”" }, { "code": null, "e": 2063, "s": 2052, "text": " Live Demo" }, { "code": null, "e": 2437, "s": 2063, "text": "#include <stdio.h>\nint divisible(long long int n) {\n long long int temp = n;\n // check if any of digit divides n\n while (n) {\n int k = n % 10;\n if (temp % k == 0)\n return 1;\n n /= 10;\n }\n return 0;\n}\nint main() {\n long long int n = 654123;\n if (divisible(n)) {\n printf(\"Yes\\n\");\n }\n else\n printf(\"No\\n\");\n return 0;\n}" }, { "code": null, "e": 2499, "s": 2437, "text": "If run the above code it will generate the following output −" }, { "code": null, "e": 2503, "s": 2499, "text": "Yes" } ]
Program to print all substrings of a given string in C++
In this tutorial, we will be discussing a program to print all the substring of a given string. For this we will be given with a string or an array of characters. Our task is to print all the substrings of that particular string. Live Demo #include<bits/stdc++.h> using namespace std; //printing all the substrings void print_substr(char str[], int n){ for (int len = 1; len <= n; len++){ for (int i = 0; i <= n - len; i++){ int j = i + len - 1; for (int k = i; k <= j; k++) cout << str[k]; cout << endl; } } } int main(){ char str[] = "abca"; print_substr(str, strlen(str)); return 0; } a b c a ab bc ca abc bca abca
[ { "code": null, "e": 1158, "s": 1062, "text": "In this tutorial, we will be discussing a program to print all the substring of a given string." }, { "code": null, "e": 1292, "s": 1158, "text": "For this we will be given with a string or an array of characters. Our task is to print all the substrings of that particular string." }, { "code": null, "e": 1303, "s": 1292, "text": " Live Demo" }, { "code": null, "e": 1714, "s": 1303, "text": "#include<bits/stdc++.h>\nusing namespace std;\n//printing all the substrings\nvoid print_substr(char str[], int n){\n for (int len = 1; len <= n; len++){\n for (int i = 0; i <= n - len; i++){\n int j = i + len - 1;\n for (int k = i; k <= j; k++)\n cout << str[k];\n cout << endl;\n }\n }\n}\nint main(){\n char str[] = \"abca\";\n print_substr(str, strlen(str));\n return 0;\n}" }, { "code": null, "e": 1744, "s": 1714, "text": "a\nb\nc\na\nab\nbc\nca\nabc\nbca\nabca" } ]
Iterative Search for a key ‘x’ in Binary Tree
27 Jun, 2022 Given a Binary Tree and a key to be searched in it, write an iterative method that returns true if key is present in Binary Tree, else false. For example, in the following tree, if the searched key is 3, then function should return true and if the searched key is 12, then function should return false. One thing is sure that we need to traverse complete tree to decide whether key is present or not. We can use any of the following traversals to iteratively search a key in a given binary tree. Iterative Level Order Traversal. Iterative Inorder Traversal Iterative Preorder Traversal Iterative Postorder Traversal Iterative Level Order Traversal. Iterative Inorder Traversal Iterative Preorder Traversal Iterative Postorder Traversal Below is iterative Level Order Traversal based solution to search an item x in binary tree. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. C++ C Java Python3 C# Javascript // Iterative level order traversal// based method to search in Binary Tree#include<bits/stdc++.h> using namespace std; /* A binary tree node has data,left child and right child */class node{ public: int data; node* left; node* right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data){ this->data = data; this->left = NULL; this->right = NULL; }}; // An iterative process to search// an element x in a given binary treebool iterativeSearch(node *root, int x){ // Base Case if (root == NULL) return false; // Create an empty queue for // level order traversal queue<node *> q; // Enqueue Root and initialize height q.push(root); // Queue based level order traversal while (q.empty() == false) { // See if current node is same as x node *node = q.front(); if (node->data == x) return true; // Remove current node and enqueue its children q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); } return false;} // Driver codeint main(){ node* NewRoot=NULL; node *root = new node(2); root->left = new node(7); root->right = new node(5); root->left->right = new node(6); root->left->right->left=new node(1); root->left->right->right=new node(11); root->right->right=new node(9); root->right->right->left=new node(4); iterativeSearch(root, 6)? cout << "Found\n": cout << "Not Found\n"; iterativeSearch(root, 12)? cout << "Found\n": cout << "Not Found\n"; return 0;} // This code is contributed by rathbhupendra // Iterative level order traversal based method to search in Binary Tree#include <iostream>#include <queue>using namespace std; /* A binary tree node has data, left child and right child */struct node{ int data; struct node* left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/struct node* newNode(int data){ struct node* node = new struct node; node->data = data; node->left = node->right = NULL; return(node);} // An iterative process to search an element x in a given binary treebool iterativeSearch(node *root, int x){ // Base Case if (root == NULL) return false; // Create an empty queue for level order traversal queue<node *> q; // Enqueue Root and initialize height q.push(root); // Queue based level order traversal while (q.empty() == false) { // See if current node is same as x node *node = q.front(); if (node->data == x) return true; // Remove current node and enqueue its children q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); } return false;} // Driver programint main(void){ struct node*NewRoot=NULL; struct node *root = newNode(2); root->left = newNode(7); root->right = newNode(5); root->left->right = newNode(6); root->left->right->left=newNode(1); root->left->right->right=newNode(11); root->right->right=newNode(9); root->right->right->left=newNode(4); iterativeSearch(root, 6)? cout << "Found\n": cout << "Not Found\n"; iterativeSearch(root, 12)? cout << "Found\n": cout << "Not Found\n"; return 0;} // Iterative level order traversal// based method to search in Binary Treeimport java.util.*; class GFG{ /* A binary tree node has data,left child and right child */static class node{ int data; node left; node right; /* Constructor that allocates a new node with the given data and null left and right pointers. */ node(int data) { this.data = data; this.left = null; this.right = null; }}; // An iterative process to search// an element x in a given binary treestatic boolean iterativeSearch(node root, int x){ // Base Case if (root == null) return false; // Create an empty queue for // level order traversal Queue<node > q = new LinkedList(); // Enqueue Root and initialize height q.add(root); // Queue based level order traversal while (q.size() > 0) { // See if current node is same as x node node = q.peek(); if (node.data == x) return true; // Remove current node and enqueue its children q.remove(); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); } return false;} // Driver codepublic static void main(String ags[]){ node NewRoot = null; node root = new node(2); root.left = new node(7); root.right = new node(5); root.left.right = new node(6); root.left.right.left = new node(1); root.left.right.right = new node(11); root.right.right = new node(9); root.right.right.left = new node(4); System.out.print((iterativeSearch(root, 6)? "Found\n": "Not Found\n")); System.out.print((iterativeSearch(root, 12)? "Found\n": "Not Found\n"));}} // This code is contributed by Arnab Kundu # Iterative level order traversal based# method to search in Binary Tree # importing Queuefrom queue import Queue # Helper function that allocates a# new node with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = self.right = None # An iterative process to search an# element x in a given binary treedef iterativeSearch(root, x): # Base Case if (root == None): return False # Create an empty queue for level # order traversal q = Queue() # Enqueue Root and initialize height q.put(root) # Queue based level order traversal while (q.empty() == False): # See if current node is same as x node = q.queue[0] if (node.data == x): return True # Remove current node and # enqueue its children q.get() if (node.left != None): q.put(node.left) if (node.right != None): q.put(node.right) return False # Driver Codeif __name__ == '__main__': root = newNode(2) root.left = newNode(7) root.right = newNode(5) root.left.right = newNode(6) root.left.right.left = newNode(1) root.left.right.right = newNode(11) root.right.right = newNode(9) root.right.right.left = newNode(4) if iterativeSearch(root, 6): print("Found") else: print("Not Found") if iterativeSearch(root, 12): print("Found") else: print("Not Found") # This code is contributed by PranchalK // Iterative level order traversal// based method to search in Binary Treeusing System;using System.Collections.Generic; class GFG{ /* A binary tree node has data,left child and right child */public class node{ public int data; public node left; public node right; /* Constructor that allocates a new node with the given data and null left and right pointers. */ public node(int data) { this.data = data; this.left = null; this.right = null; }}; // An iterative process to search// an element x in a given binary treestatic Boolean iterativeSearch(node root, int x){ // Base Case if (root == null) return false; // Create an empty queue for // level order traversal Queue<node > q = new Queue<node>(); // Enqueue Root and initialize height q.Enqueue(root); // Queue based level order traversal while (q.Count > 0) { // See if current node is same as x node node = q.Peek(); if (node.data == x) return true; // Remove current node and // enqueue its children q.Dequeue(); if (node.left != null) q.Enqueue(node.left); if (node.right != null) q.Enqueue(node.right); } return false;} // Driver codepublic static void Main(String []ags){ node root = new node(2); root.left = new node(7); root.right = new node(5); root.left.right = new node(6); root.left.right.left = new node(1); root.left.right.right = new node(11); root.right.right = new node(9); root.right.right.left = new node(4); Console.WriteLine((iterativeSearch(root, 6) ? "Found\n" : "Not Found")); Console.Write((iterativeSearch(root, 12) ? "Found\n" : "Not Found\n"));}} // This code is contributed by Rajput-Ji <script>// Iterative level order traversal// based method to search in Binary Tree /* A binary tree node has data,left child and right child */class node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} // An iterative process to search// an element x in a given binary treefunction iterativeSearch(root,x){ // Base Case if (root == null) return false; // Create an empty queue for // level order traversal let q = []; // Enqueue Root and initialize height q.push(root); // Queue based level order traversal while (q.length > 0) { // See if current node is same as x let node = q[0]; if (node.data == x) return true; // Remove current node and enqueue its children q.shift(); if (node.left != null) q.push(node.left); if (node.right != null) q.push(node.right); } return false;} // Driver codelet NewRoot = null;let root = new node(2);root.left = new node(7);root.right = new node(5);root.left.right = new node(6);root.left.right.left = new node(1);root.left.right.right = new node(11);root.right.right = new node(9);root.right.right.left = new node(4); document.write((iterativeSearch(root, 6)? "Found<br>": "Not Found<br>"));document.write((iterativeSearch(root, 12)? "Found<br>": "Not Found<br>")); // This code is contributed by rag2127</script> Found Not Found Below implementation uses Iterative Preorder Traversal to find x in Binary Tree C++ Java Python3 C# Javascript // An iterative method to search an item in Binary Tree#include <iostream>#include <stack>using namespace std; /* A binary tree node has data, left child and right child */struct node{ int data; struct node* left, *right;}; /* Helper function that allocates a new node with the given data andNULL left and right pointers.*/struct node* newNode(int data){ struct node* node = new struct node; node->data = data; node->left = node->right = NULL; return(node);} // iterative process to search an element x in a given binary treebool iterativeSearch(node *root, int x){ // Base Case if (root == NULL) return false; // Create an empty stack and push root to it stack<node *> nodeStack; nodeStack.push(root); // Do iterative preorder traversal to search x while (nodeStack.empty() == false) { // See the top item from stack and check if it is same as x struct node *node = nodeStack.top(); if (node->data == x) return true; nodeStack.pop(); // Push right and left children of the popped node to stack if (node->right) nodeStack.push(node->right); if (node->left) nodeStack.push(node->left); } return false;} // Driver programint main(void){ struct node*NewRoot=NULL; struct node *root = newNode(2); root->left = newNode(7); root->right = newNode(5); root->left->right = newNode(6); root->left->right->left=newNode(1); root->left->right->right=newNode(11); root->right->right=newNode(9); root->right->right->left=newNode(4); iterativeSearch(root, 6)? cout << "Found\n": cout << "Not Found\n"; iterativeSearch(root, 12)? cout << "Found\n": cout << "Not Found\n"; return 0;} // An iterative method to search an item in Binary Treeimport java.util.*; class GFG{ /* A binary tree node has data,left child and right child */static class node{ int data; node left, right;}; /* Helper function that allocates anew node with the given data andnull left and right pointers.*/static node newNode(int data){ node node = new node(); node.data = data; node.left = node.right = null; return(node);} // iterative process to search// an element x in a given binary treestatic boolean iterativeSearch(node root, int x){ // Base Case if (root == null) return false; // Create an empty stack and push root to it Stack<node> nodeStack = new Stack<node>(); nodeStack.push(root); // Do iterative preorder traversal to search x while (nodeStack.empty() == false) { // See the top item from stack and // check if it is same as x node node = nodeStack.peek(); if (node.data == x) return true; nodeStack.pop(); // Push right and left children // of the popped node to stack if (node.right != null) nodeStack.push(node.right); if (node.left != null) nodeStack.push(node.left); } return false;} // Driver Codepublic static void main(String[] args){ node NewRoot = null; node root = newNode(2); root.left = newNode(7); root.right = newNode(5); root.left.right = newNode(6); root.left.right.left = newNode(1); root.left.right.right = newNode(11); root.right.right = newNode(9); root.right.right.left = newNode(4); if(iterativeSearch(root, 6)) System.out.println("Found"); else System.out.println("Not Found"); if(iterativeSearch(root, 12)) System.out.println("Found"); else System.out.println("Not Found");}} // This code is contributed by 29AjayKumar # An iterative Python3 code to search# an item in Binary Tree ''' A binary tree node has data,left child and right child '''class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # iterative process to search an element x# in a given binary treedef iterativeSearch(root,x): # Base Case if (root == None): return False # Create an empty stack and # append root to it nodeStack = [] nodeStack.append(root) # Do iterative preorder traversal to search x while (len(nodeStack)): # See the top item from stack and # check if it is same as x node = nodeStack[0] if (node.data == x): return True nodeStack.pop(0) # append right and left children # of the popped node to stack if (node.right): nodeStack.append(node.right) if (node.left): nodeStack.append(node.left) return False # Driver Coderoot = newNode(2)root.left = newNode(7)root.right = newNode(5)root.left.right = newNode(6)root.left.right.left = newNode(1)root.left.right.right = newNode(11)root.right.right = newNode(9)root.right.right.left = newNode(4) if iterativeSearch(root, 6): print("Found")else: print("Not Found") if iterativeSearch(root, 12): print("Found")else: print("Not Found") # This code is contributed by SHUBHAMSINGH10 // An iterative method to search an item in Binary Treeusing System;using System.Collections.Generic; class GFG{ /* A binary tree node has data,left child and right child */class node{ public int data; public node left, right;}; /* Helper function that allocates anew node with the given data andnull left and right pointers.*/static node newNode(int data){ node node = new node(); node.data = data; node.left = node.right = null; return(node);} // iterative process to search// an element x in a given binary treestatic bool iterativeSearch(node root, int x){ // Base Case if (root == null) return false; // Create an empty stack and.Push root to it Stack<node> nodeStack = new Stack<node>(); nodeStack.Push(root); // Do iterative preorder traversal to search x while (nodeStack.Count != 0) { // See the top item from stack and // check if it is same as x node node = nodeStack.Peek(); if (node.data == x) return true; nodeStack.Pop(); // Push right and left children // of the.Popped node to stack if (node.right != null) nodeStack.Push(node.right); if (node.left != null) nodeStack.Push(node.left); } return false;} // Driver Codepublic static void Main(String[] args){ node root = newNode(2); root.left = newNode(7); root.right = newNode(5); root.left.right = newNode(6); root.left.right.left = newNode(1); root.left.right.right = newNode(11); root.right.right = newNode(9); root.right.right.left = newNode(4); if(iterativeSearch(root, 6)) Console.WriteLine("Found"); else Console.WriteLine("Not Found"); if(iterativeSearch(root, 12)) Console.WriteLine("Found"); else Console.WriteLine("Not Found");}} // This code is contributed by PrinciRaj1992 <script> // An iterative method to search an item in Binary Tree /* A binary tree node has data,left child and right child */class Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; /* Helper function that allocates anew node with the given data andnull left and right pointers.*/function newNode(data){ var node = new Node(); node.data = data; node.left = node.right = null; return(node);} // iterative process to search// an element x in a given binary treefunction iterativeSearch(root, x){ // Base Case if (root == null) return false; // Create an empty stack and.push root to it var nodeStack = []; nodeStack.push(root); // Do iterative preorder traversal to search x while (nodeStack.length != 0) { // See the top item from stack and // check if it is same as x var node = nodeStack[nodeStack.length - 1]; if (node.data == x) return true; nodeStack.pop(); // push right and left children // of the.Popped node to stack if (node.right != null) nodeStack.push(node.right); if (node.left != null) nodeStack.push(node.left); } return false;} // Driver Codevar root = newNode(2);root.left = newNode(7);root.right = newNode(5);root.left.right = newNode(6);root.left.right.left = newNode(1);root.left.right.right = newNode(11);root.right.right = newNode(9);root.right.right.left = newNode(4);if(iterativeSearch(root, 6)) document.write("Found<br>");else document.write("Not Found<br>");if(iterativeSearch(root, 12)) document.write("Found<br>");else document.write("Not Found<br>"); </script> Found Not Found Similarly, Iterative Inorder and Iterative Postorder traversals can be used. PranchalKatiyar rathbhupendra andrew1234 Rajput-Ji SHUBHAMSINGH10 29AjayKumar princiraj1992 rag2127 rrrtnx hardikkoriintern Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Introduction to Tree Data Structure What is Data Structure: Types, Classifications and Applications Diagonal Traversal of Binary Tree Top 50 Tree Coding Problems for Interviews Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Iterative Preorder Traversal Lowest Common Ancestor in a Binary Search Tree. Write Code to Determine if Two Trees are Identical Boundary Traversal of binary tree
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jun, 2022" }, { "code": null, "e": 194, "s": 52, "text": "Given a Binary Tree and a key to be searched in it, write an iterative method that returns true if key is present in Binary Tree, else false." }, { "code": null, "e": 355, "s": 194, "text": "For example, in the following tree, if the searched key is 3, then function should return true and if the searched key is 12, then function should return false." }, { "code": null, "e": 551, "s": 357, "text": "One thing is sure that we need to traverse complete tree to decide whether key is present or not. We can use any of the following traversals to iteratively search a key in a given binary tree. " }, { "code": null, "e": 671, "s": 551, "text": "Iterative Level Order Traversal. Iterative Inorder Traversal Iterative Preorder Traversal Iterative Postorder Traversal" }, { "code": null, "e": 705, "s": 671, "text": "Iterative Level Order Traversal. " }, { "code": null, "e": 734, "s": 705, "text": "Iterative Inorder Traversal " }, { "code": null, "e": 764, "s": 734, "text": "Iterative Preorder Traversal " }, { "code": null, "e": 794, "s": 764, "text": "Iterative Postorder Traversal" }, { "code": null, "e": 887, "s": 794, "text": "Below is iterative Level Order Traversal based solution to search an item x in binary tree. " }, { "code": null, "e": 896, "s": 887, "text": "Chapters" }, { "code": null, "e": 923, "s": 896, "text": "descriptions off, selected" }, { "code": null, "e": 973, "s": 923, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 996, "s": 973, "text": "captions off, selected" }, { "code": null, "e": 1004, "s": 996, "text": "English" }, { "code": null, "e": 1028, "s": 1004, "text": "This is a modal window." }, { "code": null, "e": 1097, "s": 1028, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1119, "s": 1097, "text": "End of dialog window." }, { "code": null, "e": 1123, "s": 1119, "text": "C++" }, { "code": null, "e": 1125, "s": 1123, "text": "C" }, { "code": null, "e": 1130, "s": 1125, "text": "Java" }, { "code": null, "e": 1138, "s": 1130, "text": "Python3" }, { "code": null, "e": 1141, "s": 1138, "text": "C#" }, { "code": null, "e": 1152, "s": 1141, "text": "Javascript" }, { "code": "// Iterative level order traversal// based method to search in Binary Tree#include<bits/stdc++.h> using namespace std; /* A binary tree node has data,left child and right child */class node{ public: int data; node* left; node* right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data){ this->data = data; this->left = NULL; this->right = NULL; }}; // An iterative process to search// an element x in a given binary treebool iterativeSearch(node *root, int x){ // Base Case if (root == NULL) return false; // Create an empty queue for // level order traversal queue<node *> q; // Enqueue Root and initialize height q.push(root); // Queue based level order traversal while (q.empty() == false) { // See if current node is same as x node *node = q.front(); if (node->data == x) return true; // Remove current node and enqueue its children q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); } return false;} // Driver codeint main(){ node* NewRoot=NULL; node *root = new node(2); root->left = new node(7); root->right = new node(5); root->left->right = new node(6); root->left->right->left=new node(1); root->left->right->right=new node(11); root->right->right=new node(9); root->right->right->left=new node(4); iterativeSearch(root, 6)? cout << \"Found\\n\": cout << \"Not Found\\n\"; iterativeSearch(root, 12)? cout << \"Found\\n\": cout << \"Not Found\\n\"; return 0;} // This code is contributed by rathbhupendra", "e": 2896, "s": 1152, "text": null }, { "code": "// Iterative level order traversal based method to search in Binary Tree#include <iostream>#include <queue>using namespace std; /* A binary tree node has data, left child and right child */struct node{ int data; struct node* left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/struct node* newNode(int data){ struct node* node = new struct node; node->data = data; node->left = node->right = NULL; return(node);} // An iterative process to search an element x in a given binary treebool iterativeSearch(node *root, int x){ // Base Case if (root == NULL) return false; // Create an empty queue for level order traversal queue<node *> q; // Enqueue Root and initialize height q.push(root); // Queue based level order traversal while (q.empty() == false) { // See if current node is same as x node *node = q.front(); if (node->data == x) return true; // Remove current node and enqueue its children q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); } return false;} // Driver programint main(void){ struct node*NewRoot=NULL; struct node *root = newNode(2); root->left = newNode(7); root->right = newNode(5); root->left->right = newNode(6); root->left->right->left=newNode(1); root->left->right->right=newNode(11); root->right->right=newNode(9); root->right->right->left=newNode(4); iterativeSearch(root, 6)? cout << \"Found\\n\": cout << \"Not Found\\n\"; iterativeSearch(root, 12)? cout << \"Found\\n\": cout << \"Not Found\\n\"; return 0;}", "e": 4634, "s": 2896, "text": null }, { "code": "// Iterative level order traversal// based method to search in Binary Treeimport java.util.*; class GFG{ /* A binary tree node has data,left child and right child */static class node{ int data; node left; node right; /* Constructor that allocates a new node with the given data and null left and right pointers. */ node(int data) { this.data = data; this.left = null; this.right = null; }}; // An iterative process to search// an element x in a given binary treestatic boolean iterativeSearch(node root, int x){ // Base Case if (root == null) return false; // Create an empty queue for // level order traversal Queue<node > q = new LinkedList(); // Enqueue Root and initialize height q.add(root); // Queue based level order traversal while (q.size() > 0) { // See if current node is same as x node node = q.peek(); if (node.data == x) return true; // Remove current node and enqueue its children q.remove(); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); } return false;} // Driver codepublic static void main(String ags[]){ node NewRoot = null; node root = new node(2); root.left = new node(7); root.right = new node(5); root.left.right = new node(6); root.left.right.left = new node(1); root.left.right.right = new node(11); root.right.right = new node(9); root.right.right.left = new node(4); System.out.print((iterativeSearch(root, 6)? \"Found\\n\": \"Not Found\\n\")); System.out.print((iterativeSearch(root, 12)? \"Found\\n\": \"Not Found\\n\"));}} // This code is contributed by Arnab Kundu", "e": 6391, "s": 4634, "text": null }, { "code": "# Iterative level order traversal based# method to search in Binary Tree # importing Queuefrom queue import Queue # Helper function that allocates a# new node with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = self.right = None # An iterative process to search an# element x in a given binary treedef iterativeSearch(root, x): # Base Case if (root == None): return False # Create an empty queue for level # order traversal q = Queue() # Enqueue Root and initialize height q.put(root) # Queue based level order traversal while (q.empty() == False): # See if current node is same as x node = q.queue[0] if (node.data == x): return True # Remove current node and # enqueue its children q.get() if (node.left != None): q.put(node.left) if (node.right != None): q.put(node.right) return False # Driver Codeif __name__ == '__main__': root = newNode(2) root.left = newNode(7) root.right = newNode(5) root.left.right = newNode(6) root.left.right.left = newNode(1) root.left.right.right = newNode(11) root.right.right = newNode(9) root.right.right.left = newNode(4) if iterativeSearch(root, 6): print(\"Found\") else: print(\"Not Found\") if iterativeSearch(root, 12): print(\"Found\") else: print(\"Not Found\") # This code is contributed by PranchalK", "e": 7928, "s": 6391, "text": null }, { "code": "// Iterative level order traversal// based method to search in Binary Treeusing System;using System.Collections.Generic; class GFG{ /* A binary tree node has data,left child and right child */public class node{ public int data; public node left; public node right; /* Constructor that allocates a new node with the given data and null left and right pointers. */ public node(int data) { this.data = data; this.left = null; this.right = null; }}; // An iterative process to search// an element x in a given binary treestatic Boolean iterativeSearch(node root, int x){ // Base Case if (root == null) return false; // Create an empty queue for // level order traversal Queue<node > q = new Queue<node>(); // Enqueue Root and initialize height q.Enqueue(root); // Queue based level order traversal while (q.Count > 0) { // See if current node is same as x node node = q.Peek(); if (node.data == x) return true; // Remove current node and // enqueue its children q.Dequeue(); if (node.left != null) q.Enqueue(node.left); if (node.right != null) q.Enqueue(node.right); } return false;} // Driver codepublic static void Main(String []ags){ node root = new node(2); root.left = new node(7); root.right = new node(5); root.left.right = new node(6); root.left.right.left = new node(1); root.left.right.right = new node(11); root.right.right = new node(9); root.right.right.left = new node(4); Console.WriteLine((iterativeSearch(root, 6) ? \"Found\\n\" : \"Not Found\")); Console.Write((iterativeSearch(root, 12) ? \"Found\\n\" : \"Not Found\\n\"));}} // This code is contributed by Rajput-Ji", "e": 9887, "s": 7928, "text": null }, { "code": "<script>// Iterative level order traversal// based method to search in Binary Tree /* A binary tree node has data,left child and right child */class node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} // An iterative process to search// an element x in a given binary treefunction iterativeSearch(root,x){ // Base Case if (root == null) return false; // Create an empty queue for // level order traversal let q = []; // Enqueue Root and initialize height q.push(root); // Queue based level order traversal while (q.length > 0) { // See if current node is same as x let node = q[0]; if (node.data == x) return true; // Remove current node and enqueue its children q.shift(); if (node.left != null) q.push(node.left); if (node.right != null) q.push(node.right); } return false;} // Driver codelet NewRoot = null;let root = new node(2);root.left = new node(7);root.right = new node(5);root.left.right = new node(6);root.left.right.left = new node(1);root.left.right.right = new node(11);root.right.right = new node(9);root.right.right.left = new node(4); document.write((iterativeSearch(root, 6)? \"Found<br>\": \"Not Found<br>\"));document.write((iterativeSearch(root, 12)? \"Found<br>\": \"Not Found<br>\")); // This code is contributed by rag2127</script>", "e": 11371, "s": 9887, "text": null }, { "code": null, "e": 11388, "s": 11371, "text": "Found\nNot Found\n" }, { "code": null, "e": 11469, "s": 11388, "text": "Below implementation uses Iterative Preorder Traversal to find x in Binary Tree " }, { "code": null, "e": 11473, "s": 11469, "text": "C++" }, { "code": null, "e": 11478, "s": 11473, "text": "Java" }, { "code": null, "e": 11486, "s": 11478, "text": "Python3" }, { "code": null, "e": 11489, "s": 11486, "text": "C#" }, { "code": null, "e": 11500, "s": 11489, "text": "Javascript" }, { "code": "// An iterative method to search an item in Binary Tree#include <iostream>#include <stack>using namespace std; /* A binary tree node has data, left child and right child */struct node{ int data; struct node* left, *right;}; /* Helper function that allocates a new node with the given data andNULL left and right pointers.*/struct node* newNode(int data){ struct node* node = new struct node; node->data = data; node->left = node->right = NULL; return(node);} // iterative process to search an element x in a given binary treebool iterativeSearch(node *root, int x){ // Base Case if (root == NULL) return false; // Create an empty stack and push root to it stack<node *> nodeStack; nodeStack.push(root); // Do iterative preorder traversal to search x while (nodeStack.empty() == false) { // See the top item from stack and check if it is same as x struct node *node = nodeStack.top(); if (node->data == x) return true; nodeStack.pop(); // Push right and left children of the popped node to stack if (node->right) nodeStack.push(node->right); if (node->left) nodeStack.push(node->left); } return false;} // Driver programint main(void){ struct node*NewRoot=NULL; struct node *root = newNode(2); root->left = newNode(7); root->right = newNode(5); root->left->right = newNode(6); root->left->right->left=newNode(1); root->left->right->right=newNode(11); root->right->right=newNode(9); root->right->right->left=newNode(4); iterativeSearch(root, 6)? cout << \"Found\\n\": cout << \"Not Found\\n\"; iterativeSearch(root, 12)? cout << \"Found\\n\": cout << \"Not Found\\n\"; return 0;}", "e": 13252, "s": 11500, "text": null }, { "code": "// An iterative method to search an item in Binary Treeimport java.util.*; class GFG{ /* A binary tree node has data,left child and right child */static class node{ int data; node left, right;}; /* Helper function that allocates anew node with the given data andnull left and right pointers.*/static node newNode(int data){ node node = new node(); node.data = data; node.left = node.right = null; return(node);} // iterative process to search// an element x in a given binary treestatic boolean iterativeSearch(node root, int x){ // Base Case if (root == null) return false; // Create an empty stack and push root to it Stack<node> nodeStack = new Stack<node>(); nodeStack.push(root); // Do iterative preorder traversal to search x while (nodeStack.empty() == false) { // See the top item from stack and // check if it is same as x node node = nodeStack.peek(); if (node.data == x) return true; nodeStack.pop(); // Push right and left children // of the popped node to stack if (node.right != null) nodeStack.push(node.right); if (node.left != null) nodeStack.push(node.left); } return false;} // Driver Codepublic static void main(String[] args){ node NewRoot = null; node root = newNode(2); root.left = newNode(7); root.right = newNode(5); root.left.right = newNode(6); root.left.right.left = newNode(1); root.left.right.right = newNode(11); root.right.right = newNode(9); root.right.right.left = newNode(4); if(iterativeSearch(root, 6)) System.out.println(\"Found\"); else System.out.println(\"Not Found\"); if(iterativeSearch(root, 12)) System.out.println(\"Found\"); else System.out.println(\"Not Found\");}} // This code is contributed by 29AjayKumar", "e": 15123, "s": 13252, "text": null }, { "code": "# An iterative Python3 code to search# an item in Binary Tree ''' A binary tree node has data,left child and right child '''class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # iterative process to search an element x# in a given binary treedef iterativeSearch(root,x): # Base Case if (root == None): return False # Create an empty stack and # append root to it nodeStack = [] nodeStack.append(root) # Do iterative preorder traversal to search x while (len(nodeStack)): # See the top item from stack and # check if it is same as x node = nodeStack[0] if (node.data == x): return True nodeStack.pop(0) # append right and left children # of the popped node to stack if (node.right): nodeStack.append(node.right) if (node.left): nodeStack.append(node.left) return False # Driver Coderoot = newNode(2)root.left = newNode(7)root.right = newNode(5)root.left.right = newNode(6)root.left.right.left = newNode(1)root.left.right.right = newNode(11)root.right.right = newNode(9)root.right.right.left = newNode(4) if iterativeSearch(root, 6): print(\"Found\")else: print(\"Not Found\") if iterativeSearch(root, 12): print(\"Found\")else: print(\"Not Found\") # This code is contributed by SHUBHAMSINGH10", "e": 16591, "s": 15123, "text": null }, { "code": "// An iterative method to search an item in Binary Treeusing System;using System.Collections.Generic; class GFG{ /* A binary tree node has data,left child and right child */class node{ public int data; public node left, right;}; /* Helper function that allocates anew node with the given data andnull left and right pointers.*/static node newNode(int data){ node node = new node(); node.data = data; node.left = node.right = null; return(node);} // iterative process to search// an element x in a given binary treestatic bool iterativeSearch(node root, int x){ // Base Case if (root == null) return false; // Create an empty stack and.Push root to it Stack<node> nodeStack = new Stack<node>(); nodeStack.Push(root); // Do iterative preorder traversal to search x while (nodeStack.Count != 0) { // See the top item from stack and // check if it is same as x node node = nodeStack.Peek(); if (node.data == x) return true; nodeStack.Pop(); // Push right and left children // of the.Popped node to stack if (node.right != null) nodeStack.Push(node.right); if (node.left != null) nodeStack.Push(node.left); } return false;} // Driver Codepublic static void Main(String[] args){ node root = newNode(2); root.left = newNode(7); root.right = newNode(5); root.left.right = newNode(6); root.left.right.left = newNode(1); root.left.right.right = newNode(11); root.right.right = newNode(9); root.right.right.left = newNode(4); if(iterativeSearch(root, 6)) Console.WriteLine(\"Found\"); else Console.WriteLine(\"Not Found\"); if(iterativeSearch(root, 12)) Console.WriteLine(\"Found\"); else Console.WriteLine(\"Not Found\");}} // This code is contributed by PrinciRaj1992", "e": 18461, "s": 16591, "text": null }, { "code": "<script> // An iterative method to search an item in Binary Tree /* A binary tree node has data,left child and right child */class Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; /* Helper function that allocates anew node with the given data andnull left and right pointers.*/function newNode(data){ var node = new Node(); node.data = data; node.left = node.right = null; return(node);} // iterative process to search// an element x in a given binary treefunction iterativeSearch(root, x){ // Base Case if (root == null) return false; // Create an empty stack and.push root to it var nodeStack = []; nodeStack.push(root); // Do iterative preorder traversal to search x while (nodeStack.length != 0) { // See the top item from stack and // check if it is same as x var node = nodeStack[nodeStack.length - 1]; if (node.data == x) return true; nodeStack.pop(); // push right and left children // of the.Popped node to stack if (node.right != null) nodeStack.push(node.right); if (node.left != null) nodeStack.push(node.left); } return false;} // Driver Codevar root = newNode(2);root.left = newNode(7);root.right = newNode(5);root.left.right = newNode(6);root.left.right.left = newNode(1);root.left.right.right = newNode(11);root.right.right = newNode(9);root.right.right.left = newNode(4);if(iterativeSearch(root, 6)) document.write(\"Found<br>\");else document.write(\"Not Found<br>\");if(iterativeSearch(root, 12)) document.write(\"Found<br>\");else document.write(\"Not Found<br>\"); </script>", "e": 20152, "s": 18461, "text": null }, { "code": null, "e": 20169, "s": 20152, "text": "Found\nNot Found\n" }, { "code": null, "e": 20246, "s": 20169, "text": "Similarly, Iterative Inorder and Iterative Postorder traversals can be used." }, { "code": null, "e": 20262, "s": 20246, "text": "PranchalKatiyar" }, { "code": null, "e": 20276, "s": 20262, "text": "rathbhupendra" }, { "code": null, "e": 20287, "s": 20276, "text": "andrew1234" }, { "code": null, "e": 20297, "s": 20287, "text": "Rajput-Ji" }, { "code": null, "e": 20312, "s": 20297, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 20324, "s": 20312, "text": "29AjayKumar" }, { "code": null, "e": 20338, "s": 20324, "text": "princiraj1992" }, { "code": null, "e": 20346, "s": 20338, "text": "rag2127" }, { "code": null, "e": 20353, "s": 20346, "text": "rrrtnx" }, { "code": null, "e": 20370, "s": 20353, "text": "hardikkoriintern" }, { "code": null, "e": 20375, "s": 20370, "text": "Tree" }, { "code": null, "e": 20380, "s": 20375, "text": "Tree" }, { "code": null, "e": 20478, "s": 20380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20510, "s": 20478, "text": "Introduction to Data Structures" }, { "code": null, "e": 20546, "s": 20510, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 20610, "s": 20546, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 20644, "s": 20610, "text": "Diagonal Traversal of Binary Tree" }, { "code": null, "e": 20687, "s": 20644, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 20757, "s": 20687, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 20786, "s": 20757, "text": "Iterative Preorder Traversal" }, { "code": null, "e": 20834, "s": 20786, "text": "Lowest Common Ancestor in a Binary Search Tree." }, { "code": null, "e": 20885, "s": 20834, "text": "Write Code to Determine if Two Trees are Identical" } ]
Java program to Find the Square Root of a Number using Binary Search
03 Mar, 2021 Given a non-negative number find the square root of a number using the binary search approach. Examples : Input: x = 16 Output: 4 Explanation: The square root of 16 is 4. Input: x = 5 Output: 2 Explanation: The square root of 5 lies in between 2 and 3 so floor of the square root is 2. Naive Approach: Check the square of every element till n and store the answer till the square is smaller or equal to the n Java // Java program to Find the square root of given numbers// by brute force technique import java.io.*; class GFG { static int cuberoot(int n) { int ans = 0; for (int i = 1; i <= n; ++i) { // checking every number cube if (i * i <= n) { ans = i; } } return ans; } public static void main(String[] args) { // Number int number = 16; // Checking number int cuberoot = cuberoot(number); System.out.println(cuberoot); }} 4 SpaceComplexity: O(1) TimeComplexity: O(n) Efficient Approach (Binary Search): Binary Search used Divide and Conquer approach that makes the complexity is O(logn). Algorithm: Initialize left=0 and right =n Calculate mid=left+(right-left)/2 If mid*mid is equal to the number return the mid. If mid*mid is less than the number store the mid in ans since this can possibly be the answer and increase left=mid+1 and now check in the right half. If mid*mid is more than the number and decrease the right=mid-1 since the expected value is lesser therefore we will now look into the left half part or will be scanning the smaller values. Return the answer Implementation: Java // Java program to Find the square root of given numbers// using Binary search // Importing librariesimport java.io.*;import java.util.*;class GFG { // Function to find cuberoot static int squareeroot(int number) { // Lower bound int left = 1; // Upper bound int right = number; int ans = 0; while (left <= right) { // Finding the mid value int mid = left + (right - left) / 2; // Checking the mid value if (mid * mid == number) { return mid; } // Shift the lower bound if (mid * mid < number) { left = mid + 1; ans = mid; } // Shift the upper bound else { right = mid - 1; } } // Return the ans return ans; } public static void main(String[] args) { int number = 15; System.out.println(squareroot(number)); }} 3 Time Complexity: O(logn) Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Implementing a Linked List in Java using Class Factory method design pattern in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Mar, 2021" }, { "code": null, "e": 123, "s": 28, "text": "Given a non-negative number find the square root of a number using the binary search approach." }, { "code": null, "e": 134, "s": 123, "text": "Examples :" }, { "code": null, "e": 317, "s": 134, "text": "Input: x = 16\nOutput: 4\nExplanation: The square root of 16 is 4.\n\nInput: x = 5\nOutput: 2\nExplanation: The square root of 5 lies in between\n2 and 3 so floor of the square root is 2." }, { "code": null, "e": 333, "s": 317, "text": "Naive Approach:" }, { "code": null, "e": 440, "s": 333, "text": "Check the square of every element till n and store the answer till the square is smaller or equal to the n" }, { "code": null, "e": 445, "s": 440, "text": "Java" }, { "code": "// Java program to Find the square root of given numbers// by brute force technique import java.io.*; class GFG { static int cuberoot(int n) { int ans = 0; for (int i = 1; i <= n; ++i) { // checking every number cube if (i * i <= n) { ans = i; } } return ans; } public static void main(String[] args) { // Number int number = 16; // Checking number int cuberoot = cuberoot(number); System.out.println(cuberoot); }}", "e": 1013, "s": 445, "text": null }, { "code": null, "e": 1016, "s": 1013, "text": "4\n" }, { "code": null, "e": 1038, "s": 1016, "text": "SpaceComplexity: O(1)" }, { "code": null, "e": 1059, "s": 1038, "text": "TimeComplexity: O(n)" }, { "code": null, "e": 1180, "s": 1059, "text": "Efficient Approach (Binary Search): Binary Search used Divide and Conquer approach that makes the complexity is O(logn)." }, { "code": null, "e": 1191, "s": 1180, "text": "Algorithm:" }, { "code": null, "e": 1222, "s": 1191, "text": "Initialize left=0 and right =n" }, { "code": null, "e": 1256, "s": 1222, "text": "Calculate mid=left+(right-left)/2" }, { "code": null, "e": 1306, "s": 1256, "text": "If mid*mid is equal to the number return the mid." }, { "code": null, "e": 1457, "s": 1306, "text": "If mid*mid is less than the number store the mid in ans since this can possibly be the answer and increase left=mid+1 and now check in the right half." }, { "code": null, "e": 1647, "s": 1457, "text": "If mid*mid is more than the number and decrease the right=mid-1 since the expected value is lesser therefore we will now look into the left half part or will be scanning the smaller values." }, { "code": null, "e": 1665, "s": 1647, "text": "Return the answer" }, { "code": null, "e": 1681, "s": 1665, "text": "Implementation:" }, { "code": null, "e": 1686, "s": 1681, "text": "Java" }, { "code": "// Java program to Find the square root of given numbers// using Binary search // Importing librariesimport java.io.*;import java.util.*;class GFG { // Function to find cuberoot static int squareeroot(int number) { // Lower bound int left = 1; // Upper bound int right = number; int ans = 0; while (left <= right) { // Finding the mid value int mid = left + (right - left) / 2; // Checking the mid value if (mid * mid == number) { return mid; } // Shift the lower bound if (mid * mid < number) { left = mid + 1; ans = mid; } // Shift the upper bound else { right = mid - 1; } } // Return the ans return ans; } public static void main(String[] args) { int number = 15; System.out.println(squareroot(number)); }}", "e": 2739, "s": 1686, "text": null }, { "code": null, "e": 2742, "s": 2739, "text": "3\n" }, { "code": null, "e": 2767, "s": 2742, "text": "Time Complexity: O(logn)" }, { "code": null, "e": 2774, "s": 2767, "text": "Picked" }, { "code": null, "e": 2798, "s": 2774, "text": "Technical Scripter 2020" }, { "code": null, "e": 2803, "s": 2798, "text": "Java" }, { "code": null, "e": 2817, "s": 2803, "text": "Java Programs" }, { "code": null, "e": 2836, "s": 2817, "text": "Technical Scripter" }, { "code": null, "e": 2841, "s": 2836, "text": "Java" }, { "code": null, "e": 2939, "s": 2841, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2990, "s": 2939, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3021, "s": 2990, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3040, "s": 3021, "text": "Interfaces in Java" }, { "code": null, "e": 3070, "s": 3040, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3088, "s": 3070, "text": "ArrayList in Java" }, { "code": null, "e": 3116, "s": 3088, "text": "Initializing a List in Java" }, { "code": null, "e": 3142, "s": 3116, "text": "Java Programming Examples" }, { "code": null, "e": 3186, "s": 3142, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 3233, "s": 3186, "text": "Implementing a Linked List in Java using Class" } ]
Gerrit - Installing Git-Review
You can work with Gerrit by installing git-review on different platforms as discussed in this chapter. In Windows, you can install the git-review as listed in the following steps. Step 1 − First install Python for installing git-review. Step 2 − Keep the Python installation in the default directory (like C:\Python27) instead of installing in any other directory. Step 3 − Next, set the environment variables for Python scripts directory using the path as C:\Python27\;C:\Python27\Scripts\; git_review_install Step 4 − With version 2.7, Python will install pip automatically. For older version of Python 2.7, you can install pip as described in this link. Step 5 − Run open Git Bash and install the git-review using the following command. $ pip install git-review In Linux, you can install git-review as described in the following steps − Step 1 Users of Linux platform do not have root access on shared host. Hence, without root access, you can install git-review locally in user directory using the following commands − virtualenv --python=/usr/bin/python2.6 virtualenv virtualenv/bin/pip install git-review==1.21 Step 2 − You can extend the path to the local binaries using two ways − PATH=$PATH:~/virtualenv/bin/ PATH=~/virtualenv/bin/:$PATH Step 3 − Now, use the following command to set up the work with Gerrit. git review -s or ~/virtualenv/bin/git-review -s Step 4 − With root access, git-review can be installed using the following command. sudo apt-get install git-review Step 5 − If there is no apt-get after installing Python, then use the following commands. $ sudo easy_install pip $ sudo pip install git-review==1.21 Step 6 − Run the following command to work with Gerrit. git review -s In Mac, you can install the git-review using the following steps. Step 1 − Install the Homebrew from this link. Step 2 − Next, install the git-review using the following command. brew install git-review
[ { "code": null, "e": 2475, "s": 2372, "text": "You can work with Gerrit by installing git-review on different platforms as discussed in this chapter." }, { "code": null, "e": 2552, "s": 2475, "text": "In Windows, you can install the git-review as listed in the following steps." }, { "code": null, "e": 2609, "s": 2552, "text": "Step 1 − First install Python for installing git-review." }, { "code": null, "e": 2737, "s": 2609, "text": "Step 2 − Keep the Python installation in the default directory (like C:\\Python27) instead of installing in any other directory." }, { "code": null, "e": 2864, "s": 2737, "text": "Step 3 − Next, set the environment variables for Python scripts directory using the path as C:\\Python27\\;C:\\Python27\\Scripts\\;" }, { "code": null, "e": 2884, "s": 2864, "text": "git_review_install\n" }, { "code": null, "e": 3030, "s": 2884, "text": "Step 4 − With version 2.7, Python will install pip automatically. For older version of Python 2.7, you can install pip as described in this link." }, { "code": null, "e": 3113, "s": 3030, "text": "Step 5 − Run open Git Bash and install the git-review using the following command." }, { "code": null, "e": 3139, "s": 3113, "text": "$ pip install git-review\n" }, { "code": null, "e": 3214, "s": 3139, "text": "In Linux, you can install git-review as described in the following steps −" }, { "code": null, "e": 3397, "s": 3214, "text": "Step 1 Users of Linux platform do not have root access on shared host. Hence, without root access, you can install git-review locally in user directory using the following commands −" }, { "code": null, "e": 3492, "s": 3397, "text": "virtualenv --python=/usr/bin/python2.6 virtualenv\nvirtualenv/bin/pip install git-review==1.21\n" }, { "code": null, "e": 3564, "s": 3492, "text": "Step 2 − You can extend the path to the local binaries using two ways −" }, { "code": null, "e": 3623, "s": 3564, "text": "PATH=$PATH:~/virtualenv/bin/\nPATH=~/virtualenv/bin/:$PATH\n" }, { "code": null, "e": 3695, "s": 3623, "text": "Step 3 − Now, use the following command to set up the work with Gerrit." }, { "code": null, "e": 3745, "s": 3695, "text": "git review -s\n or\n~/virtualenv/bin/git-review -s\n" }, { "code": null, "e": 3829, "s": 3745, "text": "Step 4 − With root access, git-review can be installed using the following command." }, { "code": null, "e": 3862, "s": 3829, "text": "sudo apt-get install git-review\n" }, { "code": null, "e": 3952, "s": 3862, "text": "Step 5 − If there is no apt-get after installing Python, then use the following commands." }, { "code": null, "e": 4013, "s": 3952, "text": "$ sudo easy_install pip\n$ sudo pip install git-review==1.21\n" }, { "code": null, "e": 4069, "s": 4013, "text": "Step 6 − Run the following command to work with Gerrit." }, { "code": null, "e": 4084, "s": 4069, "text": "git review -s\n" }, { "code": null, "e": 4150, "s": 4084, "text": "In Mac, you can install the git-review using the following steps." }, { "code": null, "e": 4197, "s": 4150, "text": "Step 1 − Install the Homebrew from this link.\n" }, { "code": null, "e": 4264, "s": 4197, "text": "Step 2 − Next, install the git-review using the following command." } ]
Collections.shuffle() Method in Java with Examples
07 Jul, 2022 shuffle() method of Collections class as the class name suggests is present in utility package known as java.util that shuffles the elements in the list. There are two ways with which we can use to implement in our programs that are as follows: Using the pre-defined source of randomnessUsing the user-provided source of randomness Using the pre-defined source of randomness Using the user-provided source of randomness Way 1: Shuffling a given list using the pre-defined source of randomness. Syntax: public static void shuffle(List mylist) Exception Thrown: UnsupportedOperationException is thrown if the given list or its list-iterator does not support the set operation. Example: Java // Java program to demonstrate // working of shuffle() method// of Collections class // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> mylist = new ArrayList<String>(); // Adding custom input elements to list object mylist.add("code"); mylist.add("quiz"); mylist.add("geeksforgeeks"); mylist.add("quiz"); mylist.add("practice"); mylist.add("qa"); // Printing list before shuffling System.out.println("Original List : \n" + mylist); // Shuffling the list Collections.shuffle(mylist); // Printing list after shuffling System.out.println("\nShuffled List : \n" + mylist); }} Original List : Shuffled List : Way 2: Shuffling a given list using the user-provided source of randomness. Here an additional parameter that is provided which above specified “rndm” is the source of randomness to shuffle the list. Syntax: public static void shuffle(List mylist, Random rndm) Parameters: Here it takes two parameters as listed List Source of randomness Exceptions: UnsupportedOperationException if the specified list or its list-iterator does not support the set operation. Example: Java // Java Program to demonstrate working of shuffle()// with user provided source of randomness // Importing required utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> mylist = new ArrayList<String>(); // Adding custom input elements to above created // object mylist.add("code"); mylist.add("quiz"); mylist.add("geeksforgeeks"); mylist.add("quiz"); mylist.add("practice"); mylist.add("qa"); // Print and display the elements of List on console System.out.println("Original List : \n" + mylist); // Shuffling the given list // using Random() method Collections.shuffle(mylist, new Random()); // Print the updated list on console System.out.println( "\nShuffled List with Random() : \n" + mylist); // Shuffling list by using Random(3) Collections.shuffle(mylist, new Random(3)); // Print the updated list on console System.out.println( "\nShuffled List with Random(3) : \n" + mylist); // Again shuffling list by using Random(3) Collections.shuffle(mylist, new Random(5)); System.out.println( "\nShuffled List with Random(5) : \n" + mylist); }} Original List : Shuffled List with Random() : [quiz, practice, quiz, geeksforgeeks, qa, code] Shuffled List with Random(3) : Shuffled List with Random(5) : [geeksforgeeks, qa, quiz, code, practice, quiz] But do remember certain important points as listed below prior to implementing this method as listed below as follows: Internal working: This method randomly permutes elements randomly in a list. Runtime: It runs in a linear time. Access to elements:It traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element to its “current position”.Thereafter elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive. It traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element to its “current position”. Thereafter elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive. Note: If the provided list does not implement the RandomAccess interface, like LinkedList, and is large, it first copies the list into an array, then shuffles the array copy, and finally copies the array back into the list. This makes sure that the time remains linear. This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. solankimayank sweetyty surinderdawra388 Java-Collections Java-Collections-Class Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 206, "s": 52, "text": "shuffle() method of Collections class as the class name suggests is present in utility package known as java.util that shuffles the elements in the list." }, { "code": null, "e": 297, "s": 206, "text": "There are two ways with which we can use to implement in our programs that are as follows:" }, { "code": null, "e": 384, "s": 297, "text": "Using the pre-defined source of randomnessUsing the user-provided source of randomness" }, { "code": null, "e": 427, "s": 384, "text": "Using the pre-defined source of randomness" }, { "code": null, "e": 472, "s": 427, "text": "Using the user-provided source of randomness" }, { "code": null, "e": 546, "s": 472, "text": "Way 1: Shuffling a given list using the pre-defined source of randomness." }, { "code": null, "e": 554, "s": 546, "text": "Syntax:" }, { "code": null, "e": 594, "s": 554, "text": "public static void shuffle(List mylist)" }, { "code": null, "e": 727, "s": 594, "text": "Exception Thrown: UnsupportedOperationException is thrown if the given list or its list-iterator does not support the set operation." }, { "code": null, "e": 736, "s": 727, "text": "Example:" }, { "code": null, "e": 741, "s": 736, "text": "Java" }, { "code": "// Java program to demonstrate // working of shuffle() method// of Collections class // Importing utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> mylist = new ArrayList<String>(); // Adding custom input elements to list object mylist.add(\"code\"); mylist.add(\"quiz\"); mylist.add(\"geeksforgeeks\"); mylist.add(\"quiz\"); mylist.add(\"practice\"); mylist.add(\"qa\"); // Printing list before shuffling System.out.println(\"Original List : \\n\" + mylist); // Shuffling the list Collections.shuffle(mylist); // Printing list after shuffling System.out.println(\"\\nShuffled List : \\n\" + mylist); }}", "e": 1601, "s": 741, "text": null }, { "code": null, "e": 1641, "s": 1604, "text": "Original List : \n\n\nShuffled List : \n" }, { "code": null, "e": 1721, "s": 1643, "text": "Way 2: Shuffling a given list using the user-provided source of randomness. " }, { "code": null, "e": 1846, "s": 1721, "text": "Here an additional parameter that is provided which above specified “rndm” is the source of randomness to shuffle the list. " }, { "code": null, "e": 1854, "s": 1846, "text": "Syntax:" }, { "code": null, "e": 1907, "s": 1854, "text": "public static void shuffle(List mylist, Random rndm)" }, { "code": null, "e": 1959, "s": 1907, "text": "Parameters: Here it takes two parameters as listed " }, { "code": null, "e": 1964, "s": 1959, "text": "List" }, { "code": null, "e": 1987, "s": 1964, "text": "Source of randomness " }, { "code": null, "e": 2109, "s": 1987, "text": "Exceptions: UnsupportedOperationException if the specified list or its list-iterator does not support the set operation." }, { "code": null, "e": 2118, "s": 2109, "text": "Example:" }, { "code": null, "e": 2123, "s": 2118, "text": "Java" }, { "code": "// Java Program to demonstrate working of shuffle()// with user provided source of randomness // Importing required utility classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> mylist = new ArrayList<String>(); // Adding custom input elements to above created // object mylist.add(\"code\"); mylist.add(\"quiz\"); mylist.add(\"geeksforgeeks\"); mylist.add(\"quiz\"); mylist.add(\"practice\"); mylist.add(\"qa\"); // Print and display the elements of List on console System.out.println(\"Original List : \\n\" + mylist); // Shuffling the given list // using Random() method Collections.shuffle(mylist, new Random()); // Print the updated list on console System.out.println( \"\\nShuffled List with Random() : \\n\" + mylist); // Shuffling list by using Random(3) Collections.shuffle(mylist, new Random(3)); // Print the updated list on console System.out.println( \"\\nShuffled List with Random(3) : \\n\" + mylist); // Again shuffling list by using Random(3) Collections.shuffle(mylist, new Random(5)); System.out.println( \"\\nShuffled List with Random(5) : \\n\" + mylist); }}", "e": 3543, "s": 2123, "text": null }, { "code": null, "e": 3756, "s": 3543, "text": "Original List : \n\n\nShuffled List with Random() : \n[quiz, practice, quiz, geeksforgeeks, qa, code]\n\nShuffled List with Random(3) : \n\n\nShuffled List with Random(5) : \n[geeksforgeeks, qa, quiz, code, practice, quiz]" }, { "code": null, "e": 3877, "s": 3758, "text": "But do remember certain important points as listed below prior to implementing this method as listed below as follows:" }, { "code": null, "e": 3954, "s": 3877, "text": "Internal working: This method randomly permutes elements randomly in a list." }, { "code": null, "e": 3989, "s": 3954, "text": "Runtime: It runs in a linear time." }, { "code": null, "e": 4295, "s": 3989, "text": "Access to elements:It traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element to its “current position”.Thereafter elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive." }, { "code": null, "e": 4443, "s": 4295, "text": "It traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element to its “current position”." }, { "code": null, "e": 4583, "s": 4443, "text": "Thereafter elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive." }, { "code": null, "e": 4853, "s": 4583, "text": "Note: If the provided list does not implement the RandomAccess interface, like LinkedList, and is large, it first copies the list into an array, then shuffles the array copy, and finally copies the array back into the list. This makes sure that the time remains linear." }, { "code": null, "e": 5246, "s": 4855, "text": "This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5260, "s": 5246, "text": "solankimayank" }, { "code": null, "e": 5269, "s": 5260, "text": "sweetyty" }, { "code": null, "e": 5286, "s": 5269, "text": "surinderdawra388" }, { "code": null, "e": 5303, "s": 5286, "text": "Java-Collections" }, { "code": null, "e": 5326, "s": 5303, "text": "Java-Collections-Class" }, { "code": null, "e": 5341, "s": 5326, "text": "Java-Functions" }, { "code": null, "e": 5346, "s": 5341, "text": "Java" }, { "code": null, "e": 5351, "s": 5346, "text": "Java" }, { "code": null, "e": 5368, "s": 5351, "text": "Java-Collections" } ]
Translation of objects in computer graphics
19 Jun, 2022 In computer graphics, we have seen how to draw some basic figures like line and circles. In this post we will discuss on basics of an important operation in computer graphics as well as 2-D geometry, which is transformation. In computer graphics, transformation of the coordinates consists of three major processes: Translation Rotation Scaling In this post we will discuss about translation only. What is translation? A translation process moves every point a constant distance in a specified direction. It can be described as a rigid motion. A translation can also be interpreted as the addition of a constant vector to every point, or as shifting the origin of the coordinate system. Suppose, If point (X, Y) is to be translated by amount Dx and Dy to a new location (X’, Y’) then new coordinates can be obtained by adding Dx to X and Dy to Y as: X' = Dx + X Y' = Dy + Y or P' = T + P where P' = (X', Y'), T = (Dx, Dy ), P = (X, Y) Here, P(X, Y) is the original point. T(Dx, Dy) is the translation factor, i.e. the amount by which the point will be translated. P'(X’, Y’) is the coordinates of point P after translation. Examples: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Input : P[] = {5, 6}, T = {1, 1} Output : P'[] = {6, 7} Input : P[] = {8, 6}, T = {-1, -1} Output : P'[] = {7, 5} Whenever we perform translation of any object we simply translate its each and every point. Some of basic objects along with their translation can be drawn as: Point Translation P(X, Y) : Here we only translate the x and y coordinates of given point as per given translation factor dx and dy respectively. Below is the C++ program to translate a point: Point Translation P(X, Y) : Here we only translate the x and y coordinates of given point as per given translation factor dx and dy respectively. Below is the C++ program to translate a point: CPP // C++ program for translation// of a single coordinate#include<bits/stdc++.h>#include<graphics.h> using namespace std; // function to translate pointvoid translatePoint ( int P[], int T[]){ /* init graph and putpixel are used for representing coordinates through graphical functions */ int gd = DETECT, gm, errorcode; initgraph (&gd, &gm, "c:\\tc\\bgi"); cout<<"Original Coordinates :"<<P[0]<<","<<P[1]; putpixel (P[0], P[1], 1); // calculating translated coordinates P[0] = P[0] + T[0]; P[1] = P[1] + T[1]; cout<<"\nTranslated Coordinates :"<< P[0]<<","<< P[1]; // Draw new coordinates putpixel (P[0], P[1], 3); closegraph();} // driver programint main(){ int P[2] = {5, 8}; // coordinates of point int T[] = {2, 1}; // translation factor translatePoint (P, T); return 0;} Output: Output: Original Coordinates : 5, 8 Translated Coordinates : 7, 9 Line Translation: The idea to translate a line is to translate both of the end points of the line by the given translation factor(dx, dy) and then draw a new line with inbuilt graphics function. Below is the C++ implementation of above idea: Line Translation: The idea to translate a line is to translate both of the end points of the line by the given translation factor(dx, dy) and then draw a new line with inbuilt graphics function. Below is the C++ implementation of above idea: CPP // cpp program for translation// of a single line#include<bits/stdc++.h>#include<graphics.h> using namespace std; // function to translate linevoid translateLine ( int P[][2], int T[]){ /* init graph and line() are used for representing line through graphical functions */ int gd = DETECT, gm, errorcode; initgraph (&gd, &gm, "c:\\tc\\bgi"); // drawing original line using graphics functions setcolor (2); line(P[0][0], P[0][1], P[1][0], P[1][1]); // calculating translated coordinates P[0][0] = P[0][0] + T[0]; P[0][1] = P[0][1] + T[1]; P[1][0] = P[1][0] + T[0]; P[1][1] = P[1][1] + T[1]; // drawing translated line using graphics functions setcolor(3); line(P[0][0], P[0][1], P[1][0], P[1][1]); closegraph();} // driver programint main(){ int P[2][2] = {5, 8, 12, 18}; // coordinates of point int T[] = {2, 1}; // translation factor translateLine (P, T); return 0;} Output: Output: Rectangle Translation : Here we translate the x and y coordinates of both given points A(top left ) and B(bottom right) as per given translation factor dx and dy respectively and then draw a rectangle with inbuilt graphics function Rectangle Translation : Here we translate the x and y coordinates of both given points A(top left ) and B(bottom right) as per given translation factor dx and dy respectively and then draw a rectangle with inbuilt graphics function CPP // C++ program for translation// of a rectangle#include<bits/stdc++.h>#include<graphics.h>using namespace std; // function to translate rectanglevoid translateRectangle ( int P[][2], int T[]){ /* init graph and rectangle() are used for representing rectangle through graphical functions */ int gd = DETECT, gm, errorcode; initgraph (&gd, &gm, "c:\\tc\\bgi"); setcolor (2); // rectangle (Xmin, Ymin, Xmax, Ymax) // original rectangle rectangle (P[0][0], P[0][1], P[1][0], P[1][1]); // calculating translated coordinates P[0][0] = P[0][0] + T[0]; P[0][1] = P[0][1] + T[1]; P[1][0] = P[1][0] + T[0]; P[1][1] = P[1][1] + T[1]; // translated rectangle (Xmin, Ymin, Xmax, Ymax) // setcolor(3); rectangle (P[0][0], P[0][1], P[1][0], P[1][1]); // closegraph();} // driver programint main(){ // Xmin, Ymin, Xmax, Ymax as rectangle // coordinates of top left and bottom right points int P[2][2] = {5, 8, 12, 18}; int T[] = {2, 1}; // translation factor translateRectangle (P, T); return 0;} Output: Output: References : http://math.hws.edu/graphicsbook/.This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. arorakashish0911 computer-graphics Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Jun, 2022" }, { "code": null, "e": 370, "s": 52, "text": "In computer graphics, we have seen how to draw some basic figures like line and circles. In this post we will discuss on basics of an important operation in computer graphics as well as 2-D geometry, which is transformation. In computer graphics, transformation of the coordinates consists of three major processes: " }, { "code": null, "e": 382, "s": 370, "text": "Translation" }, { "code": null, "e": 391, "s": 382, "text": "Rotation" }, { "code": null, "e": 399, "s": 391, "text": "Scaling" }, { "code": null, "e": 454, "s": 399, "text": "In this post we will discuss about translation only. " }, { "code": null, "e": 475, "s": 454, "text": "What is translation?" }, { "code": null, "e": 908, "s": 475, "text": "A translation process moves every point a constant distance in a specified direction. It can be described as a rigid motion. A translation can also be interpreted as the addition of a constant vector to every point, or as shifting the origin of the coordinate system. Suppose, If point (X, Y) is to be translated by amount Dx and Dy to a new location (X’, Y’) then new coordinates can be obtained by adding Dx to X and Dy to Y as: " }, { "code": null, "e": 995, "s": 908, "text": "X' = Dx + X\nY' = Dy + Y\n\nor P' = T + P where\n\nP' = (X', Y'),\nT = (Dx, Dy ),\nP = (X, Y)" }, { "code": null, "e": 1196, "s": 995, "text": "Here, P(X, Y) is the original point. T(Dx, Dy) is the translation factor, i.e. the amount by which the point will be translated. P'(X’, Y’) is the coordinates of point P after translation. Examples: " }, { "code": null, "e": 1205, "s": 1196, "text": "Chapters" }, { "code": null, "e": 1232, "s": 1205, "text": "descriptions off, selected" }, { "code": null, "e": 1282, "s": 1232, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1305, "s": 1282, "text": "captions off, selected" }, { "code": null, "e": 1313, "s": 1305, "text": "English" }, { "code": null, "e": 1337, "s": 1313, "text": "This is a modal window." }, { "code": null, "e": 1406, "s": 1337, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1428, "s": 1406, "text": "End of dialog window." }, { "code": null, "e": 1543, "s": 1428, "text": "Input : P[] = {5, 6}, T = {1, 1}\nOutput : P'[] = {6, 7}\n\nInput : P[] = {8, 6}, T = {-1, -1}\nOutput : P'[] = {7, 5}" }, { "code": null, "e": 1705, "s": 1543, "text": "Whenever we perform translation of any object we simply translate its each and every point. Some of basic objects along with their translation can be drawn as: " }, { "code": null, "e": 1900, "s": 1705, "text": "Point Translation P(X, Y) : Here we only translate the x and y coordinates of given point as per given translation factor dx and dy respectively. Below is the C++ program to translate a point: " }, { "code": null, "e": 2095, "s": 1900, "text": "Point Translation P(X, Y) : Here we only translate the x and y coordinates of given point as per given translation factor dx and dy respectively. Below is the C++ program to translate a point: " }, { "code": null, "e": 2099, "s": 2095, "text": "CPP" }, { "code": "// C++ program for translation// of a single coordinate#include<bits/stdc++.h>#include<graphics.h> using namespace std; // function to translate pointvoid translatePoint ( int P[], int T[]){ /* init graph and putpixel are used for representing coordinates through graphical functions */ int gd = DETECT, gm, errorcode; initgraph (&gd, &gm, \"c:\\\\tc\\\\bgi\"); cout<<\"Original Coordinates :\"<<P[0]<<\",\"<<P[1]; putpixel (P[0], P[1], 1); // calculating translated coordinates P[0] = P[0] + T[0]; P[1] = P[1] + T[1]; cout<<\"\\nTranslated Coordinates :\"<< P[0]<<\",\"<< P[1]; // Draw new coordinates putpixel (P[0], P[1], 3); closegraph();} // driver programint main(){ int P[2] = {5, 8}; // coordinates of point int T[] = {2, 1}; // translation factor translatePoint (P, T); return 0;} ", "e": 2962, "s": 2099, "text": null }, { "code": null, "e": 2972, "s": 2962, "text": "Output: " }, { "code": null, "e": 2982, "s": 2972, "text": "Output: " }, { "code": null, "e": 3040, "s": 2982, "text": "Original Coordinates : 5, 8\nTranslated Coordinates : 7, 9" }, { "code": null, "e": 3285, "s": 3040, "text": " Line Translation: The idea to translate a line is to translate both of the end points of the line by the given translation factor(dx, dy) and then draw a new line with inbuilt graphics function. Below is the C++ implementation of above idea: " }, { "code": null, "e": 3531, "s": 3287, "text": "Line Translation: The idea to translate a line is to translate both of the end points of the line by the given translation factor(dx, dy) and then draw a new line with inbuilt graphics function. Below is the C++ implementation of above idea: " }, { "code": null, "e": 3535, "s": 3531, "text": "CPP" }, { "code": "// cpp program for translation// of a single line#include<bits/stdc++.h>#include<graphics.h> using namespace std; // function to translate linevoid translateLine ( int P[][2], int T[]){ /* init graph and line() are used for representing line through graphical functions */ int gd = DETECT, gm, errorcode; initgraph (&gd, &gm, \"c:\\\\tc\\\\bgi\"); // drawing original line using graphics functions setcolor (2); line(P[0][0], P[0][1], P[1][0], P[1][1]); // calculating translated coordinates P[0][0] = P[0][0] + T[0]; P[0][1] = P[0][1] + T[1]; P[1][0] = P[1][0] + T[0]; P[1][1] = P[1][1] + T[1]; // drawing translated line using graphics functions setcolor(3); line(P[0][0], P[0][1], P[1][0], P[1][1]); closegraph();} // driver programint main(){ int P[2][2] = {5, 8, 12, 18}; // coordinates of point int T[] = {2, 1}; // translation factor translateLine (P, T); return 0;} ", "e": 4492, "s": 3535, "text": null }, { "code": null, "e": 4502, "s": 4492, "text": "Output: " }, { "code": null, "e": 4512, "s": 4502, "text": "Output: " }, { "code": null, "e": 4747, "s": 4512, "text": " Rectangle Translation : Here we translate the x and y coordinates of both given points A(top left ) and B(bottom right) as per given translation factor dx and dy respectively and then draw a rectangle with inbuilt graphics function " }, { "code": null, "e": 4983, "s": 4749, "text": "Rectangle Translation : Here we translate the x and y coordinates of both given points A(top left ) and B(bottom right) as per given translation factor dx and dy respectively and then draw a rectangle with inbuilt graphics function " }, { "code": null, "e": 4987, "s": 4983, "text": "CPP" }, { "code": "// C++ program for translation// of a rectangle#include<bits/stdc++.h>#include<graphics.h>using namespace std; // function to translate rectanglevoid translateRectangle ( int P[][2], int T[]){ /* init graph and rectangle() are used for representing rectangle through graphical functions */ int gd = DETECT, gm, errorcode; initgraph (&gd, &gm, \"c:\\\\tc\\\\bgi\"); setcolor (2); // rectangle (Xmin, Ymin, Xmax, Ymax) // original rectangle rectangle (P[0][0], P[0][1], P[1][0], P[1][1]); // calculating translated coordinates P[0][0] = P[0][0] + T[0]; P[0][1] = P[0][1] + T[1]; P[1][0] = P[1][0] + T[0]; P[1][1] = P[1][1] + T[1]; // translated rectangle (Xmin, Ymin, Xmax, Ymax) // setcolor(3); rectangle (P[0][0], P[0][1], P[1][0], P[1][1]); // closegraph();} // driver programint main(){ // Xmin, Ymin, Xmax, Ymax as rectangle // coordinates of top left and bottom right points int P[2][2] = {5, 8, 12, 18}; int T[] = {2, 1}; // translation factor translateRectangle (P, T); return 0;} ", "e": 6046, "s": 4987, "text": null }, { "code": null, "e": 6056, "s": 6046, "text": "Output: " }, { "code": null, "e": 6066, "s": 6056, "text": "Output: " }, { "code": null, "e": 6553, "s": 6070, "text": "References : http://math.hws.edu/graphicsbook/.This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 6570, "s": 6553, "text": "arorakashish0911" }, { "code": null, "e": 6588, "s": 6570, "text": "computer-graphics" }, { "code": null, "e": 6599, "s": 6588, "text": "Algorithms" }, { "code": null, "e": 6610, "s": 6599, "text": "Algorithms" } ]
Bash Scripting – Concatenate String
04 Jan, 2022 In this article, we will see the concatenation of string in bash scripting. Joining two or more strings together is called string concatenation. Bash does not have any built-in function to perform the concatenation on string data or variables. There are various methods using which we can perform the concatenation of strings in bash, those are : This is the easiest method to perform concatenation. Example: Let’s take two strings (i.e., “welcome” and “to geeksforgeeks”), and we want to return a new string which is the combination of the given two strings. Code: #!/bin/bash # Script to Concatenate Strings # Declaration of first String str1="Welcome" # Declaration of Second String str2=" to GeeksforGeeks." # Combining first and second string str3="$str1$str2" # print the concatenated string echo $str3 Output: Welcome to GeeksforGeeks. It is also one of the easy methods to perform concatenation. This method uses variables inside the string, which is defined with double quotes. The advantage of using this method is we can concatenate the string variable at any position of the string data. Example: Let’s concatenate two strings (i.e., “to” and “Welcome geeksforgeeks”) in such a way that it returns the result as “Welcome to GeeksforGeeks”. Code: #!/bin/bash # Concatenate Strings # Declaration of String Variable str="to" # Add the variable within the string echo "Welcome $str GeeksforGeeks." Output: Welcome to GeeksforGeeks. printf is a function in bash that is used to print and concatenate the strings. Syntax: printf -v new_str “$str string_to_concatenate.” This command will concatenate the data present inside the double quotes and store the new string into the new_str variable. In this method also we can concatenate the string variable at any position. Example: Let’s concatenate two strings (i.e., “to” and “Welcome geeksforgeeks”) in such a way that it returns the result as “Welcome to GeeksforGeeks”. Code: #!/bin/bash str="to" printf -v new_str "Welcome $str GeeksforGeeks." echo $new_str Output: Welcome to GeeksforGeeks. In this method, concatenation is performed with a literal string by using curly braces{}. It should be used in such a way that the variable does not mix up with the literal string. Let’s concatenate two strings (i.e., “to” and “Welcome geeksforgeeks”) in such a way that it returns the result as “Welcome to GeeksforGeeks”. Code: #!/bin/bash str="to" # concatenation of strings new="Welcome ${str} GeeksforGeeks." echo "$new" Output: Welcome to GeeksforGeeks. This method is used when we have to concatenate strings present inside the list. Syntax: newstr=" " for value in list; do # Combining the list values using append operator Newstr+="$value " done Example Code: lang="" # for loop for reading the list for value in 'Welcome ''to ''GeeksforGeeks''!!'; do # Combining the list values using append operator lang+="$value " done # Printing the combined values echo "$lang" Output: Welcome to GeeksforGeeks!! If we want to concatenate strings separated by certain characters, we use this method. This is similar to writing variables side by side. In this method, we write variables side by side with the character in between. Example: Let’s concatenate strings(‘Apple’, ‘Mango’, ‘Guava’, ‘Orange’) separated by comma(,) character. Code: str1="Apple" str2="Mango" str3="Guava" str4="Orange" # concatenate string using ',' echo "$str1,$str2,$str3,$str4" Output: Apple,Mango,Guava,Orange Bash-Script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jan, 2022" }, { "code": null, "e": 104, "s": 28, "text": "In this article, we will see the concatenation of string in bash scripting." }, { "code": null, "e": 375, "s": 104, "text": "Joining two or more strings together is called string concatenation. Bash does not have any built-in function to perform the concatenation on string data or variables. There are various methods using which we can perform the concatenation of strings in bash, those are :" }, { "code": null, "e": 428, "s": 375, "text": "This is the easiest method to perform concatenation." }, { "code": null, "e": 589, "s": 428, "text": "Example: Let’s take two strings (i.e., “welcome” and “to geeksforgeeks”), and we want to return a new string which is the combination of the given two strings. " }, { "code": null, "e": 595, "s": 589, "text": "Code:" }, { "code": null, "e": 868, "s": 595, "text": "#!/bin/bash \n# Script to Concatenate Strings \n \n# Declaration of first String \nstr1=\"Welcome\" \n \n# Declaration of Second String \nstr2=\" to GeeksforGeeks.\" \n \n# Combining first and second string \nstr3=\"$str1$str2\" \n \n# print the concatenated string \necho $str3 " }, { "code": null, "e": 876, "s": 868, "text": "Output:" }, { "code": null, "e": 902, "s": 876, "text": "Welcome to GeeksforGeeks." }, { "code": null, "e": 1159, "s": 902, "text": "It is also one of the easy methods to perform concatenation. This method uses variables inside the string, which is defined with double quotes. The advantage of using this method is we can concatenate the string variable at any position of the string data." }, { "code": null, "e": 1311, "s": 1159, "text": "Example: Let’s concatenate two strings (i.e., “to” and “Welcome geeksforgeeks”) in such a way that it returns the result as “Welcome to GeeksforGeeks”." }, { "code": null, "e": 1317, "s": 1311, "text": "Code:" }, { "code": null, "e": 1481, "s": 1317, "text": "#!/bin/bash \n# Concatenate Strings \n \n# Declaration of String Variable \nstr=\"to\" \n \n# Add the variable within the string \necho \"Welcome $str GeeksforGeeks.\" " }, { "code": null, "e": 1489, "s": 1481, "text": "Output:" }, { "code": null, "e": 1515, "s": 1489, "text": "Welcome to GeeksforGeeks." }, { "code": null, "e": 1595, "s": 1515, "text": "printf is a function in bash that is used to print and concatenate the strings." }, { "code": null, "e": 1603, "s": 1595, "text": "Syntax:" }, { "code": null, "e": 1652, "s": 1603, "text": "printf -v new_str “$str string_to_concatenate.” " }, { "code": null, "e": 1852, "s": 1652, "text": "This command will concatenate the data present inside the double quotes and store the new string into the new_str variable. In this method also we can concatenate the string variable at any position." }, { "code": null, "e": 2004, "s": 1852, "text": "Example: Let’s concatenate two strings (i.e., “to” and “Welcome geeksforgeeks”) in such a way that it returns the result as “Welcome to GeeksforGeeks”." }, { "code": null, "e": 2010, "s": 2004, "text": "Code:" }, { "code": null, "e": 2103, "s": 2010, "text": "#!/bin/bash \n \nstr=\"to\" \nprintf -v new_str \"Welcome $str GeeksforGeeks.\" \necho $new_str " }, { "code": null, "e": 2111, "s": 2103, "text": "Output:" }, { "code": null, "e": 2137, "s": 2111, "text": "Welcome to GeeksforGeeks." }, { "code": null, "e": 2318, "s": 2137, "text": "In this method, concatenation is performed with a literal string by using curly braces{}. It should be used in such a way that the variable does not mix up with the literal string." }, { "code": null, "e": 2461, "s": 2318, "text": "Let’s concatenate two strings (i.e., “to” and “Welcome geeksforgeeks”) in such a way that it returns the result as “Welcome to GeeksforGeeks”." }, { "code": null, "e": 2467, "s": 2461, "text": "Code:" }, { "code": null, "e": 2574, "s": 2467, "text": "#!/bin/bash \n \nstr=\"to\" \n\n# concatenation of strings \nnew=\"Welcome ${str} GeeksforGeeks.\" \necho \"$new\"" }, { "code": null, "e": 2582, "s": 2574, "text": "Output:" }, { "code": null, "e": 2608, "s": 2582, "text": "Welcome to GeeksforGeeks." }, { "code": null, "e": 2690, "s": 2608, "text": "This method is used when we have to concatenate strings present inside the list. " }, { "code": null, "e": 2698, "s": 2690, "text": "Syntax:" }, { "code": null, "e": 2816, "s": 2698, "text": "newstr=\" \"\nfor value in list; \n\ndo \n\n# Combining the list values using append operator \nNewstr+=\"$value \" \ndone " }, { "code": null, "e": 2824, "s": 2816, "text": "Example" }, { "code": null, "e": 2830, "s": 2824, "text": "Code:" }, { "code": null, "e": 3061, "s": 2830, "text": "lang=\"\" \n\n# for loop for reading the list \nfor value in 'Welcome ''to ''GeeksforGeeks''!!'; \n\ndo \n\n# Combining the list values using append operator \nlang+=\"$value \" \ndone \n\n# Printing the combined values \necho \"$lang\" " }, { "code": null, "e": 3069, "s": 3061, "text": "Output:" }, { "code": null, "e": 3097, "s": 3069, "text": "Welcome to GeeksforGeeks!! " }, { "code": null, "e": 3236, "s": 3097, "text": "If we want to concatenate strings separated by certain characters, we use this method. This is similar to writing variables side by side. " }, { "code": null, "e": 3315, "s": 3236, "text": "In this method, we write variables side by side with the character in between." }, { "code": null, "e": 3420, "s": 3315, "text": "Example: Let’s concatenate strings(‘Apple’, ‘Mango’, ‘Guava’, ‘Orange’) separated by comma(,) character." }, { "code": null, "e": 3426, "s": 3420, "text": "Code:" }, { "code": null, "e": 3554, "s": 3426, "text": "str1=\"Apple\" \nstr2=\"Mango\" \nstr3=\"Guava\" \nstr4=\"Orange\" \n\n# concatenate string using ',' \necho \"$str1,$str2,$str3,$str4\" " }, { "code": null, "e": 3562, "s": 3554, "text": "Output:" }, { "code": null, "e": 3587, "s": 3562, "text": "Apple,Mango,Guava,Orange" }, { "code": null, "e": 3599, "s": 3587, "text": "Bash-Script" }, { "code": null, "e": 3606, "s": 3599, "text": "Picked" }, { "code": null, "e": 3617, "s": 3606, "text": "Linux-Unix" } ]
Tpot AutoML
09 Mar, 2021 Tpot is an automated machine learning package in python that uses genetic programming concepts to optimize the machine learning pipeline. It automates the most tedious part of machine learning by intelligently exploring thousands of the possible to find the best possible parameter that suits your data. Tpot is Tpot is built upon the scikit-learn, so its code looks similar to the scikit-learn. Parts of ML pipeline automated by Tpot Tpot uses genetic programming to generate the optimized search space, they are inspired by Darwin’s idea of natural selection, the genetic programming uses the following properties: Selection: In this stage, the fitness function is evaluated at each of the individuals and normalized their values, so that each of them has values between 0 and 1 and their sum is 1. After that, we decide a random number R b/w 0 and 1. Now, we keep those individuals whose value of fitness function is greater or equal to R. Crossover: Now, we can select the fittest individuals from above and perform crossover between them to generate a new population. Mutation: Mutate the individuals generated by crossover and perform some random modifications and repeat it for few steps or until we get the best population Below are some important functions of Tpot: TpoT Pipeline TpotClassifier: module to perform automated learning for the supervised classification task. Below are some important arguments it takes:generations: number of iterations to run pipeline process (default: 100).population_size: number of individuals to retain genetic programming population every generation ( default 100).offspring_size: number of offspring to generate in each genetic programming iteration. (default 100).mutation_rate: mutation rate b/w [0,1] (default 0.9)crossover_rate: crossover rate b/w [0,1] (default 0.1) {mutation rate + crossover_rate <= 1}.scoring: metrics for evaluating the quality of the pipeline. Here scoring takes parameters such as Accuracy, F1 score etccv: cross-validation method, if the given value is Integer, then it will be K in K-Fold cross-validation.n_job: number of processes that can be run in parallel (default 1).max_time_mins: maximum time Tpot allowed optimizing the pipeline (default: None).max_eval_time_mins: How many minutes TPOT has to evaluate a single pipeline(default: None).verbosity: How much information TPOT displays while it’s running. {0: nothing, 1: minimal information, 2: more information and progress bar, 3: everything} (default: 0) generations: number of iterations to run pipeline process (default: 100). population_size: number of individuals to retain genetic programming population every generation ( default 100). offspring_size: number of offspring to generate in each genetic programming iteration. (default 100). mutation_rate: mutation rate b/w [0,1] (default 0.9) crossover_rate: crossover rate b/w [0,1] (default 0.1) {mutation rate + crossover_rate <= 1}. scoring: metrics for evaluating the quality of the pipeline. Here scoring takes parameters such as Accuracy, F1 score etc cv: cross-validation method, if the given value is Integer, then it will be K in K-Fold cross-validation. n_job: number of processes that can be run in parallel (default 1). max_time_mins: maximum time Tpot allowed optimizing the pipeline (default: None). max_eval_time_mins: How many minutes TPOT has to evaluate a single pipeline(default: None). verbosity: How much information TPOT displays while it’s running. {0: nothing, 1: minimal information, 2: more information and progress bar, 3: everything} (default: 0) TpotRegressor: module to perform automated deep learning for regression tasks. Most of the arguments are common to above describe TpotClassifier. Here the only parameter which is different is scoring. In TpotRegression, we need to evaluate the regression, so we use parameters such as: ‘neg_median_absolute_error’, ‘neg_mean_absolute_error’, ‘neg_mean_squared_error’, ‘r2’ Both of the modules provide 4 functions to fit and evaluate the dataset. These are: fit(features, target): Run the TPOT optimization pipeline on the given data. predict(features): Use the optimized pipeline to predict the target values of an example/examples of features set. score(test_features, test_target): evaluate the model on test data and returns the most optimized score generated export(output_file_name): export the optimized pipeline as python code. In this implementation, we will be using Boston Housing Dataset and we will use ‘neg_mean_squared error’ as our scoring function. Python3 # install TPot and other dependencies!pip install sklearn fsspec xgboost%pip install -U distributed scikit-learn dask-ml dask-glm%pip install "tornado>=5" %pip install "dask[complete]"!pip install TPOT # import required modulesfrom tpot import TPOTRegressorfrom sklearn.datasets import load_bostonfrom sklearn.model_selection import train_test_splitimport numpy as np # load boston datasetX, y = load_boston(return_X_y=True) # divide the data into train and testX_train, X_test, y_train, y_test = train_test_split(X, y, test_size= .25) # define TpotRegressor reg = TPOTRegressor(verbosity=2, population_size=50, generations=10, random_state=35) # fit the regressor on training datareg.fit(X_train, y_train) # print the results on test dataprint(reg.score(X_test, y_test)) #save the model in top_boston.pyreg.export('top_boston.py') Generation 1 - Current best internal CV score: -13.196955982336481 Generation 2 - Current best internal CV score: -13.196955982336481 Generation 3 - Current best internal CV score: -13.196955982336481 Generation 4 - Current best internal CV score: -13.196015224855723 Generation 5 - Current best internal CV score: -13.143264025811806 Generation 6 - Current best internal CV score: -12.800705944988994 Generation 7 - Current best internal CV score: -12.717234303495596 Generation 8 - Current best internal CV score: -12.717234303495596 Generation 9 - Current best internal CV score: -11.707932909438588 Generation 10 - Current best internal CV score: -11.707932909438588 Best pipeline: ExtraTreesRegressor(input_matrix, bootstrap=False, max_features=0.7000000000000001, min_samples_leaf=1, min_samples_split=3, n_estimators=100) -8.098697897637797 Now, we look into the file generated by the TpotRegressor i.e: the file contains code to read data using pandas and model for best regressor. #tpot_boston.py import numpy as np import pandas as pd from sklearn.ensemble import ExtraTreesRegressor from sklearn.model_selection import train_test_split # NOTE: Make sure that the outcome column is labeled 'target' in the data file tpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64) features = tpot_data.drop('target', axis=1) training_features, testing_features, training_target, testing_target = \ train_test_split(features, tpot_data['target'], random_state=35) # Average CV score on the training set was: -11.707932909438588 exported_pipeline = ExtraTreesRegressor(bootstrap=False, max_features=0.7000000000000001, min_samples_leaf=1, min_samples_split=3, n_estimators=100) # Fix random state in exported estimator if hasattr(exported_pipeline, 'random_state'): setattr(exported_pipeline, 'random_state', 35) exported_pipeline.fit(training_features, training_target) results = exported_pipeline.predict(testing_features) Tpot Documentation ML-Statistics Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm ML | Monte Carlo Tree Search (MCTS) Markov Decision Process DBSCAN Clustering in ML | Density based clustering Normalization vs Standardization Bagging vs Boosting in Machine Learning Principal Component Analysis with Python Types of Environments in AI Intuition of Adam Optimizer
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2021" }, { "code": null, "e": 424, "s": 28, "text": "Tpot is an automated machine learning package in python that uses genetic programming concepts to optimize the machine learning pipeline. It automates the most tedious part of machine learning by intelligently exploring thousands of the possible to find the best possible parameter that suits your data. Tpot is Tpot is built upon the scikit-learn, so its code looks similar to the scikit-learn." }, { "code": null, "e": 463, "s": 424, "text": "Parts of ML pipeline automated by Tpot" }, { "code": null, "e": 645, "s": 463, "text": "Tpot uses genetic programming to generate the optimized search space, they are inspired by Darwin’s idea of natural selection, the genetic programming uses the following properties:" }, { "code": null, "e": 971, "s": 645, "text": "Selection: In this stage, the fitness function is evaluated at each of the individuals and normalized their values, so that each of them has values between 0 and 1 and their sum is 1. After that, we decide a random number R b/w 0 and 1. Now, we keep those individuals whose value of fitness function is greater or equal to R." }, { "code": null, "e": 1101, "s": 971, "text": "Crossover: Now, we can select the fittest individuals from above and perform crossover between them to generate a new population." }, { "code": null, "e": 1259, "s": 1101, "text": "Mutation: Mutate the individuals generated by crossover and perform some random modifications and repeat it for few steps or until we get the best population" }, { "code": null, "e": 1304, "s": 1259, "text": "Below are some important functions of Tpot: " }, { "code": null, "e": 1318, "s": 1304, "text": "TpoT Pipeline" }, { "code": null, "e": 2521, "s": 1318, "text": "TpotClassifier: module to perform automated learning for the supervised classification task. Below are some important arguments it takes:generations: number of iterations to run pipeline process (default: 100).population_size: number of individuals to retain genetic programming population every generation ( default 100).offspring_size: number of offspring to generate in each genetic programming iteration. (default 100).mutation_rate: mutation rate b/w [0,1] (default 0.9)crossover_rate: crossover rate b/w [0,1] (default 0.1) {mutation rate + crossover_rate <= 1}.scoring: metrics for evaluating the quality of the pipeline. Here scoring takes parameters such as Accuracy, F1 score etccv: cross-validation method, if the given value is Integer, then it will be K in K-Fold cross-validation.n_job: number of processes that can be run in parallel (default 1).max_time_mins: maximum time Tpot allowed optimizing the pipeline (default: None).max_eval_time_mins: How many minutes TPOT has to evaluate a single pipeline(default: None).verbosity: How much information TPOT displays while it’s running. {0: nothing, 1: minimal information, 2: more information and progress bar, 3: everything} (default: 0) " }, { "code": null, "e": 2595, "s": 2521, "text": "generations: number of iterations to run pipeline process (default: 100)." }, { "code": null, "e": 2708, "s": 2595, "text": "population_size: number of individuals to retain genetic programming population every generation ( default 100)." }, { "code": null, "e": 2810, "s": 2708, "text": "offspring_size: number of offspring to generate in each genetic programming iteration. (default 100)." }, { "code": null, "e": 2863, "s": 2810, "text": "mutation_rate: mutation rate b/w [0,1] (default 0.9)" }, { "code": null, "e": 2957, "s": 2863, "text": "crossover_rate: crossover rate b/w [0,1] (default 0.1) {mutation rate + crossover_rate <= 1}." }, { "code": null, "e": 3079, "s": 2957, "text": "scoring: metrics for evaluating the quality of the pipeline. Here scoring takes parameters such as Accuracy, F1 score etc" }, { "code": null, "e": 3185, "s": 3079, "text": "cv: cross-validation method, if the given value is Integer, then it will be K in K-Fold cross-validation." }, { "code": null, "e": 3253, "s": 3185, "text": "n_job: number of processes that can be run in parallel (default 1)." }, { "code": null, "e": 3335, "s": 3253, "text": "max_time_mins: maximum time Tpot allowed optimizing the pipeline (default: None)." }, { "code": null, "e": 3427, "s": 3335, "text": "max_eval_time_mins: How many minutes TPOT has to evaluate a single pipeline(default: None)." }, { "code": null, "e": 3597, "s": 3427, "text": "verbosity: How much information TPOT displays while it’s running. {0: nothing, 1: minimal information, 2: more information and progress bar, 3: everything} (default: 0) " }, { "code": null, "e": 3970, "s": 3597, "text": "TpotRegressor: module to perform automated deep learning for regression tasks. Most of the arguments are common to above describe TpotClassifier. Here the only parameter which is different is scoring. In TpotRegression, we need to evaluate the regression, so we use parameters such as: ‘neg_median_absolute_error’, ‘neg_mean_absolute_error’, ‘neg_mean_squared_error’, ‘r2’" }, { "code": null, "e": 4054, "s": 3970, "text": "Both of the modules provide 4 functions to fit and evaluate the dataset. These are:" }, { "code": null, "e": 4131, "s": 4054, "text": "fit(features, target): Run the TPOT optimization pipeline on the given data." }, { "code": null, "e": 4246, "s": 4131, "text": "predict(features): Use the optimized pipeline to predict the target values of an example/examples of features set." }, { "code": null, "e": 4360, "s": 4246, "text": "score(test_features, test_target): evaluate the model on test data and returns the most optimized score generated" }, { "code": null, "e": 4432, "s": 4360, "text": "export(output_file_name): export the optimized pipeline as python code." }, { "code": null, "e": 4562, "s": 4432, "text": "In this implementation, we will be using Boston Housing Dataset and we will use ‘neg_mean_squared error’ as our scoring function." }, { "code": null, "e": 4570, "s": 4562, "text": "Python3" }, { "code": "# install TPot and other dependencies!pip install sklearn fsspec xgboost%pip install -U distributed scikit-learn dask-ml dask-glm%pip install \"tornado>=5\" %pip install \"dask[complete]\"!pip install TPOT # import required modulesfrom tpot import TPOTRegressorfrom sklearn.datasets import load_bostonfrom sklearn.model_selection import train_test_splitimport numpy as np # load boston datasetX, y = load_boston(return_X_y=True) # divide the data into train and testX_train, X_test, y_train, y_test = train_test_split(X, y, test_size= .25) # define TpotRegressor reg = TPOTRegressor(verbosity=2, population_size=50, generations=10, random_state=35) # fit the regressor on training datareg.fit(X_train, y_train) # print the results on test dataprint(reg.score(X_test, y_test)) #save the model in top_boston.pyreg.export('top_boston.py')", "e": 5409, "s": 4570, "text": null }, { "code": null, "e": 6267, "s": 5409, "text": "Generation 1 - Current best internal CV score: -13.196955982336481\n\nGeneration 2 - Current best internal CV score: -13.196955982336481\n\nGeneration 3 - Current best internal CV score: -13.196955982336481\n\nGeneration 4 - Current best internal CV score: -13.196015224855723\n\nGeneration 5 - Current best internal CV score: -13.143264025811806\n\nGeneration 6 - Current best internal CV score: -12.800705944988994\n\nGeneration 7 - Current best internal CV score: -12.717234303495596\n\nGeneration 8 - Current best internal CV score: -12.717234303495596\n\nGeneration 9 - Current best internal CV score: -11.707932909438588\n\nGeneration 10 - Current best internal CV score: -11.707932909438588\n\nBest pipeline: ExtraTreesRegressor(input_matrix, bootstrap=False, max_features=0.7000000000000001, min_samples_leaf=1, min_samples_split=3, n_estimators=100)\n-8.098697897637797" }, { "code": null, "e": 6409, "s": 6267, "text": "Now, we look into the file generated by the TpotRegressor i.e: the file contains code to read data using pandas and model for best regressor." }, { "code": null, "e": 7395, "s": 6409, "text": "#tpot_boston.py\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import ExtraTreesRegressor\nfrom sklearn.model_selection import train_test_split\n\n# NOTE: Make sure that the outcome column is labeled 'target' in the data file\ntpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64)\nfeatures = tpot_data.drop('target', axis=1)\ntraining_features, testing_features, training_target, testing_target = \\\n train_test_split(features, tpot_data['target'], random_state=35)\n\n# Average CV score on the training set was: -11.707932909438588\nexported_pipeline = ExtraTreesRegressor(bootstrap=False, max_features=0.7000000000000001,\n min_samples_leaf=1, min_samples_split=3, n_estimators=100)\n\n# Fix random state in exported estimator\nif hasattr(exported_pipeline, 'random_state'):\n setattr(exported_pipeline, 'random_state', 35)\n\nexported_pipeline.fit(training_features, training_target)\nresults = exported_pipeline.predict(testing_features)" }, { "code": null, "e": 7414, "s": 7395, "text": "Tpot Documentation" }, { "code": null, "e": 7428, "s": 7414, "text": "ML-Statistics" }, { "code": null, "e": 7445, "s": 7428, "text": "Machine Learning" }, { "code": null, "e": 7462, "s": 7445, "text": "Machine Learning" }, { "code": null, "e": 7560, "s": 7462, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7601, "s": 7560, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 7634, "s": 7601, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 7670, "s": 7634, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 7694, "s": 7670, "text": "Markov Decision Process" }, { "code": null, "e": 7745, "s": 7694, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 7778, "s": 7745, "text": "Normalization vs Standardization" }, { "code": null, "e": 7818, "s": 7778, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 7859, "s": 7818, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 7887, "s": 7859, "text": "Types of Environments in AI" } ]
PHP | Get PHP configuration information using phpinfo()
13 Jan, 2022 PHP provides us with a built-in function phpinfo() which gives us the details about the PHP version and PHP configuration of PHP installed in our system. To know about the Configurations and PHP version which is installed in your computer, a simple PHP script can be used. The script consists of a PHP function called “phpinfo()” which outputs information about PHP’s configuration. The phpinfo() function is also useful in the debugging process.This function generally outputs a large amount of information, such as: Information about PHP compilation options and extensions.PHP version.Server information and environment (if compiled as a module).PHP environment.OS version information, paths, master and local values of configuration options.HTTP headers.PHP license. Information about PHP compilation options and extensions. PHP version. Server information and environment (if compiled as a module). PHP environment. OS version information, paths, master and local values of configuration options. HTTP headers. PHP license. Syntax: bool phpinfo ([ int $what = INFO_ALL ] ) Parameters: $what : It is an optional parameter which can be used to display specific information. It can take the following values: INFO_GENERAL:It is used to display the configuration line, php.ini location, build date, Web Server, System and more. INFO_CREDITS:It is used to display PHP Credits. INFO_CONFIGURATION: It is used to display current, local and Master values for PHP directives. INFO_MODULES: It is used to display loaded modules and their respective settings. INFO_ENVIRONMENT:It is used to display the environment variable information. INFO_VARIABLES:It shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server). INFO_LICENSE:It is used to display PHP License information. INFO_ALL:It shows all of the above information. INFO_GENERAL:It is used to display the configuration line, php.ini location, build date, Web Server, System and more. INFO_CREDITS:It is used to display PHP Credits. INFO_CONFIGURATION: It is used to display current, local and Master values for PHP directives. INFO_MODULES: It is used to display loaded modules and their respective settings. INFO_ENVIRONMENT:It is used to display the environment variable information. INFO_VARIABLES:It shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server). INFO_LICENSE:It is used to display PHP License information. INFO_ALL:It shows all of the above information. Return Type: The phpinfo() function return a boolean value. That is, it returns true on success and false on failure.Displaying Complete information: To display the complete information on the PHP version, configurations, environment details etc. the phpinfo() function should be executed in the following way: php <?php phpinfo(); ?> Output: Note: phpinfo() outputs plain text instead of HTML when using the CLI mode. Akanksha_Rai rkbhola5 PHP-function Misc PHP Web Technologies Misc Misc PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Virtualization In Cloud Computing and Types Association Rule OOPs | Object Oriented Design Software Engineering | Prototyping Model Java Math min() method with Examples How to execute PHP code using command line ? PHP in_array() Function How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ?
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2022" }, { "code": null, "e": 548, "s": 28, "text": "PHP provides us with a built-in function phpinfo() which gives us the details about the PHP version and PHP configuration of PHP installed in our system. To know about the Configurations and PHP version which is installed in your computer, a simple PHP script can be used. The script consists of a PHP function called “phpinfo()” which outputs information about PHP’s configuration. The phpinfo() function is also useful in the debugging process.This function generally outputs a large amount of information, such as: " }, { "code": null, "e": 800, "s": 548, "text": "Information about PHP compilation options and extensions.PHP version.Server information and environment (if compiled as a module).PHP environment.OS version information, paths, master and local values of configuration options.HTTP headers.PHP license." }, { "code": null, "e": 858, "s": 800, "text": "Information about PHP compilation options and extensions." }, { "code": null, "e": 871, "s": 858, "text": "PHP version." }, { "code": null, "e": 933, "s": 871, "text": "Server information and environment (if compiled as a module)." }, { "code": null, "e": 950, "s": 933, "text": "PHP environment." }, { "code": null, "e": 1031, "s": 950, "text": "OS version information, paths, master and local values of configuration options." }, { "code": null, "e": 1045, "s": 1031, "text": "HTTP headers." }, { "code": null, "e": 1058, "s": 1045, "text": "PHP license." }, { "code": null, "e": 1068, "s": 1058, "text": "Syntax: " }, { "code": null, "e": 1109, "s": 1068, "text": "bool phpinfo ([ int $what = INFO_ALL ] )" }, { "code": null, "e": 1244, "s": 1109, "text": "Parameters: $what : It is an optional parameter which can be used to display specific information. It can take the following values: " }, { "code": null, "e": 1883, "s": 1244, "text": "INFO_GENERAL:It is used to display the configuration line, php.ini location, build date, Web Server, System and more. INFO_CREDITS:It is used to display PHP Credits. INFO_CONFIGURATION: It is used to display current, local and Master values for PHP directives. INFO_MODULES: It is used to display loaded modules and their respective settings. INFO_ENVIRONMENT:It is used to display the environment variable information. INFO_VARIABLES:It shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server). INFO_LICENSE:It is used to display PHP License information. INFO_ALL:It shows all of the above information. " }, { "code": null, "e": 2003, "s": 1883, "text": "INFO_GENERAL:It is used to display the configuration line, php.ini location, build date, Web Server, System and more. " }, { "code": null, "e": 2053, "s": 2003, "text": "INFO_CREDITS:It is used to display PHP Credits. " }, { "code": null, "e": 2150, "s": 2053, "text": "INFO_CONFIGURATION: It is used to display current, local and Master values for PHP directives. " }, { "code": null, "e": 2234, "s": 2150, "text": "INFO_MODULES: It is used to display loaded modules and their respective settings. " }, { "code": null, "e": 2313, "s": 2234, "text": "INFO_ENVIRONMENT:It is used to display the environment variable information. " }, { "code": null, "e": 2417, "s": 2313, "text": "INFO_VARIABLES:It shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server). " }, { "code": null, "e": 2479, "s": 2417, "text": "INFO_LICENSE:It is used to display PHP License information. " }, { "code": null, "e": 2529, "s": 2479, "text": "INFO_ALL:It shows all of the above information. " }, { "code": null, "e": 2841, "s": 2529, "text": "Return Type: The phpinfo() function return a boolean value. That is, it returns true on success and false on failure.Displaying Complete information: To display the complete information on the PHP version, configurations, environment details etc. the phpinfo() function should be executed in the following way: " }, { "code": null, "e": 2845, "s": 2841, "text": "php" }, { "code": "<?php phpinfo(); ?>", "e": 2865, "s": 2845, "text": null }, { "code": null, "e": 2874, "s": 2865, "text": "Output: " }, { "code": null, "e": 2950, "s": 2874, "text": "Note: phpinfo() outputs plain text instead of HTML when using the CLI mode." }, { "code": null, "e": 2963, "s": 2950, "text": "Akanksha_Rai" }, { "code": null, "e": 2972, "s": 2963, "text": "rkbhola5" }, { "code": null, "e": 2985, "s": 2972, "text": "PHP-function" }, { "code": null, "e": 2990, "s": 2985, "text": "Misc" }, { "code": null, "e": 2994, "s": 2990, "text": "PHP" }, { "code": null, "e": 3011, "s": 2994, "text": "Web Technologies" }, { "code": null, "e": 3016, "s": 3011, "text": "Misc" }, { "code": null, "e": 3021, "s": 3016, "text": "Misc" }, { "code": null, "e": 3025, "s": 3021, "text": "PHP" }, { "code": null, "e": 3123, "s": 3025, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3167, "s": 3123, "text": "Virtualization In Cloud Computing and Types" }, { "code": null, "e": 3184, "s": 3167, "text": "Association Rule" }, { "code": null, "e": 3214, "s": 3184, "text": "OOPs | Object Oriented Design" }, { "code": null, "e": 3255, "s": 3214, "text": "Software Engineering | Prototyping Model" }, { "code": null, "e": 3292, "s": 3255, "text": "Java Math min() method with Examples" }, { "code": null, "e": 3337, "s": 3292, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 3361, "s": 3337, "text": "PHP in_array() Function" }, { "code": null, "e": 3413, "s": 3361, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 3463, "s": 3413, "text": "How to Insert Form Data into Database using PHP ?" } ]
Remove characters that appear more than k times
23 Jun, 2022 Given a string of lowercase letters, reduce it by removing the characters which appear more than k times in the string.Examples: Input : str = "geeksforgeeks" k = 2 Output : for Input : str = "geeksforgeeks" k = 3 Output : gksforgks Approach : Create a hash table of 26 indexes, where 0th index represents ‘a’ and 1th index represents ‘b’ and so on. Initialize the hash table to zero. Iterate through the string and count increment the frequency of the str[i] character in the hash table. Now once again traverse through the string and append those characters in the new string whose frequency in the hash table is less than k and skip those which appear more than equal to k. Time Complexity – O(N)Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ program to reduce the string by// removing the characters which// appears more than k times#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; void removeChars(char arr[], int k){ // Hash table initialised to 0 int hash[MAX_CHAR] = { 0 }; // Increment the frequency of the character int n = strlen(arr); for (int i = 0; i < n; ++i) hash[arr[i] - 'a']++; // Next index in reduced string int index = 0; for (int i = 0; i < n; ++i) { // Append the characters which // appears less than k times if (hash[arr[i] - 'a'] < k) { arr[index++] = arr[i]; } } arr[index] = '\0';} int main(){ char str[] = "geeksforgeeks"; int k = 2; removeChars(str, k); cout << str; return 0;} // Java program to reduce the string by// removing the characters which// appears more than k timesimport java.util.*;class Solution{ static final int MAX_CHAR = 26; static void removeChars(char arr[], int k){ // Hash table initialised to 0 int hash[]=new int[MAX_CHAR]; for (int i = 0; i <MAX_CHAR; ++i) hash[i]=0; // Increment the frequency of the character int n = (arr).length; for (int i = 0; i < n; ++i) hash[arr[i] - 'a']++; // Next index in reduced string int index = 0; for (int i = 0; i < n; ++i) { // Append the characters which // appears less than k times if (hash[arr[i] - 'a'] < k) { arr[index++] = arr[i]; } } for (int i = index; i < n; ++i) arr[i] = ' ';} public static void main(String args[]){ char str[] = "geeksforgeeks".toCharArray();; int k = 2; removeChars(str, k); System.out.println(String.valueOf( str));} }//contributed by Arnab Kundu # Python 3 program to reduce the string by# removing the characters which# appears more than k timesMAX_CHAR = 26 def removeChars(arr, k): # Hash table initialised to 0 hash = [0 for i in range(MAX_CHAR)] # Increment the frequency of the character n = len(arr) for i in range(n): hash[ord(arr[i]) - ord('a')] += 1 # Next index in reduced string index = 0 for i in range(n): # Append the characters which # appears less than k times if (hash[ord(arr[i]) - ord('a')] < k): arr[index] = arr[i] index += 1 arr[index] = ' ' for i in range(index): print(arr[i], end = '') # Driver codeif __name__ == '__main__': str = "geeksforgeeks" str = list(str) k = 2 removeChars(str, k) # This code is contributed by# Shashank_Sharma // C# program to reduce the string by// removing the characters which// appears more than k timesusing System;public class Solution{ static readonly int MAX_CHAR = 26; static void removeChars(char []arr, int k) { // Hash table initialised to 0 int []hash=new int[MAX_CHAR]; for (int i = 0; i <MAX_CHAR; ++i) hash[i]=0; // Increment the frequency of the character int n = (arr).Length; for (int i = 0; i < n; ++i) hash[arr[i] - 'a']++; // Next index in reduced string int index = 0; for (int i = 0; i < n; ++i) { // Append the characters which // appears less than k times if (hash[arr[i] - 'a'] < k) { arr[index++] = arr[i]; } } for (int i = index; i < n; ++i) arr[i] = ' '; } public static void Main() { char []str = "geeksforgeeks".ToCharArray();; int k = 2; removeChars(str, k); Console.Write(String.Join("",str)); } }// This code is contributed by PrinciRaj1992 <?php// PHP program to reduce the string by// removing the characters which// appears more than k times$MAX_CHAR = 26; function removeChars($arr, $k){ global $MAX_CHAR; // Hash table initialised to 0 $hash = array_fill(0, $MAX_CHAR, NULL); // Increment the frequency of // the character $n = strlen($arr); for ($i = 0; $i < $n; ++$i) $hash[ord($arr[$i]) - ord('a')]++; // Next index in reduced string $index = 0; for ($i = 0; $i < $n; ++$i) { // Append the characters which // appears less than k times if ($hash[ord($arr[$i]) - ord('a')] < $k) { $arr[$index++] = $arr[$i]; } } $arr[$index] = ''; for($i = 0; $i < $index; $i++) echo $arr[$i];} // Driver Code$str = "geeksforgeeks";$k = 2;removeChars($str, $k); // This code is contributed by ita_c?> <script> // JavaScript program to reduce the string by// removing the characters which// appears less than k times let MAX_CHAR = 26; // Function to reduce the string by// removing the characters which// appears less than k times function removeChars(str,k) { // Hash table initialised to 0 let hash = new Array(MAX_CHAR); for(let i=0;i<hash.length;i++) { hash[i]=0; } // Increment the frequency of the character let n = str.length; for (let i = 0; i < n; ++i) { hash[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // create a new empty string let index = ""; for (let i = 0; i < n; ++i) { // Append the characters which // appears more than equal to k times if (hash[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] < k) { index += str[i]; } } return index; } // Driver Code let str = "geeksforgeeks"; let k = 2; document.write(removeChars(str, k)); // This code is contributed by rag2127 </script> for Time Complexity: O(n), where n represents the size of the given array. Auxiliary Space: O(26), no extra space is required, so it is a constant. We will scan the string and count the occurrence of all characters using built-in Counter() function. Now once again traverse through the string and append those characters in the new string whose frequency in the frequency dictionary is less than k and skip those which appear more than equal to k. Note: This method is applicable for all types of characters. Python3 # Python 3 program to reduce the string# by removing the characters which# appears more than k timesfrom collections import Counter # Function to reduce the string by# removing the characters which# appears more than k timesdef removeChars(str, k): # Using Counter function to # count frequencies freq = Counter(str) # create a new empty string res = "" for i in range(len(str)): # Append the characters which # appears less than equal to k times if (freq[str[i]] < k): res += str[i] return res # Driver Codeif __name__ == "__main__": str = "geeksforgeeks" k = 2 print(removeChars(str, k)) # This code is contributed by vikkycirus for Time Complexity: O(n), where n represents the size of the given array. Auxiliary Space: O(26), no extra space is required, so it is a constant. andrew1234 princiraj1992 Shashank_Sharma ukasp vikkycirus rag2127 tamanna17122007 frequency-counting Technical Scripter 2018 Hash Strings Technical Scripter Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2022" }, { "code": null, "e": 158, "s": 28, "text": "Given a string of lowercase letters, reduce it by removing the characters which appear more than k times in the string.Examples: " }, { "code": null, "e": 279, "s": 158, "text": "Input : str = \"geeksforgeeks\"\n k = 2\nOutput : for\n\nInput : str = \"geeksforgeeks\"\n k = 3\nOutput : gksforgks" }, { "code": null, "e": 292, "s": 279, "text": "Approach : " }, { "code": null, "e": 433, "s": 292, "text": "Create a hash table of 26 indexes, where 0th index represents ‘a’ and 1th index represents ‘b’ and so on. Initialize the hash table to zero." }, { "code": null, "e": 537, "s": 433, "text": "Iterate through the string and count increment the frequency of the str[i] character in the hash table." }, { "code": null, "e": 725, "s": 537, "text": "Now once again traverse through the string and append those characters in the new string whose frequency in the hash table is less than k and skip those which appear more than equal to k." }, { "code": null, "e": 795, "s": 725, "text": "Time Complexity – O(N)Below is the implementation of above approach: " }, { "code": null, "e": 799, "s": 795, "text": "C++" }, { "code": null, "e": 804, "s": 799, "text": "Java" }, { "code": null, "e": 812, "s": 804, "text": "Python3" }, { "code": null, "e": 815, "s": 812, "text": "C#" }, { "code": null, "e": 819, "s": 815, "text": "PHP" }, { "code": null, "e": 830, "s": 819, "text": "Javascript" }, { "code": "// C++ program to reduce the string by// removing the characters which// appears more than k times#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; void removeChars(char arr[], int k){ // Hash table initialised to 0 int hash[MAX_CHAR] = { 0 }; // Increment the frequency of the character int n = strlen(arr); for (int i = 0; i < n; ++i) hash[arr[i] - 'a']++; // Next index in reduced string int index = 0; for (int i = 0; i < n; ++i) { // Append the characters which // appears less than k times if (hash[arr[i] - 'a'] < k) { arr[index++] = arr[i]; } } arr[index] = '\\0';} int main(){ char str[] = \"geeksforgeeks\"; int k = 2; removeChars(str, k); cout << str; return 0;}", "e": 1618, "s": 830, "text": null }, { "code": "// Java program to reduce the string by// removing the characters which// appears more than k timesimport java.util.*;class Solution{ static final int MAX_CHAR = 26; static void removeChars(char arr[], int k){ // Hash table initialised to 0 int hash[]=new int[MAX_CHAR]; for (int i = 0; i <MAX_CHAR; ++i) hash[i]=0; // Increment the frequency of the character int n = (arr).length; for (int i = 0; i < n; ++i) hash[arr[i] - 'a']++; // Next index in reduced string int index = 0; for (int i = 0; i < n; ++i) { // Append the characters which // appears less than k times if (hash[arr[i] - 'a'] < k) { arr[index++] = arr[i]; } } for (int i = index; i < n; ++i) arr[i] = ' ';} public static void main(String args[]){ char str[] = \"geeksforgeeks\".toCharArray();; int k = 2; removeChars(str, k); System.out.println(String.valueOf( str));} }//contributed by Arnab Kundu", "e": 2594, "s": 1618, "text": null }, { "code": "# Python 3 program to reduce the string by# removing the characters which# appears more than k timesMAX_CHAR = 26 def removeChars(arr, k): # Hash table initialised to 0 hash = [0 for i in range(MAX_CHAR)] # Increment the frequency of the character n = len(arr) for i in range(n): hash[ord(arr[i]) - ord('a')] += 1 # Next index in reduced string index = 0 for i in range(n): # Append the characters which # appears less than k times if (hash[ord(arr[i]) - ord('a')] < k): arr[index] = arr[i] index += 1 arr[index] = ' ' for i in range(index): print(arr[i], end = '') # Driver codeif __name__ == '__main__': str = \"geeksforgeeks\" str = list(str) k = 2 removeChars(str, k) # This code is contributed by# Shashank_Sharma", "e": 3440, "s": 2594, "text": null }, { "code": "// C# program to reduce the string by// removing the characters which// appears more than k timesusing System;public class Solution{ static readonly int MAX_CHAR = 26; static void removeChars(char []arr, int k) { // Hash table initialised to 0 int []hash=new int[MAX_CHAR]; for (int i = 0; i <MAX_CHAR; ++i) hash[i]=0; // Increment the frequency of the character int n = (arr).Length; for (int i = 0; i < n; ++i) hash[arr[i] - 'a']++; // Next index in reduced string int index = 0; for (int i = 0; i < n; ++i) { // Append the characters which // appears less than k times if (hash[arr[i] - 'a'] < k) { arr[index++] = arr[i]; } } for (int i = index; i < n; ++i) arr[i] = ' '; } public static void Main() { char []str = \"geeksforgeeks\".ToCharArray();; int k = 2; removeChars(str, k); Console.Write(String.Join(\"\",str)); } }// This code is contributed by PrinciRaj1992", "e": 4523, "s": 3440, "text": null }, { "code": "<?php// PHP program to reduce the string by// removing the characters which// appears more than k times$MAX_CHAR = 26; function removeChars($arr, $k){ global $MAX_CHAR; // Hash table initialised to 0 $hash = array_fill(0, $MAX_CHAR, NULL); // Increment the frequency of // the character $n = strlen($arr); for ($i = 0; $i < $n; ++$i) $hash[ord($arr[$i]) - ord('a')]++; // Next index in reduced string $index = 0; for ($i = 0; $i < $n; ++$i) { // Append the characters which // appears less than k times if ($hash[ord($arr[$i]) - ord('a')] < $k) { $arr[$index++] = $arr[$i]; } } $arr[$index] = ''; for($i = 0; $i < $index; $i++) echo $arr[$i];} // Driver Code$str = \"geeksforgeeks\";$k = 2;removeChars($str, $k); // This code is contributed by ita_c?>", "e": 5388, "s": 4523, "text": null }, { "code": "<script> // JavaScript program to reduce the string by// removing the characters which// appears less than k times let MAX_CHAR = 26; // Function to reduce the string by// removing the characters which// appears less than k times function removeChars(str,k) { // Hash table initialised to 0 let hash = new Array(MAX_CHAR); for(let i=0;i<hash.length;i++) { hash[i]=0; } // Increment the frequency of the character let n = str.length; for (let i = 0; i < n; ++i) { hash[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // create a new empty string let index = \"\"; for (let i = 0; i < n; ++i) { // Append the characters which // appears more than equal to k times if (hash[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] < k) { index += str[i]; } } return index; } // Driver Code let str = \"geeksforgeeks\"; let k = 2; document.write(removeChars(str, k)); // This code is contributed by rag2127 </script>", "e": 6548, "s": 5388, "text": null }, { "code": null, "e": 6552, "s": 6548, "text": "for" }, { "code": null, "e": 6625, "s": 6554, "text": "Time Complexity: O(n), where n represents the size of the given array." }, { "code": null, "e": 6698, "s": 6625, "text": "Auxiliary Space: O(26), no extra space is required, so it is a constant." }, { "code": null, "e": 6800, "s": 6698, "text": "We will scan the string and count the occurrence of all characters using built-in Counter() function." }, { "code": null, "e": 6998, "s": 6800, "text": "Now once again traverse through the string and append those characters in the new string whose frequency in the frequency dictionary is less than k and skip those which appear more than equal to k." }, { "code": null, "e": 7059, "s": 6998, "text": "Note: This method is applicable for all types of characters." }, { "code": null, "e": 7067, "s": 7059, "text": "Python3" }, { "code": "# Python 3 program to reduce the string# by removing the characters which# appears more than k timesfrom collections import Counter # Function to reduce the string by# removing the characters which# appears more than k timesdef removeChars(str, k): # Using Counter function to # count frequencies freq = Counter(str) # create a new empty string res = \"\" for i in range(len(str)): # Append the characters which # appears less than equal to k times if (freq[str[i]] < k): res += str[i] return res # Driver Codeif __name__ == \"__main__\": str = \"geeksforgeeks\" k = 2 print(removeChars(str, k)) # This code is contributed by vikkycirus", "e": 7774, "s": 7067, "text": null }, { "code": null, "e": 7778, "s": 7774, "text": "for" }, { "code": null, "e": 7849, "s": 7778, "text": "Time Complexity: O(n), where n represents the size of the given array." }, { "code": null, "e": 7922, "s": 7849, "text": "Auxiliary Space: O(26), no extra space is required, so it is a constant." }, { "code": null, "e": 7933, "s": 7922, "text": "andrew1234" }, { "code": null, "e": 7947, "s": 7933, "text": "princiraj1992" }, { "code": null, "e": 7963, "s": 7947, "text": "Shashank_Sharma" }, { "code": null, "e": 7969, "s": 7963, "text": "ukasp" }, { "code": null, "e": 7980, "s": 7969, "text": "vikkycirus" }, { "code": null, "e": 7988, "s": 7980, "text": "rag2127" }, { "code": null, "e": 8004, "s": 7988, "text": "tamanna17122007" }, { "code": null, "e": 8023, "s": 8004, "text": "frequency-counting" }, { "code": null, "e": 8047, "s": 8023, "text": "Technical Scripter 2018" }, { "code": null, "e": 8052, "s": 8047, "text": "Hash" }, { "code": null, "e": 8060, "s": 8052, "text": "Strings" }, { "code": null, "e": 8079, "s": 8060, "text": "Technical Scripter" }, { "code": null, "e": 8084, "s": 8079, "text": "Hash" }, { "code": null, "e": 8092, "s": 8084, "text": "Strings" } ]
Print all sublists of a list in Python
12 Jul, 2022 Given a list, print all the sublists of a list. Examples: Input : list = [1, 2, 3] Output : [[], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]] Input : [1, 2, 3, 4] Output : [[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]] Approach#1: The approach will be run two nested loops till the length of the given list. The outer loop i traverse from 0 to the length of the list and the inner loop goes from 0 to i. Need to add 1 to length because the range only goes from 0 to i-1. To get the subarray we can use slicing to get the subarray. Step 1: Run a loop till length+1 of the given list.Step 2: Run another loop from 0 to i.Step 3: Slice the subarray from j to i. Step 4: Append it to a another list to store it Step 5: Print it at the end Below is the Python implementation of the above approach: Python # Python program to print all# sublist from a given list # function to generate all the sub listsdef sub_lists (l): lists = [[]] for i in range(len(l) + 1): for j in range(i): lists.append(l[j: i]) return lists # driver codel1 = [1, 2, 3]print(sub_lists(l1)) Output: [[], [1], [2], [1, 2], [3], [2, 3], [1, 2, 3]] Approach#2: The approach will use for loop and combinations function. For loop is used to iterate till the length of list which is helpful for generating a sub-list of variable ith length. With each iteration combinations function generate the possible combination of list with ith length. Python3 # Python program to print all# sublist from a given listfrom itertools import combinations # function to generate all the sub listsdef sub_lists (l): # initializing empty list comb = [] #Iterating till length of list for i in range(len(l)+1): # Generating sub list comb += [list(j) for j in combinations([1, 2, 3], i)] # Returning list return comb # driver code#Initial listl1 = [1, 2, 3] #Print initial listprint("Initial list is : " + str(l1)) # Calling function to generate all sub listsprint("All sub list is : "+ str(sub_lists(l1))) Output: Initial list is : [1, 2, 3] All sub list is : [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] guydangerous mongiavishesh1999 abdullahgokcinar ravinmechux wastu satyam00so Python list-programs python-list Python 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 Jul, 2022" }, { "code": null, "e": 102, "s": 53, "text": "Given a list, print all the sublists of a list. " }, { "code": null, "e": 113, "s": 102, "text": "Examples: " }, { "code": null, "e": 333, "s": 113, "text": "Input : list = [1, 2, 3] \nOutput : [[], [1], [1, 2], [1, 2, 3], [2], \n [2, 3], [3]]\n\nInput : [1, 2, 3, 4] \nOutput : [[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], \n [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]" }, { "code": null, "e": 348, "s": 335, "text": "Approach#1: " }, { "code": null, "e": 649, "s": 348, "text": "The approach will be run two nested loops till the length of the given list. The outer loop i traverse from 0 to the length of the list and the inner loop goes from 0 to i. Need to add 1 to length because the range only goes from 0 to i-1. To get the subarray we can use slicing to get the subarray. " }, { "code": null, "e": 853, "s": 649, "text": "Step 1: Run a loop till length+1 of the given list.Step 2: Run another loop from 0 to i.Step 3: Slice the subarray from j to i. Step 4: Append it to a another list to store it Step 5: Print it at the end" }, { "code": null, "e": 911, "s": 853, "text": "Below is the Python implementation of the above approach:" }, { "code": null, "e": 918, "s": 911, "text": "Python" }, { "code": "# Python program to print all# sublist from a given list # function to generate all the sub listsdef sub_lists (l): lists = [[]] for i in range(len(l) + 1): for j in range(i): lists.append(l[j: i]) return lists # driver codel1 = [1, 2, 3]print(sub_lists(l1))", "e": 1204, "s": 918, "text": null }, { "code": null, "e": 1213, "s": 1204, "text": "Output: " }, { "code": null, "e": 1260, "s": 1213, "text": "[[], [1], [2], [1, 2], [3], [2, 3], [1, 2, 3]]" }, { "code": null, "e": 1273, "s": 1260, "text": "Approach#2: " }, { "code": null, "e": 1552, "s": 1273, "text": "The approach will use for loop and combinations function. For loop is used to iterate till the length of list which is helpful for generating a sub-list of variable ith length. With each iteration combinations function generate the possible combination of list with ith length. " }, { "code": null, "e": 1560, "s": 1552, "text": "Python3" }, { "code": "# Python program to print all# sublist from a given listfrom itertools import combinations # function to generate all the sub listsdef sub_lists (l): # initializing empty list comb = [] #Iterating till length of list for i in range(len(l)+1): # Generating sub list comb += [list(j) for j in combinations([1, 2, 3], i)] # Returning list return comb # driver code#Initial listl1 = [1, 2, 3] #Print initial listprint(\"Initial list is : \" + str(l1)) # Calling function to generate all sub listsprint(\"All sub list is : \"+ str(sub_lists(l1)))", "e": 2135, "s": 1560, "text": null }, { "code": null, "e": 2143, "s": 2135, "text": "Output:" }, { "code": null, "e": 2244, "s": 2143, "text": "Initial list is : [1, 2, 3]\nAll sub list is : [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]" }, { "code": null, "e": 2257, "s": 2244, "text": "guydangerous" }, { "code": null, "e": 2275, "s": 2257, "text": "mongiavishesh1999" }, { "code": null, "e": 2292, "s": 2275, "text": "abdullahgokcinar" }, { "code": null, "e": 2304, "s": 2292, "text": "ravinmechux" }, { "code": null, "e": 2310, "s": 2304, "text": "wastu" }, { "code": null, "e": 2321, "s": 2310, "text": "satyam00so" }, { "code": null, "e": 2342, "s": 2321, "text": "Python list-programs" }, { "code": null, "e": 2354, "s": 2342, "text": "python-list" }, { "code": null, "e": 2361, "s": 2354, "text": "Python" }, { "code": null, "e": 2373, "s": 2361, "text": "python-list" } ]
Recursively enumerable sets and Turing machines - GeeksforGeeks
21 Jan, 2014 1. For every non-deterministic Turing machine, there exists an equivalent deterministic Turing machine. 2. Turing recognizable languages are closed under union and complementation. 3. Turing decidable languages are closed under intersection and complementation. 4. Turing recognizable languages are closed under union and intersection. A) Always True (Recursively enumerable - Recursive ) is Recursively enumerable B) Not always true L1 - L3 = L1 intersection ( Complement L3 ) L1 is recursive , L3 is recursively enumerable but not recursive Recursively enumerable languages are NOT closed under complement. C) and D) Always true Recursively enumerable languages are closed under intersection and union. A ≤m B means language A is mapping reducible to language B.Thus, A cannot be harder than B. Since, A can be reduced to B, instead of deciding A we can now decide B. So, the first three options are correct. As B is not recursively enumerable, it doesn't guarantee A is not recursively enumerable.Thus, if A ≤m B and B is not recursively enumerable then A is not recursively enumerable. Therefore, answer is D is correct L1' --> Complement of L1 L2' --> Complement of L2 S1 : L1 is recursive implies L2 is recursive S2 : L2 is recursive implies L1 is recursive Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Learn C++ Programming Step by Step - A 20 Day Curriculum! Must Do Coding Questions for Product Based Companies GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? Types of Distributed System Naming Convention in C++ Floyd’s Cycle Finding Algorithm TCS Digital Interview Experience | Off-Campus 2021 Samsung R&D Interview Experience Samsung Internship Interview Experience | On-Campus 2021
[ { "code": null, "e": 31777, "s": 31749, "text": "\n21 Jan, 2014" }, { "code": null, "e": 32130, "s": 31777, "text": "1. For every non-deterministic Turing machine, \n there exists an equivalent deterministic Turing machine.\n2. Turing recognizable languages are closed under union \n and complementation.\n3. Turing decidable languages are closed under intersection \n and complementation.\n4. Turing recognizable languages are closed under union \n and intersection. " }, { "code": null, "e": 32505, "s": 32130, "text": "A) Always True\n(Recursively enumerable - Recursive ) is \nRecursively enumerable\n\nB) Not always true\nL1 - L3 = L1 intersection ( Complement L3 )\nL1 is recursive , L3 is recursively enumerable \nbut not recursive Recursively enumerable languages\nare NOT closed under complement.\n\nC) and D) Always true Recursively enumerable languages \nare closed under intersection and union. " }, { "code": null, "e": 32711, "s": 32505, "text": "A ≤m B means language A is mapping reducible to language B.Thus, A cannot be harder than B.\nSince, A can be reduced to B, instead of deciding A we can now decide B.\nSo, the first three options are correct." }, { "code": null, "e": 32924, "s": 32711, "text": "As B is not recursively enumerable, it doesn't guarantee A is not recursively enumerable.Thus, if A ≤m B and B is not recursively enumerable then A is not recursively enumerable. Therefore, answer is D is correct" }, { "code": null, "e": 32975, "s": 32924, "text": "L1' --> Complement of L1\nL2' --> Complement of L2 " }, { "code": null, "e": 33067, "s": 32975, "text": "S1 : L1 is recursive implies L2 is recursive\nS2 : L2 is recursive implies L1 is recursive " }, { "code": null, "e": 33165, "s": 33067, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 33239, "s": 33165, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 33297, "s": 33239, "text": "Learn C++ Programming Step by Step - A 20 Day Curriculum!" }, { "code": null, "e": 33350, "s": 33297, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 33416, "s": 33350, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 33444, "s": 33416, "text": "Types of Distributed System" }, { "code": null, "e": 33469, "s": 33444, "text": "Naming Convention in C++" }, { "code": null, "e": 33501, "s": 33469, "text": "Floyd’s Cycle Finding Algorithm" }, { "code": null, "e": 33552, "s": 33501, "text": "TCS Digital Interview Experience | Off-Campus 2021" }, { "code": null, "e": 33585, "s": 33552, "text": "Samsung R&D Interview Experience" } ]
RC4 Encryption Algorithm
18 Oct, 2021 RC4 is a stream cipher and variable-length key algorithm. This algorithm encrypts one byte at a time (or larger units at a time).A key input is pseudorandom bit generator that produces a stream 8-bit number that is unpredictable without knowledge of input key, The output of the generator is called key-stream, is combined one byte at a time with the plaintext stream cipher using X-OR operation.Example: RC4 Encryption 10011000 ? 01010000 = 11001000 RC4 Decryption 11001000 ? 01010000 = 10011000 Key-Generation Algorithm –A variable-length key from 1 to 256 bytes is used to initialize a 256-byte state vector S, with elements S[0] to S[255]. For encryption and decryption, a byte k is generated from S by selecting one of the 255 entries in a systematic fashion, then the entries in S are permuted again. Key-Scheduling Algorithm:Initialization: The entries of S are set equal to the values from 0 to 255 in ascending order, a temporary vector T, is created.If the length of the key k is 256 bytes, then k is assigned to T. Otherwise, for a key with length(k-len) bytes, the first k-len elements of T as copied from K, and then K is repeated as many times as necessary to fill T. The idea is illustrated as follow:for i = 0 to 255 do S[i] = i;T[i] = K[i mod k - len];we use T to produce the initial permutation of S. Starting with S[0] to S[255], and for each S[i] algorithm swap it with another byte in S according to a scheme dictated by T[i], but S will still contain values from 0 to 255 :j = 0;for i = 0 to 255 do { j = (j + S[i] + T[i])mod 256; Swap(S[i], S[j]); }Pseudo random generation algorithm (Stream Generation):Once the vector S is initialized, the input key will not be used. In this step, for each S[i] algorithm swap it with another byte in S according to a scheme dictated by the current configuration of S. After reaching S[255] the process continues, starting from S[0] againi, j = 0;while (true) i = (i + 1)mod 256;j = (j + S[i])mod 256;Swap(S[i], S[j]);t = (S[i] + S[j])mod 256;k = S[t];Encrypt using X-Or(): Key-Scheduling Algorithm:Initialization: The entries of S are set equal to the values from 0 to 255 in ascending order, a temporary vector T, is created.If the length of the key k is 256 bytes, then k is assigned to T. Otherwise, for a key with length(k-len) bytes, the first k-len elements of T as copied from K, and then K is repeated as many times as necessary to fill T. The idea is illustrated as follow:for i = 0 to 255 do S[i] = i;T[i] = K[i mod k - len];we use T to produce the initial permutation of S. Starting with S[0] to S[255], and for each S[i] algorithm swap it with another byte in S according to a scheme dictated by T[i], but S will still contain values from 0 to 255 :j = 0;for i = 0 to 255 do { j = (j + S[i] + T[i])mod 256; Swap(S[i], S[j]); } for i = 0 to 255 do S[i] = i;T[i] = K[i mod k - len]; we use T to produce the initial permutation of S. Starting with S[0] to S[255], and for each S[i] algorithm swap it with another byte in S according to a scheme dictated by T[i], but S will still contain values from 0 to 255 : j = 0;for i = 0 to 255 do { j = (j + S[i] + T[i])mod 256; Swap(S[i], S[j]); } Pseudo random generation algorithm (Stream Generation):Once the vector S is initialized, the input key will not be used. In this step, for each S[i] algorithm swap it with another byte in S according to a scheme dictated by the current configuration of S. After reaching S[255] the process continues, starting from S[0] againi, j = 0;while (true) i = (i + 1)mod 256;j = (j + S[i])mod 256;Swap(S[i], S[j]);t = (S[i] + S[j])mod 256;k = S[t]; i, j = 0;while (true) i = (i + 1)mod 256;j = (j + S[i])mod 256;Swap(S[i], S[j]);t = (S[i] + S[j])mod 256;k = S[t]; Encrypt using X-Or(): News:In September 2015, Microsoft announced the end of using RC4 in Microsoft edge and internet explorer 11. This video gives a clear example of RC4 algorithmYouTubeWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosVideo unavailableThis video is unavailableMore videos on YouTubeSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:00•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage">Unable to execute JavaScript.</div></div> Akanksha_Rai Pushpender007 Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Oct, 2021" }, { "code": null, "e": 457, "s": 52, "text": "RC4 is a stream cipher and variable-length key algorithm. This algorithm encrypts one byte at a time (or larger units at a time).A key input is pseudorandom bit generator that produces a stream 8-bit number that is unpredictable without knowledge of input key, The output of the generator is called key-stream, is combined one byte at a time with the plaintext stream cipher using X-OR operation.Example:" }, { "code": null, "e": 557, "s": 457, "text": "RC4 Encryption \n10011000 ? 01010000 = 11001000 \n\nRC4 Decryption \n11001000 ? 01010000 = 10011000\n" }, { "code": null, "e": 867, "s": 557, "text": "Key-Generation Algorithm –A variable-length key from 1 to 256 bytes is used to initialize a 256-byte state vector S, with elements S[0] to S[255]. For encryption and decryption, a byte k is generated from S by selecting one of the 255 entries in a systematic fashion, then the entries in S are permuted again." }, { "code": null, "e": 2122, "s": 867, "text": "Key-Scheduling Algorithm:Initialization: The entries of S are set equal to the values from 0 to 255 in ascending order, a temporary vector T, is created.If the length of the key k is 256 bytes, then k is assigned to T. Otherwise, for a key with length(k-len) bytes, the first k-len elements of T as copied from K, and then K is repeated as many times as necessary to fill T. The idea is illustrated as follow:for i = 0 to 255 do S[i] = i;T[i] = K[i mod k - len];we use T to produce the initial permutation of S. Starting with S[0] to S[255], and for each S[i] algorithm swap it with another byte in S according to a scheme dictated by T[i], but S will still contain values from 0 to 255 :j = 0;for i = 0 to 255 do { j = (j + S[i] + T[i])mod 256; Swap(S[i], S[j]); }Pseudo random generation algorithm (Stream Generation):Once the vector S is initialized, the input key will not be used. In this step, for each S[i] algorithm swap it with another byte in S according to a scheme dictated by the current configuration of S. After reaching S[255] the process continues, starting from S[0] againi, j = 0;while (true) i = (i + 1)mod 256;j = (j + S[i])mod 256;Swap(S[i], S[j]);t = (S[i] + S[j])mod 256;k = S[t];Encrypt using X-Or():" }, { "code": null, "e": 2914, "s": 2122, "text": "Key-Scheduling Algorithm:Initialization: The entries of S are set equal to the values from 0 to 255 in ascending order, a temporary vector T, is created.If the length of the key k is 256 bytes, then k is assigned to T. Otherwise, for a key with length(k-len) bytes, the first k-len elements of T as copied from K, and then K is repeated as many times as necessary to fill T. The idea is illustrated as follow:for i = 0 to 255 do S[i] = i;T[i] = K[i mod k - len];we use T to produce the initial permutation of S. Starting with S[0] to S[255], and for each S[i] algorithm swap it with another byte in S according to a scheme dictated by T[i], but S will still contain values from 0 to 255 :j = 0;for i = 0 to 255 do { j = (j + S[i] + T[i])mod 256; Swap(S[i], S[j]); }" }, { "code": "for i = 0 to 255 do S[i] = i;T[i] = K[i mod k - len];", "e": 2971, "s": 2914, "text": null }, { "code": null, "e": 3198, "s": 2971, "text": "we use T to produce the initial permutation of S. Starting with S[0] to S[255], and for each S[i] algorithm swap it with another byte in S according to a scheme dictated by T[i], but S will still contain values from 0 to 255 :" }, { "code": "j = 0;for i = 0 to 255 do { j = (j + S[i] + T[i])mod 256; Swap(S[i], S[j]); }", "e": 3299, "s": 3198, "text": null }, { "code": null, "e": 3742, "s": 3299, "text": "Pseudo random generation algorithm (Stream Generation):Once the vector S is initialized, the input key will not be used. In this step, for each S[i] algorithm swap it with another byte in S according to a scheme dictated by the current configuration of S. After reaching S[255] the process continues, starting from S[0] againi, j = 0;while (true) i = (i + 1)mod 256;j = (j + S[i])mod 256;Swap(S[i], S[j]);t = (S[i] + S[j])mod 256;k = S[t];" }, { "code": "i, j = 0;while (true) i = (i + 1)mod 256;j = (j + S[i])mod 256;Swap(S[i], S[j]);t = (S[i] + S[j])mod 256;k = S[t];", "e": 3860, "s": 3742, "text": null }, { "code": null, "e": 3882, "s": 3860, "text": "Encrypt using X-Or():" }, { "code": null, "e": 3991, "s": 3882, "text": "News:In September 2015, Microsoft announced the end of using RC4 in Microsoft edge and internet explorer 11." }, { "code": null, "e": 4532, "s": 3991, "text": "This video gives a clear example of RC4 algorithmYouTubeWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosVideo unavailableThis video is unavailableMore videos on YouTubeSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:00•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\">Unable to execute JavaScript.</div></div>" }, { "code": null, "e": 4545, "s": 4532, "text": "Akanksha_Rai" }, { "code": null, "e": 4559, "s": 4545, "text": "Pushpender007" }, { "code": null, "e": 4577, "s": 4559, "text": "Computer Networks" }, { "code": null, "e": 4585, "s": 4577, "text": "GATE CS" }, { "code": null, "e": 4603, "s": 4585, "text": "Computer Networks" } ]
Uber H3 for Data Analysis with Python | by Eshwaran Venkat | Towards Data Science
If you’ve ever played Civilization VI or Settlers of Catan, you might have noticed that the board map is shaped into regular hexagons. This is a famed game design technique called Hex Map and is used in board games such as Hexagonal chess and video games such as Forge of Empires. This is a natural feature of the game because these maps bring in a lot of advantages for gameplay, especially in movement and tiling. What if this design could prove useful in the real world if we re-modelled our own maps with a layer of hexagons? Perhaps we can find some actual business problems that could be solved with such a model. Enter Uber H3. Currently there exist a number of ways to analyze data related to maps. One of the most rudimentary ways is to plot a list of co-ordinates and see where the densities and clusters arise. Analyzing individual points has certain drawbacks. There is no clear form of classification for points within a certain area and the analysis we often wish to carry out may be area-wise or regional. It would help if we had a grid system where points could be contained within a certain fence and we analyze the behavior of the grid itself as representing the behavior of all points underneath. This means each grid represents the data of the points beneath it. Another issue is that when using points directly, while useful for humans to see the map and notice where the data is bunching up may be computationally a bit more expensive for a computer system. A computer needs to calculate distances of neighboring points to group them together to gather the same visual insights as a human being. However, coordinate points are as granular as you can go with respect to geolocation data so don’t dismiss them just yet. We simply need to find a grid framework around which we, or a computer can view geospatial data and derive insights from it. A common form of using a grid system more locally is to define zones in cities, by drawing out a shape over a neighborhood, city, district or country. Administrative and political boundaries while useful to section the geospatial analysis into realistic areas may still be problematic in a number of ways. Some zones may be larger than other zones within a city, and there could be overlaps between two or more zones. Furthermore, from a mathematical/absolute perspective, defining zones in this form are highly arbitrary. Zones or districts may be defined based on natural features, population, economy, etc. and are subject to change over time. An absolute method of using uniform grid systems is to cover a the Earth with repeated tiling. Assuming that we want to tile our plane regularly and completely, we need to choose the shape that acts as a building block facilitating the complete tiling. This shape needs to be closed and uniformly repeating. Our candidates are the triangle (3 sides), square (4 sides), and hexagon (6 sides). There is no right answer here, so choosing one of these depends on your use-case. At Uber, one of the most in-demand use-cases we have is to determine distances for both rides and deliveries. Using a hexagon as the cell shape is critical for H3. Hexagons have only one distance between a hexagon’s center-point and its neighbors’, compared to two distances for squares or three distances for triangles. This property greatly simplifies performing analysis and smoothing over gradients. Besides distances, it is generally a good idea to choose a hexagon as the base shape because Hexagons are the Bestagons! ;) H3 is an open source framework developed by Uber in the C Programming Language. At its core, H3 is a geospatial analysis tool that provides a hexagonal, hierarchical spatial index to gain insights from large geospatial datasets. The building blocks of H3 are different sized regular hexagonal polygons. These polygons are spread out over the entire projection of the earth map from pole to pole. This means that any location on the planet can be attributed to a H3 Hexagon down to a precision of 0.0000009 km2 area. Imagine it as a layer over the planet where each unit of the layer is a hexagon and each hexagon has a unique ID and can very quickly perform geospatial calculations. Each H3 hexagon can be thought of as its own object and each object can be accessed in a very short amount of time given its ID. A core strength of H3 is that it covers the entire world with different sized hexagons. This means that the resolution of the layer can be adjusted based on the problem being solved, like scaling the entire grid up and down. H3 contains a total of 16 resolutions as described in the table below, and each resolution has a certain number of hexagons that span the entire earth as a layer ranging from 122 hexagons in the highest layer and about 500 trillion hexagons at the lowest layer. Each layer consists of a more granular level of hexagons and each hexagon of every layer has its own unique ID. H3 defines its indices via hexadecimal format (16-bits, and therefore 16 resolutions), so a cell resolution can be immediately determined by looking at the ID of the cell. The layered approach of different sized hexagons is what lends H3 its power of “hierarchy”. Every low resolution hexagon contains a set of child hexagons in higher resolutions. Every hexagon of a resolution can have sibling hexagons that share the same set of parent hexagons. The layers in essence define a tree of hexagons with the last layer (resolution) containing 500 trillion siblings. It’s worth checking out this notebook. The resolution can be adjusted accordingly and the hexagons can be viewed over the entire earth. You can find some examples of using H3 functions directly in the C language here. We’ll be using the H3 library binding with the Python programming language since it relatively easier to analyze data with Python. pip install h3 Let’s say you had a coordinate point, or even a list of coordinates. You can fetch the H3 index of each point with the following function: h3.geo_to_h3( lat=25.32, lng=55.46, resolution=7) Get the resolution of a H3 index if the index represented in a string is valid h3_result = lambda id_str: h3.h3_get_resolution(id_str) if h3.h3_is_valid(id_str) else Noneh3_result('8843a13687fffff') Let’s try a full fledged function that returns a set of H3 attributes, given a H3 index import h3 from shapely.geometry import Polygon, Point import shapely.wkt def output_h3_id_attributes(h3_id): return { "co_ordinates" : h3.h3_to_geo(h3_id), "geo_boundary" : Polygon(h3.h3_to_geo_boundary(h3_id, geo_json=True)).wkt, "parent" : h3.h3_to_parent(h3_id), "children" : h3.h3_to_children(h3_id) } output_h3_id_attributes('8843acd819fffff') {'co_ordinates': (25.311756198253676, 55.24286266589328), 'geo_boundary': 'POLYGON ((55.23774694448915 25.31287951583933, 55.23951392798415 25.30858249027833, 55.24462934439571 25.30745909858661, 55.24797838839316 25.31063268305425, 55.24621180412194 25.31493004366226, 55.24109577657453 25.31605348476041, 55.23774694448915 25.31287951583933))', 'parent': '8743acd81ffffff', 'children': {'8943acd8183ffff', '8943acd8187ffff', '8943acd818bffff', '8943acd818fffff', '8943acd8193ffff', '8943acd8197ffff', '8943acd819bffff'}} Another useful function in H3 is its ability to quickly return an index’s k-nearest neighbors. This means that for k =1, a hexagon’s 1st degree neighbors are returned, and for k = 2, it is second degree neighbors (or neighbors of neighbors) and so on. h3_id = "8843a13687fffff"h3.k_ring(h3_id,1)h3.k_ring(h3_id,2)h3.k_ring(h3_id,10) Now that we have some absolute methods to define grids over the Earth, it would suit us to begin assigning real-world details to hexagons. This is because despite having been given a H3 index and its centroid coordinate, we don’t have much to go on in terms of the physical location which that hexagon represents. One way to extend the power of H3 is to combine it together with Maps APIs that contain on-the-ground information. Common choices include Google Maps API, Mapbox API and Nominatim. These services allow us to assign more useful geographical information per hexagon. One common function is reverse geocoding, which is a technique of converting a given coordinate into a physical text address by means of a lookup. Let’s find the reverse geocode result of the centroid of a H3 index using the Google Maps Client for Python. If H3 contains different resolution hexagons that span the entire earth, what if you wanted to select a fraction of those hexagons that represented a country, city or neighborhood? The poly-fill function fills a polygon with H3 Hexagons. A geofence is a polygon spread out over a map. Zones in cities, or country shapes can be modelled as geofences. Geofences are often represented by means of Geo-JSON files or Shapely polygons. An example of a shapely polygon’s WKT(well known text representation): POLYGON ((55.13977696520102 25.09805053895709, 55.14002932545401 25.09743871100549, 55.1407574981263 25.0972787358399, 55.14123332293791 25.09773058763684, 55.14098097073993 25.09834242241949, 55.14025278567518 25.09850239857415, 55.13977696520102 25.09805053895709)) A WKT is, as the name implies, a textual representation of the polygon’s vertex points. Notice how the first set of coordinates and last set of coordinates in the polygon are the same (as highlighted in the code block). This is a closed polygonal figure. Every “Point” object of a polygon can be of the form of (lat, lng) or (lng, lat). The latter is usually a Geo-JSON representation of the polygon, since the Geo-JSON specification requires longitudes to appear first in the Point object. The shapely polygon object needs to be extracted from the WKT, and the WKT is an attribute of the shapely polygon as demonstrated below: The loads function parses out and builds a shapely polygon from its WKT representation. I’ve taken a H3 Hexagon’s own WKT here, but you can get a WKT of pretty much any polygon. Another point to note is that the shape has no reference to a map. This is because we need a base map to plot our polygons on, as a layer. Let’s take a geofence of an entire city, say Dubai, UAE and see what the Multi-polygon object looks like. I’ll be using the GADM database to extract the UAE country’s Geo-Package. In this way, we’ll be able to view an entire city/district as a geometrical shape. We’ll process the Geo-Package and output the Multi-Polygon for sector 3, Dubai as shown below: It is a “multi-polygon” because it contains a list of polygons, as shown in the world islands off the shore of Dubai where each island is its own polygon. Below is an example of a Geo-JSON file, which can be another useful form to represent geofences. Note again how the first and last coordinates of the list are the same. { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [ 55.07652282714844, 25.11731056144692 ], [ 55.15205383300781, 25.055745117015316 ], [ 55.223464965820305, 25.112958466940725 ], [ 55.15068054199219, 25.18070920440447 ], [ 55.07652282714844, 25.11731056144692 ] ] ] } } ]} A Geo-JSON file is a standard JSON file with special key names that help certain frameworks understand the nature of the data being passed. The Geo-JSON specification defines a list of Features called a Feature Collection, and in this case, the feature is of type Polygon. The properties dictionary can be populated with custom data and may be useful to provide attributes for different feature IDs. Say for example, if you wanted to store the population per polygon of a city, then properties is where you can save that information. It is an extension of your polygon that allows each polygon/feature to carry relevant information specific to itself for later analysis. You can use geojson.io, or any GIS tool/software to create custom geo-fences by drawing out your own shapes. Defining zones allow us to construct choropleth maps (maps with zonal coloring). The Plotly graphing libary has native choropleth support using Geo-JSON files. Kepler natively supports H3 visualizations by using just the indices of H3 hexagons from the data. Now we know what we need to deal with the elephant in the room. How can we reconcile geofences with H3? We poly-fill the entire boundary with specific resolution hexagons (resolution 10 in our case). H3 has capabilities to poly-fill both Shapely Polygons and Geo-JSON objects. The output of this data-frame visualized from Uber’s Kepler.GL below with different resolutions. Looks like a retro 16-bit city to me (ba dum tss). Now that we have our hexagons populated across a city, and we have each hexagon’s ID stored in a table/data-frame, We can perform any H3 related function on each hexagon (Find its parent for a more aggregate analysis, store its geo-fence, find its neighboring hexes, etc)We can track coordinate level data grouped by their respective hexagons. In this case, hexagons become buckets which we can use to perform grouped analysis on a set of coordinate points per bucket/hex We can perform any H3 related function on each hexagon (Find its parent for a more aggregate analysis, store its geo-fence, find its neighboring hexes, etc) We can track coordinate level data grouped by their respective hexagons. In this case, hexagons become buckets which we can use to perform grouped analysis on a set of coordinate points per bucket/hex Some non-exhaustive ways to fully utilize H3 would be: Using it as an “on/off” indicator to highlight activity in a particular region. Remember that H3 hexagons can be of different resolutions so you can go as granular as you want or aggregate it upwards to lower resolutions.View time series data by analyzing the evolution of hexagons over a time frame. Each hexagon is representative of the neighborhood of a number of coordinates that reside within its boundaries.Clustering areas with specific levels of activity. Using it as an “on/off” indicator to highlight activity in a particular region. Remember that H3 hexagons can be of different resolutions so you can go as granular as you want or aggregate it upwards to lower resolutions. View time series data by analyzing the evolution of hexagons over a time frame. Each hexagon is representative of the neighborhood of a number of coordinates that reside within its boundaries. Clustering areas with specific levels of activity. The rest is up to you ;) Thanks for reading! A few more links: Uber Open Source: Engineering Sub-City Geos for a Hyper-Local Marketplace with Uber Veritasium’s “The Infinite Pattern That Never Repeats” References: Uber Engineering Blog: H3: Uber’s Hexagonal Hierarchical Spatial Index
[ { "code": null, "e": 463, "s": 47, "text": "If you’ve ever played Civilization VI or Settlers of Catan, you might have noticed that the board map is shaped into regular hexagons. This is a famed game design technique called Hex Map and is used in board games such as Hexagonal chess and video games such as Forge of Empires. This is a natural feature of the game because these maps bring in a lot of advantages for gameplay, especially in movement and tiling." }, { "code": null, "e": 682, "s": 463, "text": "What if this design could prove useful in the real world if we re-modelled our own maps with a layer of hexagons? Perhaps we can find some actual business problems that could be solved with such a model. Enter Uber H3." }, { "code": null, "e": 869, "s": 682, "text": "Currently there exist a number of ways to analyze data related to maps. One of the most rudimentary ways is to plot a list of co-ordinates and see where the densities and clusters arise." }, { "code": null, "e": 1068, "s": 869, "text": "Analyzing individual points has certain drawbacks. There is no clear form of classification for points within a certain area and the analysis we often wish to carry out may be area-wise or regional." }, { "code": null, "e": 1665, "s": 1068, "text": "It would help if we had a grid system where points could be contained within a certain fence and we analyze the behavior of the grid itself as representing the behavior of all points underneath. This means each grid represents the data of the points beneath it. Another issue is that when using points directly, while useful for humans to see the map and notice where the data is bunching up may be computationally a bit more expensive for a computer system. A computer needs to calculate distances of neighboring points to group them together to gather the same visual insights as a human being." }, { "code": null, "e": 1912, "s": 1665, "text": "However, coordinate points are as granular as you can go with respect to geolocation data so don’t dismiss them just yet. We simply need to find a grid framework around which we, or a computer can view geospatial data and derive insights from it." }, { "code": null, "e": 2559, "s": 1912, "text": "A common form of using a grid system more locally is to define zones in cities, by drawing out a shape over a neighborhood, city, district or country. Administrative and political boundaries while useful to section the geospatial analysis into realistic areas may still be problematic in a number of ways. Some zones may be larger than other zones within a city, and there could be overlaps between two or more zones. Furthermore, from a mathematical/absolute perspective, defining zones in this form are highly arbitrary. Zones or districts may be defined based on natural features, population, economy, etc. and are subject to change over time." }, { "code": null, "e": 2951, "s": 2559, "text": "An absolute method of using uniform grid systems is to cover a the Earth with repeated tiling. Assuming that we want to tile our plane regularly and completely, we need to choose the shape that acts as a building block facilitating the complete tiling. This shape needs to be closed and uniformly repeating. Our candidates are the triangle (3 sides), square (4 sides), and hexagon (6 sides)." }, { "code": null, "e": 3143, "s": 2951, "text": "There is no right answer here, so choosing one of these depends on your use-case. At Uber, one of the most in-demand use-cases we have is to determine distances for both rides and deliveries." }, { "code": null, "e": 3437, "s": 3143, "text": "Using a hexagon as the cell shape is critical for H3. Hexagons have only one distance between a hexagon’s center-point and its neighbors’, compared to two distances for squares or three distances for triangles. This property greatly simplifies performing analysis and smoothing over gradients." }, { "code": null, "e": 3561, "s": 3437, "text": "Besides distances, it is generally a good idea to choose a hexagon as the base shape because Hexagons are the Bestagons! ;)" }, { "code": null, "e": 4077, "s": 3561, "text": "H3 is an open source framework developed by Uber in the C Programming Language. At its core, H3 is a geospatial analysis tool that provides a hexagonal, hierarchical spatial index to gain insights from large geospatial datasets. The building blocks of H3 are different sized regular hexagonal polygons. These polygons are spread out over the entire projection of the earth map from pole to pole. This means that any location on the planet can be attributed to a H3 Hexagon down to a precision of 0.0000009 km2 area." }, { "code": null, "e": 4373, "s": 4077, "text": "Imagine it as a layer over the planet where each unit of the layer is a hexagon and each hexagon has a unique ID and can very quickly perform geospatial calculations. Each H3 hexagon can be thought of as its own object and each object can be accessed in a very short amount of time given its ID." }, { "code": null, "e": 4972, "s": 4373, "text": "A core strength of H3 is that it covers the entire world with different sized hexagons. This means that the resolution of the layer can be adjusted based on the problem being solved, like scaling the entire grid up and down. H3 contains a total of 16 resolutions as described in the table below, and each resolution has a certain number of hexagons that span the entire earth as a layer ranging from 122 hexagons in the highest layer and about 500 trillion hexagons at the lowest layer. Each layer consists of a more granular level of hexagons and each hexagon of every layer has its own unique ID." }, { "code": null, "e": 5536, "s": 4972, "text": "H3 defines its indices via hexadecimal format (16-bits, and therefore 16 resolutions), so a cell resolution can be immediately determined by looking at the ID of the cell. The layered approach of different sized hexagons is what lends H3 its power of “hierarchy”. Every low resolution hexagon contains a set of child hexagons in higher resolutions. Every hexagon of a resolution can have sibling hexagons that share the same set of parent hexagons. The layers in essence define a tree of hexagons with the last layer (resolution) containing 500 trillion siblings." }, { "code": null, "e": 5672, "s": 5536, "text": "It’s worth checking out this notebook. The resolution can be adjusted accordingly and the hexagons can be viewed over the entire earth." }, { "code": null, "e": 5885, "s": 5672, "text": "You can find some examples of using H3 functions directly in the C language here. We’ll be using the H3 library binding with the Python programming language since it relatively easier to analyze data with Python." }, { "code": null, "e": 5900, "s": 5885, "text": "pip install h3" }, { "code": null, "e": 6039, "s": 5900, "text": "Let’s say you had a coordinate point, or even a list of coordinates. You can fetch the H3 index of each point with the following function:" }, { "code": null, "e": 6098, "s": 6039, "text": "h3.geo_to_h3( lat=25.32, lng=55.46, resolution=7)" }, { "code": null, "e": 6177, "s": 6098, "text": "Get the resolution of a H3 index if the index represented in a string is valid" }, { "code": null, "e": 6297, "s": 6177, "text": "h3_result = lambda id_str: h3.h3_get_resolution(id_str) if h3.h3_is_valid(id_str) else Noneh3_result('8843a13687fffff')" }, { "code": null, "e": 6385, "s": 6297, "text": "Let’s try a full fledged function that returns a set of H3 attributes, given a H3 index" }, { "code": null, "e": 6459, "s": 6385, "text": "import h3\nfrom shapely.geometry import Polygon, Point\nimport shapely.wkt\n" }, { "code": null, "e": 6736, "s": 6459, "text": "def output_h3_id_attributes(h3_id):\n return {\n \"co_ordinates\" : h3.h3_to_geo(h3_id), \n \"geo_boundary\" : Polygon(h3.h3_to_geo_boundary(h3_id, geo_json=True)).wkt, \n \"parent\" : h3.h3_to_parent(h3_id), \n \"children\" : h3.h3_to_children(h3_id)\n }\n" }, { "code": null, "e": 6780, "s": 6736, "text": "output_h3_id_attributes('8843acd819fffff')\n" }, { "code": null, "e": 7318, "s": 6780, "text": "{'co_ordinates': (25.311756198253676, 55.24286266589328),\n 'geo_boundary': 'POLYGON ((55.23774694448915 25.31287951583933, 55.23951392798415 25.30858249027833, 55.24462934439571 25.30745909858661, 55.24797838839316 25.31063268305425, 55.24621180412194 25.31493004366226, 55.24109577657453 25.31605348476041, 55.23774694448915 25.31287951583933))',\n 'parent': '8743acd81ffffff',\n 'children': {'8943acd8183ffff',\n '8943acd8187ffff',\n '8943acd818bffff',\n '8943acd818fffff',\n '8943acd8193ffff',\n '8943acd8197ffff',\n '8943acd819bffff'}}" }, { "code": null, "e": 7570, "s": 7318, "text": "Another useful function in H3 is its ability to quickly return an index’s k-nearest neighbors. This means that for k =1, a hexagon’s 1st degree neighbors are returned, and for k = 2, it is second degree neighbors (or neighbors of neighbors) and so on." }, { "code": null, "e": 7651, "s": 7570, "text": "h3_id = \"8843a13687fffff\"h3.k_ring(h3_id,1)h3.k_ring(h3_id,2)h3.k_ring(h3_id,10)" }, { "code": null, "e": 7965, "s": 7651, "text": "Now that we have some absolute methods to define grids over the Earth, it would suit us to begin assigning real-world details to hexagons. This is because despite having been given a H3 index and its centroid coordinate, we don’t have much to go on in terms of the physical location which that hexagon represents." }, { "code": null, "e": 8230, "s": 7965, "text": "One way to extend the power of H3 is to combine it together with Maps APIs that contain on-the-ground information. Common choices include Google Maps API, Mapbox API and Nominatim. These services allow us to assign more useful geographical information per hexagon." }, { "code": null, "e": 8486, "s": 8230, "text": "One common function is reverse geocoding, which is a technique of converting a given coordinate into a physical text address by means of a lookup. Let’s find the reverse geocode result of the centroid of a H3 index using the Google Maps Client for Python." }, { "code": null, "e": 8667, "s": 8486, "text": "If H3 contains different resolution hexagons that span the entire earth, what if you wanted to select a fraction of those hexagons that represented a country, city or neighborhood?" }, { "code": null, "e": 8987, "s": 8667, "text": "The poly-fill function fills a polygon with H3 Hexagons. A geofence is a polygon spread out over a map. Zones in cities, or country shapes can be modelled as geofences. Geofences are often represented by means of Geo-JSON files or Shapely polygons. An example of a shapely polygon’s WKT(well known text representation):" }, { "code": null, "e": 9255, "s": 8987, "text": "POLYGON ((55.13977696520102 25.09805053895709, 55.14002932545401 25.09743871100549, 55.1407574981263 25.0972787358399, 55.14123332293791 25.09773058763684, 55.14098097073993 25.09834242241949, 55.14025278567518 25.09850239857415, 55.13977696520102 25.09805053895709))" }, { "code": null, "e": 9510, "s": 9255, "text": "A WKT is, as the name implies, a textual representation of the polygon’s vertex points. Notice how the first set of coordinates and last set of coordinates in the polygon are the same (as highlighted in the code block). This is a closed polygonal figure." }, { "code": null, "e": 9746, "s": 9510, "text": "Every “Point” object of a polygon can be of the form of (lat, lng) or (lng, lat). The latter is usually a Geo-JSON representation of the polygon, since the Geo-JSON specification requires longitudes to appear first in the Point object." }, { "code": null, "e": 9883, "s": 9746, "text": "The shapely polygon object needs to be extracted from the WKT, and the WKT is an attribute of the shapely polygon as demonstrated below:" }, { "code": null, "e": 9971, "s": 9883, "text": "The loads function parses out and builds a shapely polygon from its WKT representation." }, { "code": null, "e": 10200, "s": 9971, "text": "I’ve taken a H3 Hexagon’s own WKT here, but you can get a WKT of pretty much any polygon. Another point to note is that the shape has no reference to a map. This is because we need a base map to plot our polygons on, as a layer." }, { "code": null, "e": 10558, "s": 10200, "text": "Let’s take a geofence of an entire city, say Dubai, UAE and see what the Multi-polygon object looks like. I’ll be using the GADM database to extract the UAE country’s Geo-Package. In this way, we’ll be able to view an entire city/district as a geometrical shape. We’ll process the Geo-Package and output the Multi-Polygon for sector 3, Dubai as shown below:" }, { "code": null, "e": 10713, "s": 10558, "text": "It is a “multi-polygon” because it contains a list of polygons, as shown in the world islands off the shore of Dubai where each island is its own polygon." }, { "code": null, "e": 10882, "s": 10713, "text": "Below is an example of a Geo-JSON file, which can be another useful form to represent geofences. Note again how the first and last coordinates of the list are the same." }, { "code": null, "e": 11549, "s": 10882, "text": "{ \"type\": \"FeatureCollection\", \"features\": [ { \"type\": \"Feature\", \"properties\": {}, \"geometry\": { \"type\": \"Polygon\", \"coordinates\": [ [ [ 55.07652282714844, 25.11731056144692 ], [ 55.15205383300781, 25.055745117015316 ], [ 55.223464965820305, 25.112958466940725 ], [ 55.15068054199219, 25.18070920440447 ], [ 55.07652282714844, 25.11731056144692 ] ] ] } } ]}" }, { "code": null, "e": 12220, "s": 11549, "text": "A Geo-JSON file is a standard JSON file with special key names that help certain frameworks understand the nature of the data being passed. The Geo-JSON specification defines a list of Features called a Feature Collection, and in this case, the feature is of type Polygon. The properties dictionary can be populated with custom data and may be useful to provide attributes for different feature IDs. Say for example, if you wanted to store the population per polygon of a city, then properties is where you can save that information. It is an extension of your polygon that allows each polygon/feature to carry relevant information specific to itself for later analysis." }, { "code": null, "e": 12329, "s": 12220, "text": "You can use geojson.io, or any GIS tool/software to create custom geo-fences by drawing out your own shapes." }, { "code": null, "e": 12588, "s": 12329, "text": "Defining zones allow us to construct choropleth maps (maps with zonal coloring). The Plotly graphing libary has native choropleth support using Geo-JSON files. Kepler natively supports H3 visualizations by using just the indices of H3 hexagons from the data." }, { "code": null, "e": 12865, "s": 12588, "text": "Now we know what we need to deal with the elephant in the room. How can we reconcile geofences with H3? We poly-fill the entire boundary with specific resolution hexagons (resolution 10 in our case). H3 has capabilities to poly-fill both Shapely Polygons and Geo-JSON objects." }, { "code": null, "e": 12962, "s": 12865, "text": "The output of this data-frame visualized from Uber’s Kepler.GL below with different resolutions." }, { "code": null, "e": 13013, "s": 12962, "text": "Looks like a retro 16-bit city to me (ba dum tss)." }, { "code": null, "e": 13128, "s": 13013, "text": "Now that we have our hexagons populated across a city, and we have each hexagon’s ID stored in a table/data-frame," }, { "code": null, "e": 13485, "s": 13128, "text": "We can perform any H3 related function on each hexagon (Find its parent for a more aggregate analysis, store its geo-fence, find its neighboring hexes, etc)We can track coordinate level data grouped by their respective hexagons. In this case, hexagons become buckets which we can use to perform grouped analysis on a set of coordinate points per bucket/hex" }, { "code": null, "e": 13642, "s": 13485, "text": "We can perform any H3 related function on each hexagon (Find its parent for a more aggregate analysis, store its geo-fence, find its neighboring hexes, etc)" }, { "code": null, "e": 13843, "s": 13642, "text": "We can track coordinate level data grouped by their respective hexagons. In this case, hexagons become buckets which we can use to perform grouped analysis on a set of coordinate points per bucket/hex" }, { "code": null, "e": 13898, "s": 13843, "text": "Some non-exhaustive ways to fully utilize H3 would be:" }, { "code": null, "e": 14362, "s": 13898, "text": "Using it as an “on/off” indicator to highlight activity in a particular region. Remember that H3 hexagons can be of different resolutions so you can go as granular as you want or aggregate it upwards to lower resolutions.View time series data by analyzing the evolution of hexagons over a time frame. Each hexagon is representative of the neighborhood of a number of coordinates that reside within its boundaries.Clustering areas with specific levels of activity." }, { "code": null, "e": 14584, "s": 14362, "text": "Using it as an “on/off” indicator to highlight activity in a particular region. Remember that H3 hexagons can be of different resolutions so you can go as granular as you want or aggregate it upwards to lower resolutions." }, { "code": null, "e": 14777, "s": 14584, "text": "View time series data by analyzing the evolution of hexagons over a time frame. Each hexagon is representative of the neighborhood of a number of coordinates that reside within its boundaries." }, { "code": null, "e": 14828, "s": 14777, "text": "Clustering areas with specific levels of activity." }, { "code": null, "e": 14853, "s": 14828, "text": "The rest is up to you ;)" }, { "code": null, "e": 14873, "s": 14853, "text": "Thanks for reading!" }, { "code": null, "e": 14891, "s": 14873, "text": "A few more links:" }, { "code": null, "e": 14975, "s": 14891, "text": "Uber Open Source: Engineering Sub-City Geos for a Hyper-Local Marketplace with Uber" }, { "code": null, "e": 15030, "s": 14975, "text": "Veritasium’s “The Infinite Pattern That Never Repeats”" }, { "code": null, "e": 15042, "s": 15030, "text": "References:" } ]
How to access a function property as a method in JavaScript?
A javascript object is made up of properties. To access a property as a method, just define a function to a property and include other properties in that function. In the following example an object called "employee" is created with properties "fullName", "lastName" , "firstName" and "id". A function is defined under property "fullName" and properties such as "firstName" and "lastName" were included in it. So when the property "fullName" is called, the full name of the employee is going to display as shown in the output. Live Demo <html> <body> <script type="text/javascript"> var employee = { firstName: "raju", lastName : "nayak", Designation : "Engineer", fullName : function() { return this.firstName + " " + this.lastName; } }; document.write(employee.fullName()); </script> </body> </html> raju nayak Live Demo <html> <body> <script type="text/javascript"> var student= { Name: "susan", country : "USA", RollNo : "5", details : function() { return "the student named" + " " + this.Name + " " +"is allocated with rollno " + " " + this.RollNo ; } }; document.write(student.details()); </script> </body> </html> the student named susan is allocated with rollno 5
[ { "code": null, "e": 1227, "s": 1062, "text": " A javascript object is made up of properties. To access a property as a method, just define a function to a property and include other properties in that function." }, { "code": null, "e": 1590, "s": 1227, "text": "In the following example an object called \"employee\" is created with properties \"fullName\", \"lastName\" , \"firstName\" and \"id\". A function is defined under property \"fullName\" and properties such as \"firstName\" and \"lastName\" were included in it. So when the property \"fullName\" is called, the full name of the employee is going to display as shown in the output." }, { "code": null, "e": 1600, "s": 1590, "text": "Live Demo" }, { "code": null, "e": 1913, "s": 1600, "text": "<html>\n<body>\n<script type=\"text/javascript\">\n var employee = {\n firstName: \"raju\",\n lastName : \"nayak\",\n Designation : \"Engineer\",\n fullName : function() {\n return this.firstName + \" \" + this.lastName;\n }\n };\n document.write(employee.fullName());\n</script>\n</body>\n</html>" }, { "code": null, "e": 1924, "s": 1913, "text": "raju nayak" }, { "code": null, "e": 1934, "s": 1924, "text": "Live Demo" }, { "code": null, "e": 2293, "s": 1934, "text": "<html>\n<body>\n<script type=\"text/javascript\">\n var student= {\n Name: \"susan\",\n country : \"USA\",\n RollNo : \"5\",\n details : function() {\n return \"the student named\" + \" \" + this.Name + \" \" +\"is allocated with rollno \" + \" \" + this.RollNo ;\n }\n };\n document.write(student.details());\n</script>\n</body>\n</html>" }, { "code": null, "e": 2344, "s": 2293, "text": "the student named susan is allocated with rollno 5" } ]
Context free languages and Push-down automata - GeeksforGeeks
21 Jan, 2014 NDPDA can handle languages or grammars with ambiguity, but DPDA cannot handle languages with ambiguity and any context-free grammar. S → AB A → 0A|ε B → 1B|ε S → AB A → 0A|ε B → 1B|ε L1 = { | m, n >= 0 } L2 = { | i, j, k >= 0 } For each occurrence of ‘0’ , we PUSH X in the stack. When ‘2’ appears, no stack operation is performed. But, state of the automata is changed. For each occurrence of ‘1’ , we POP X from the stack. If at the end Z0 is on the stack top then input string is accepted When ‘0’ appears in the input string , we replace it with X .Then, traverse to the rightmost corner and replace ‘1’ with Y. We go back to the leftmost ‘0’ and repeat the above process. While traversing rightwards from the beginning of the input string, if after X, ‘2’ appears and after ‘2’, Y appears then we reach the HALT state. Thus, the given language is recursive. Every recursive language is a CFL. Thus, option (B) is the answer. Please comment below if you find anything wrong in the above post. S --> aB S --> bA B --> b A --> a B --> bS A --> aS B --> aBB A --> bAA S --> aB S --> bA B --> b A --> a B --> bS A --> aS B --> aBB A --> bAA S -> aB [Using S --> aB] -> aaBB [Using B --> aBB] -> aabB [Using B --> b] -> aabbS [Using B --> bS] -> aabbaB [Using S --> aB] -> aabbab [Using B --> b] Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies Axios in React: A Guide for Beginners BigInt (BIG INTEGERS) in C++ with Example How to Install Flutter on Visual Studio Code? How to calculate MOVING AVERAGE in a Pandas DataFrame? Retrofit with Kotlin Coroutine in Android Get Hired With GeeksforGeeks and Win Exciting Rewards! How to insert a pandas DataFrame to an existing PostgreSQL table? Difference between sh and bash
[ { "code": null, "e": 29810, "s": 29782, "text": "\n21 Jan, 2014" }, { "code": null, "e": 29943, "s": 29810, "text": "NDPDA can handle languages or grammars with ambiguity, but DPDA cannot handle languages with ambiguity and any context-free grammar." }, { "code": null, "e": 30000, "s": 29951, "text": " S → AB\n A → 0A|ε\n B → 1B|ε" }, { "code": null, "e": 30049, "s": 30000, "text": " S → AB\n A → 0A|ε\n B → 1B|ε" }, { "code": null, "e": 30094, "s": 30049, "text": "L1 = { | m, n >= 0 }\nL2 = { | i, j, k >= 0 }" }, { "code": null, "e": 30147, "s": 30094, "text": "For each occurrence of ‘0’ , we PUSH X in the stack." }, { "code": null, "e": 30237, "s": 30147, "text": "When ‘2’ appears, no stack operation is performed. But, state of the automata is changed." }, { "code": null, "e": 30291, "s": 30237, "text": "For each occurrence of ‘1’ , we POP X from the stack." }, { "code": null, "e": 30358, "s": 30291, "text": "If at the end Z0 is on the stack top then input string is accepted" }, { "code": null, "e": 30482, "s": 30358, "text": "When ‘0’ appears in the input string , we replace it with X .Then, traverse to the rightmost corner and replace ‘1’ with Y." }, { "code": null, "e": 30543, "s": 30482, "text": "We go back to the leftmost ‘0’ and repeat the above process." }, { "code": null, "e": 30863, "s": 30543, "text": "While traversing rightwards from the beginning of the input string, if after X, ‘2’ appears and after ‘2’, Y appears then we reach the HALT state.\nThus, the given language is recursive. Every recursive language is a CFL.\nThus, option (B) is the answer.\nPlease comment below if you find anything wrong in the above post." }, { "code": null, "e": 30963, "s": 30863, "text": "S --> aB S --> bA\nB --> b A --> a\nB --> bS A --> aS\nB --> aBB A --> bAA" }, { "code": null, "e": 31063, "s": 30963, "text": "S --> aB S --> bA\nB --> b A --> a\nB --> bS A --> aS\nB --> aBB A --> bAA" }, { "code": null, "e": 31249, "s": 31063, "text": "S -> aB [Using S --> aB] \n -> aaBB [Using B --> aBB]\n -> aabB [Using B --> b]\n -> aabbS [Using B --> bS]\n -> aabbaB [Using S --> aB]\n -> aabbab [Using B --> b]" }, { "code": null, "e": 31347, "s": 31249, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 31379, "s": 31347, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 31432, "s": 31379, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 31470, "s": 31432, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 31512, "s": 31470, "text": "BigInt (BIG INTEGERS) in C++ with Example" }, { "code": null, "e": 31558, "s": 31512, "text": "How to Install Flutter on Visual Studio Code?" }, { "code": null, "e": 31613, "s": 31558, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 31655, "s": 31613, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 31710, "s": 31655, "text": "Get Hired With GeeksforGeeks and Win Exciting Rewards!" }, { "code": null, "e": 31776, "s": 31710, "text": "How to insert a pandas DataFrame to an existing PostgreSQL table?" } ]
Yii - Sessions
Sessions make data accessible across various pages. A session creates a file on the server in a temporary directory where all session variables are stored. This data is available to all the pages of your web site during the visit of that particular user. When a session starts, the following happens − PHP creates a unique ID for that particular session. PHP creates a unique ID for that particular session. A cookie called PHPSESSID is sent on the client side (to the browser). A cookie called PHPSESSID is sent on the client side (to the browser). The server creates a file in the temporary folder where all session variables are saved. The server creates a file in the temporary folder where all session variables are saved. When a server wants to retrieve the value from a session variable, PHP automatically gets the unique session ID from the PHPSESSID cookie. Then, it looks in its temporary directory for the needed file. When a server wants to retrieve the value from a session variable, PHP automatically gets the unique session ID from the PHPSESSID cookie. Then, it looks in its temporary directory for the needed file. To start a session, you should call the session_start() function. All session variables are stored in the $_SESSION global variable. You can also use the isset() function to check whether the session variable is set − <?php session_start(); if( isset( $_SESSION['number'] ) ) { $_SESSION['number'] += 1; }else { $_SESSION['number'] = 1; } $msg = "This page was visited ". $_SESSION['number']; $msg .= "in this session."; echo $msg; ?> To destroy a session, you should call the session_destroy() function. To destroy a single session variable, call the unset() function − <?php unset($_SESSION['number']); session_destroy(); ?> Sessions allow data to be persisted across user requests. In PHP, you may access them through the $_SESSION variable. In Yii, you can get access to sessions via the session application component. Step 1 − Add the actionOpenAndCloseSession method to the SiteController. public function actionOpenAndCloseSession() { $session = Yii::$app->session; // open a session $session->open(); // check if a session is already opened if ($session->isActive) echo "session is active"; // close a session $session->close(); // destroys all data registered to a session $session->destroy(); } In the above code, we get the session application component, open a session, check whether it is active, close the session, and finally destroy it. Step 2 − Type http://localhost:8080/index.php?r=site/open-and-close-session in the address bar of the web browser, you will see the following. To access session variables, you may use set() and get() methods. Step 3 − Add an actionAccessSession method to the SiteController. public function actionAccessSession() { $session = Yii::$app->session; // set a session variable $session->set('language', 'ru-RU'); // get a session variable $language = $session->get('language'); var_dump($language); // remove a session variable $session->remove('language'); // check if a session variable exists if (!$session->has('language')) echo "language is not set"; $session['captcha'] = [ 'value' => 'aSBS23', 'lifetime' => 7200, ]; var_dump($session['captcha']); } Step 4 − Go to http://localhost:8080/index.php?r=site/access-session, you will see the following. Print Add Notes Bookmark this page
[ { "code": null, "e": 3088, "s": 2833, "text": "Sessions make data accessible across various pages. A session creates a file on the server in a temporary directory where all session variables are stored. This data is available to all the pages of your web site during the visit of that particular user." }, { "code": null, "e": 3135, "s": 3088, "text": "When a session starts, the following happens −" }, { "code": null, "e": 3188, "s": 3135, "text": "PHP creates a unique ID for that particular session." }, { "code": null, "e": 3241, "s": 3188, "text": "PHP creates a unique ID for that particular session." }, { "code": null, "e": 3312, "s": 3241, "text": "A cookie called PHPSESSID is sent on the client side (to the browser)." }, { "code": null, "e": 3383, "s": 3312, "text": "A cookie called PHPSESSID is sent on the client side (to the browser)." }, { "code": null, "e": 3472, "s": 3383, "text": "The server creates a file in the temporary folder where all session variables are saved." }, { "code": null, "e": 3561, "s": 3472, "text": "The server creates a file in the temporary folder where all session variables are saved." }, { "code": null, "e": 3763, "s": 3561, "text": "When a server wants to retrieve the value from a session variable, PHP automatically gets the unique session ID from the PHPSESSID cookie. Then, it looks in its temporary directory for the needed file." }, { "code": null, "e": 3965, "s": 3763, "text": "When a server wants to retrieve the value from a session variable, PHP automatically gets the unique session ID from the PHPSESSID cookie. Then, it looks in its temporary directory for the needed file." }, { "code": null, "e": 4183, "s": 3965, "text": "To start a session, you should call the session_start() function. All session variables are stored in the $_SESSION global variable. You can also use the isset() function to check whether the session variable is set −" }, { "code": null, "e": 4434, "s": 4183, "text": "<?php\n session_start();\n if( isset( $_SESSION['number'] ) ) {\n $_SESSION['number'] += 1;\n }else {\n $_SESSION['number'] = 1;\n }\n $msg = \"This page was visited \". $_SESSION['number'];\n $msg .= \"in this session.\";\n echo $msg;\n?>" }, { "code": null, "e": 4570, "s": 4434, "text": "To destroy a session, you should call the session_destroy() function. To destroy a single session variable, call the unset() function −" }, { "code": null, "e": 4632, "s": 4570, "text": "<?php\n unset($_SESSION['number']);\n session_destroy();\n?>" }, { "code": null, "e": 4828, "s": 4632, "text": "Sessions allow data to be persisted across user requests. In PHP, you may access them through the $_SESSION variable. In Yii, you can get access to sessions via the session application component." }, { "code": null, "e": 4901, "s": 4828, "text": "Step 1 − Add the actionOpenAndCloseSession method to the SiteController." }, { "code": null, "e": 5237, "s": 4901, "text": "public function actionOpenAndCloseSession() {\n $session = Yii::$app->session;\n // open a session\n $session->open();\n // check if a session is already opened\n if ($session->isActive) echo \"session is active\";\n // close a session\n $session->close();\n // destroys all data registered to a session\n $session->destroy();\n}" }, { "code": null, "e": 5385, "s": 5237, "text": "In the above code, we get the session application component, open a session, check whether it is active, close the session, and finally destroy it." }, { "code": null, "e": 5528, "s": 5385, "text": "Step 2 − Type http://localhost:8080/index.php?r=site/open-and-close-session in the address bar of the web browser, you will see the following." }, { "code": null, "e": 5594, "s": 5528, "text": "To access session variables, you may use set() and get() methods." }, { "code": null, "e": 5660, "s": 5594, "text": "Step 3 − Add an actionAccessSession method to the SiteController." }, { "code": null, "e": 6208, "s": 5660, "text": "public function actionAccessSession() {\n\n $session = Yii::$app->session;\n\t\n // set a session variable\n $session->set('language', 'ru-RU');\n\t\n // get a session variable\n $language = $session->get('language');\n var_dump($language);\n\t\t \n // remove a session variable\n $session->remove('language');\n\t\t \n // check if a session variable exists\n if (!$session->has('language')) echo \"language is not set\";\n\t\t \n $session['captcha'] = [\n 'value' => 'aSBS23',\n 'lifetime' => 7200,\n ];\n var_dump($session['captcha']);\n}" }, { "code": null, "e": 6306, "s": 6208, "text": "Step 4 − Go to http://localhost:8080/index.php?r=site/access-session, you will see the following." }, { "code": null, "e": 6313, "s": 6306, "text": " Print" }, { "code": null, "e": 6324, "s": 6313, "text": " Add Notes" } ]
HTML Class Attribute
The class attribute in HTML is used to set one or more classnames for an element. With the specified class name you can work it through CSS and point in a stylesheet. Let us now see an example to implement the class attribute in HTML − Live Demo <!DOCTYPE html> <html> <head> <style> h2.demo { color: orange; background-color: black; } </style> </head> <body> <h1>Resources</h1> <h2 class="demo">Text Tutorials</h1> <h2 class="demo">Video Tutorials</h1> <h2 class="demo">Interview Questions and Answers</h1> <h2 class="demo">Online Quiz</h1> </body> </html> In the above example, we have set a class name for the element <h2> − <h2 class="demo">Text Tutorials</h1> <h2 class="demo">Video Tutorials</h1> This is set with a style to update the text as well as background color of the <h2> element − h2.demo { color: orange; background-color: black; }
[ { "code": null, "e": 1229, "s": 1062, "text": "The class attribute in HTML is used to set one or more classnames for an element. With the specified class name you can work it through CSS and point in a stylesheet." }, { "code": null, "e": 1298, "s": 1229, "text": "Let us now see an example to implement the class attribute in HTML −" }, { "code": null, "e": 1309, "s": 1298, "text": " Live Demo" }, { "code": null, "e": 1639, "s": 1309, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nh2.demo {\n color: orange;\n background-color: black;\n}\n</style>\n</head>\n<body>\n<h1>Resources</h1>\n <h2 class=\"demo\">Text Tutorials</h1>\n <h2 class=\"demo\">Video Tutorials</h1>\n <h2 class=\"demo\">Interview Questions and Answers</h1>\n <h2 class=\"demo\">Online Quiz</h1>\n</body>\n</html>" }, { "code": null, "e": 1709, "s": 1639, "text": "In the above example, we have set a class name for the element <h2> −" }, { "code": null, "e": 1784, "s": 1709, "text": "<h2 class=\"demo\">Text Tutorials</h1>\n<h2 class=\"demo\">Video Tutorials</h1>" }, { "code": null, "e": 1878, "s": 1784, "text": "This is set with a style to update the text as well as background color of the <h2> element −" }, { "code": null, "e": 1936, "s": 1878, "text": "h2.demo {\n color: orange;\n background-color: black;\n}" } ]
How can I set the row height in Tkinter TreeView?
The treeview widget in Tkinter provides a way to represent the data in a hierarchical structure. With the Treeview widget, we can insert our data in the form of a table. The table can have rows and columns in which we can insert the data instantly. We can also configure the properties of the treeview widget such as its color, size, column width, height, row width & height, etc. To set the row height of the Treeview widget, you can create an instance of ttk themed widget where you can specify the rowheight property. The rowheight property will add internal padding to each row in the table. # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame win=Tk() # Set the size of the tkinter window win.geometry("700x350") s=ttk.Style() s.theme_use('clam') # Add the rowheight s.configure('Treeview', rowheight=40) # Add a Treeview widget tree=ttk.Treeview(win, column=("c1", "c2","c3"), show='headings', height=5) tree.column("# 1",anchor=CENTER) tree.heading("# 1", text="ID") tree.column("# 2", anchor=CENTER) tree.heading("# 2", text="FName") tree.column("# 3", anchor=CENTER) tree.heading("# 3", text="LName") # Insert the data in Treeview widget tree.insert('', 'end',text="1",values=('1', 'Joe','Nash')) tree.insert('', 'end',text="2",values=('2', 'Emily','Mackmohan')) tree.insert('', 'end',text="3",values=('3', 'Estilla','Roffe')) tree.insert('', 'end',text="4",values=('4', 'Percy','Andrews')) tree.insert('', 'end',text="5",values=('5', 'Stephan','Heyward')) tree.pack() win.mainloop() If we run the above code, it will display a window with a table and some data in it. In the given table, each row has an assigned row height.
[ { "code": null, "e": 1311, "s": 1062, "text": "The treeview widget in Tkinter provides a way to represent the data in a hierarchical structure. With the Treeview widget, we can insert our data in the form of a table. The table can have rows and columns in which we can insert the data instantly." }, { "code": null, "e": 1658, "s": 1311, "text": "We can also configure the properties of the treeview widget such as its color, size, column width, height, row width & height, etc. To set the row height of the Treeview widget, you can create an instance of ttk themed widget where you can specify the rowheight property. The rowheight property will add internal padding to each row in the table." }, { "code": null, "e": 2626, "s": 1658, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin=Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\ns=ttk.Style()\ns.theme_use('clam')\n\n# Add the rowheight\ns.configure('Treeview', rowheight=40)\n\n# Add a Treeview widget\ntree=ttk.Treeview(win, column=(\"c1\", \"c2\",\"c3\"), show='headings', height=5)\ntree.column(\"# 1\",anchor=CENTER)\ntree.heading(\"# 1\", text=\"ID\")\ntree.column(\"# 2\", anchor=CENTER)\ntree.heading(\"# 2\", text=\"FName\")\ntree.column(\"# 3\", anchor=CENTER)\ntree.heading(\"# 3\", text=\"LName\")\n\n# Insert the data in Treeview widget\ntree.insert('', 'end',text=\"1\",values=('1', 'Joe','Nash'))\ntree.insert('', 'end',text=\"2\",values=('2', 'Emily','Mackmohan'))\ntree.insert('', 'end',text=\"3\",values=('3', 'Estilla','Roffe'))\ntree.insert('', 'end',text=\"4\",values=('4', 'Percy','Andrews'))\ntree.insert('', 'end',text=\"5\",values=('5', 'Stephan','Heyward'))\n\ntree.pack()\n\nwin.mainloop()" }, { "code": null, "e": 2768, "s": 2626, "text": "If we run the above code, it will display a window with a table and some data in it. In the given table, each row has an assigned row height." } ]
Data Preprocessing, Analysis & Visualization
In the real world, we usually come across lots of raw data which is not fit to be readily processed by machine learning algorithms. We need to preprocess the raw data before it is fed into various machine learning algorithms. This chapter discusses various techniques for preprocessing data in Python machine learning. In this section, let us understand how we preprocess data in Python. Initially, open a file with a .py extension, for example prefoo.py file, in a text editor like notepad. Then, add the following piece of code to this file − import numpy as np from sklearn import preprocessing #We imported a couple of packages. Let's create some sample data and add the line to this file: input_data = np.array([[3, -1.5, 3, -6.4], [0, 3, -1.3, 4.1], [1, 2.3, -2.9, -4.3]]) We are now ready to operate on this data. Data can be preprocessed using several techniques as discussed here − It involves removing the mean from each feature so that it is centered on zero. Mean removal helps in removing any bias from the features. You can use the following code for mean removal − data_standardized = preprocessing.scale(input_data) print "\nMean = ", data_standardized.mean(axis = 0) print "Std deviation = ", data_standardized.std(axis = 0) Now run the following command on the terminal − $ python prefoo.py You can observe the following output − Mean = [ 5.55111512e-17 -3.70074342e-17 0.00000000e+00 -1.85037171e-17] Std deviation = [1. 1. 1. 1.] Observe that in the output, mean is almost 0 and the standard deviation is 1. The values of every feature in a data point can vary between random values. So, it is important to scale them so that this matches specified rules. You can use the following code for scaling − data_scaler = preprocessing.MinMaxScaler(feature_range = (0, 1)) data_scaled = data_scaler.fit_transform(input_data) print "\nMin max scaled data = ", data_scaled Now run the code and you can observe the following output − Min max scaled data = [ [ 1. 0. 1. 0. ] [ 0. 1. 0.27118644 1. ] [ 0.33333333 0.84444444 0. 0.2 ] ] Note that all the values have been scaled between the given range. Normalization involves adjusting the values in the feature vector so as to measure them on a common scale. Here, the values of a feature vector are adjusted so that they sum up to 1. We add the following lines to the prefoo.py file − You can use the following code for normalization − data_normalized = preprocessing.normalize(input_data, norm = 'l1') print "\nL1 normalized data = ", data_normalized Now run the code and you can observe the following output − L1 normalized data = [ [ 0.21582734 -0.10791367 0.21582734 -0.46043165] [ 0. 0.35714286 -0.1547619 0.48809524] [ 0.0952381 0.21904762 -0.27619048 -0.40952381] ] Normalization is used to ensure that data points do not get boosted due to the nature of their features. Binarization is used to convert a numerical feature vector into a Boolean vector. You can use the following code for binarization − data_binarized = preprocessing.Binarizer(threshold=1.4).transform(input_data) print "\nBinarized data =", data_binarized Now run the code and you can observe the following output − Binarized data = [[ 1. 0. 1. 0.] [ 0. 1. 0. 1.] [ 0. 1. 0. 0.] ] This technique is helpful when we have prior knowledge of the data. It may be required to deal with numerical values that are few and scattered, and you may not need to store these values. In such situations you can use One Hot Encoding technique. If the number of distinct values is k, it will transform the feature into a k-dimensional vector where only one value is 1 and all other values are 0. You can use the following code for one hot encoding − encoder = preprocessing.OneHotEncoder() encoder.fit([ [0, 2, 1, 12], [1, 3, 5, 3], [2, 3, 2, 12], [1, 2, 4, 3] ]) encoded_vector = encoder.transform([[2, 3, 5, 3]]).toarray() print "\nEncoded vector =", encoded_vector Now run the code and you can observe the following output − Encoded vector = [[ 0. 0. 1. 0. 1. 0. 0. 0. 1. 1. 0.]] In the example above, let us consider the third feature in each feature vector. The values are 1, 5, 2, and 4. There are four separate values here, which means the one-hot encoded vector will be of length 4. If we want to encode the value 5, it will be a vector [0, 1, 0, 0]. Only one value can be 1 in this vector. The second element is 1, which indicates that the value is 5. In supervised learning, we mostly come across a variety of labels which can be in the form of numbers or words. If they are numbers, then they can be used directly by the algorithm. However, many times, labels need to be in readable form. Hence, the training data is usually labelled with words. Label encoding refers to changing the word labels into numbers so that the algorithms can understand how to work on them. Let us understand in detail how to perform label encoding − Create a new Python file, and import the preprocessing package − from sklearn import preprocessing label_encoder = preprocessing.LabelEncoder() input_classes = ['suzuki', 'ford', 'suzuki', 'toyota', 'ford', 'bmw'] label_encoder.fit(input_classes) print "\nClass mapping:" for i, item in enumerate(label_encoder.classes_): print item, '-->', i Now run the code and you can observe the following output − Class mapping: bmw --> 0 ford --> 1 suzuki --> 2 toyota --> 3 As shown in above output, the words have been changed into 0-indexed numbers. Now, when we deal with a set of labels, we can transform them as follows − labels = ['toyota', 'ford', 'suzuki'] encoded_labels = label_encoder.transform(labels) print "\nLabels =", labels print "Encoded labels =", list(encoded_labels) Now run the code and you can observe the following output − Labels = ['toyota', 'ford', 'suzuki'] Encoded labels = [3, 1, 2] This is efficient than manually maintaining mapping between words and numbers. You can check by transforming numbers back to word labels as shown in the code here − encoded_labels = [3, 2, 0, 2, 1] decoded_labels = label_encoder.inverse_transform(encoded_labels) print "\nEncoded labels =", encoded_labels print "Decoded labels =", list(decoded_labels) Now run the code and you can observe the following output − Encoded labels = [3, 2, 0, 2, 1] Decoded labels = ['toyota', 'suzuki', 'bmw', 'suzuki', 'ford'] From the output, you can observe that the mapping is preserved perfectly. This section discusses data analysis in Python machine learning in detail − We can load the data directly from the UCI Machine Learning repository. Note that here we are using pandas to load the data. We will also use pandas next to explore the data both with descriptive statistics and data visualization. Observe the following code and note that we are specifying the names of each column when loading the data. import pandas data = ‘pima_indians.csv’ names = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', ‘Outcome’] dataset = pandas.read_csv(data, names = names) When you run the code, you can observe that the dataset loads and is ready to be analyzed. Here, we have downloaded the pima_indians.csv file and moved it into our working directory and loaded it using the local file name. Summarizing the data can be done in many ways as follows − Check dimensions of the dataset List the entire data View the statistical summary of all attributes Breakdown of the data by the class variable You can use the following command to check how many instances (rows) and attributes (columns) the data contains with the shape property. print(dataset.shape) Then, for the code that we have discussed, we can see 769 instances and 6 attributes − (769, 6) You can view the entire data and understand its summary − print(dataset.head(20)) This command prints the first 20 rows of the data as shown − Sno Pregnancies Glucose BloodPressure SkinThickness Insulin Outcome 1 6 148 72 35 0 1 2 1 85 66 29 0 0 3 8 183 64 0 0 1 4 1 89 66 23 94 0 5 0 137 40 35 168 1 6 5 116 74 0 0 0 7 3 78 50 32 88 1 8 10 115 0 0 0 0 9 2 197 70 45 543 1 10 8 125 96 0 0 1 11 4 110 92 0 0 0 12 10 168 74 0 0 1 13 10 139 80 0 0 0 14 1 189 60 23 846 1 15 5 166 72 19 175 1 16 7 100 0 0 0 1 17 0 118 84 47 230 1 18 7 107 74 0 0 1 19 1 103 30 38 83 0 You can view the statistical summary of each attribute, which includes the count, unique, top and freq, by using the following command. print(dataset.describe()) The above command gives you the following output that shows the statistical summary of each attribute − Pregnancies Glucose BloodPressur SkinThckns Insulin Outcome count 769 769 769 769 769 769 unique 18 137 48 52 187 3 top 1 100 70 0 0 0 freq 135 17 57 227 374 500 You can also look at the number of instances (rows) that belong to each outcome as an absolute count, using the command shown here − print(dataset.groupby('Outcome').size()) Then you can see the number of outcomes of instances as shown − Outcome 0 500 1 268 Outcome 1 dtype: int64 You can visualize data using two types of plots as shown − Univariate plots to understand each attribute Univariate plots to understand each attribute Multivariate plots to understand the relationships between attributes Multivariate plots to understand the relationships between attributes Univariate plots are plots of each individual variable. Consider a case where the input variables are numeric, and we need to create box and whisker plots of each. You can use the following code for this purpose. import pandas import matplotlib.pyplot as plt data = 'iris_df.csv' names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class'] dataset = pandas.read_csv(data, names=names) dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False) plt.show() You can see the output with a clearer idea of the distribution of the input attributes as shown − You can create a histogram of each input variable to get an idea of the distribution using the commands shown below − #histograms dataset.hist() plt().show() From the output, you can see that two of the input variables have a Gaussian distribution. Thus these plots help in giving an idea about the algorithms that we can use in our program. Multivariate plots help us to understand the interactions between the variables. First, let’s look at scatterplots of all pairs of attributes. This can be helpful to spot structured relationships between input variables. from pandas.plotting import scatter_matrix scatter_matrix(dataset) plt.show() You can observe the output as shown − Observe that in the output there is a diagonal grouping of some pairs of attributes. This indicates a high correlation and a predictable relationship. 168 Lectures 13.5 hours Er. Himanshu Vasishta 64 Lectures 10.5 hours Eduonix Learning Solutions 91 Lectures 10 hours Abhilash Nelson 54 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj 35 Lectures 4 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2623, "s": 2304, "text": "In the real world, we usually come across lots of raw data which is not fit to be readily processed by machine learning algorithms. We need to preprocess the raw data before it is fed into various machine learning algorithms. This chapter discusses various techniques for preprocessing data in Python machine learning." }, { "code": null, "e": 2692, "s": 2623, "text": "In this section, let us understand how we preprocess data in Python." }, { "code": null, "e": 2796, "s": 2692, "text": "Initially, open a file with a .py extension, for example prefoo.py file, in a text editor like notepad." }, { "code": null, "e": 2849, "s": 2796, "text": "Then, add the following piece of code to this file −" }, { "code": null, "e": 3086, "s": 2849, "text": "import numpy as np\n\nfrom sklearn import preprocessing\n\n#We imported a couple of packages. Let's create some sample data and add the line to this file:\n\ninput_data = np.array([[3, -1.5, 3, -6.4], [0, 3, -1.3, 4.1], [1, 2.3, -2.9, -4.3]])" }, { "code": null, "e": 3128, "s": 3086, "text": "We are now ready to operate on this data." }, { "code": null, "e": 3198, "s": 3128, "text": "Data can be preprocessed using several techniques as discussed here −" }, { "code": null, "e": 3337, "s": 3198, "text": "It involves removing the mean from each feature so that it is centered on zero. Mean removal helps in removing any bias from the features." }, { "code": null, "e": 3387, "s": 3337, "text": "You can use the following code for mean removal −" }, { "code": null, "e": 3549, "s": 3387, "text": "data_standardized = preprocessing.scale(input_data)\nprint \"\\nMean = \", data_standardized.mean(axis = 0)\nprint \"Std deviation = \", data_standardized.std(axis = 0)" }, { "code": null, "e": 3597, "s": 3549, "text": "Now run the following command on the terminal −" }, { "code": null, "e": 3617, "s": 3597, "text": "$ python prefoo.py\n" }, { "code": null, "e": 3656, "s": 3617, "text": "You can observe the following output −" }, { "code": null, "e": 3759, "s": 3656, "text": "Mean = [ 5.55111512e-17 -3.70074342e-17 0.00000000e+00 -1.85037171e-17]\nStd deviation = [1. 1. 1. 1.]\n" }, { "code": null, "e": 3837, "s": 3759, "text": "Observe that in the output, mean is almost 0 and the standard deviation is 1." }, { "code": null, "e": 3985, "s": 3837, "text": "The values of every feature in a data point can vary between random values. So, it is important to scale them so that this matches specified rules." }, { "code": null, "e": 4030, "s": 3985, "text": "You can use the following code for scaling −" }, { "code": null, "e": 4194, "s": 4030, "text": "data_scaler = preprocessing.MinMaxScaler(feature_range = (0, 1))\ndata_scaled = data_scaler.fit_transform(input_data)\nprint \"\\nMin max scaled data = \", data_scaled\n" }, { "code": null, "e": 4254, "s": 4194, "text": "Now run the code and you can observe the following output −" }, { "code": null, "e": 4402, "s": 4254, "text": "Min max scaled data = [ [ 1. 0. 1. 0. ]\n [ 0. 1. 0.27118644 1. ]\n [ 0.33333333 0.84444444 0. 0.2 ]\n]\n" }, { "code": null, "e": 4469, "s": 4402, "text": "Note that all the values have been scaled between the given range." }, { "code": null, "e": 4703, "s": 4469, "text": "Normalization involves adjusting the values in the feature vector so as to measure them on a common scale. Here, the values of a feature vector are adjusted so that they sum up to 1. We add the following lines to the prefoo.py file −" }, { "code": null, "e": 4754, "s": 4703, "text": "You can use the following code for normalization −" }, { "code": null, "e": 4872, "s": 4754, "text": "data_normalized = preprocessing.normalize(input_data, norm = 'l1')\nprint \"\\nL1 normalized data = \", data_normalized\n" }, { "code": null, "e": 4932, "s": 4872, "text": "Now run the code and you can observe the following output −" }, { "code": null, "e": 5143, "s": 4932, "text": "L1 normalized data = [ [ 0.21582734 -0.10791367 0.21582734 -0.46043165]\n [ 0. 0.35714286 -0.1547619 0.48809524]\n [ 0.0952381 0.21904762 -0.27619048 -0.40952381]\n]\n" }, { "code": null, "e": 5248, "s": 5143, "text": "Normalization is used to ensure that data points do not get boosted due to the nature of their features." }, { "code": null, "e": 5380, "s": 5248, "text": "Binarization is used to convert a numerical feature vector into a Boolean vector. You can use the following code for binarization −" }, { "code": null, "e": 5502, "s": 5380, "text": "data_binarized = preprocessing.Binarizer(threshold=1.4).transform(input_data)\nprint \"\\nBinarized data =\", data_binarized\n" }, { "code": null, "e": 5562, "s": 5502, "text": "Now run the code and you can observe the following output −" }, { "code": null, "e": 5681, "s": 5562, "text": "Binarized data = [[ 1. 0. 1. 0.]\n [ 0. 1. 0. 1.]\n [ 0. 1. 0. 0.]\n ]\n" }, { "code": null, "e": 5749, "s": 5681, "text": "This technique is helpful when we have prior knowledge of the data." }, { "code": null, "e": 5929, "s": 5749, "text": "It may be required to deal with numerical values that are few and scattered, and you may not need to store these values. In such situations you can use One Hot Encoding technique." }, { "code": null, "e": 6080, "s": 5929, "text": "If the number of distinct values is k, it will transform the feature into a k-dimensional vector where only one value is 1 and all other values are 0." }, { "code": null, "e": 6134, "s": 6080, "text": "You can use the following code for one hot encoding −" }, { "code": null, "e": 6402, "s": 6134, "text": "encoder = preprocessing.OneHotEncoder()\nencoder.fit([ [0, 2, 1, 12], \n [1, 3, 5, 3], \n [2, 3, 2, 12], \n [1, 2, 4, 3]\n])\nencoded_vector = encoder.transform([[2, 3, 5, 3]]).toarray()\nprint \"\\nEncoded vector =\", encoded_vector\n" }, { "code": null, "e": 6462, "s": 6402, "text": "Now run the code and you can observe the following output −" }, { "code": null, "e": 6518, "s": 6462, "text": "Encoded vector = [[ 0. 0. 1. 0. 1. 0. 0. 0. 1. 1. 0.]]\n" }, { "code": null, "e": 6629, "s": 6518, "text": "In the example above, let us consider the third feature in each feature vector. The values are 1, 5, 2, and 4." }, { "code": null, "e": 6896, "s": 6629, "text": "There are four separate values here, which means the one-hot encoded vector will be of length 4. If we want to encode the value 5, it will be a vector [0, 1, 0, 0]. Only one value can be 1 in this vector. The second element is 1, which indicates that the value is 5." }, { "code": null, "e": 7192, "s": 6896, "text": "In supervised learning, we mostly come across a variety of labels which can be in the form of numbers or words. If they are numbers, then they can be used directly by the algorithm. However, many times, labels need to be in readable form. Hence, the training data is usually labelled with words." }, { "code": null, "e": 7374, "s": 7192, "text": "Label encoding refers to changing the word labels into numbers so that the algorithms can understand how to work on them. Let us understand in detail how to perform label encoding −" }, { "code": null, "e": 7439, "s": 7374, "text": "Create a new Python file, and import the preprocessing package −" }, { "code": null, "e": 7717, "s": 7439, "text": "from sklearn import preprocessing\nlabel_encoder = preprocessing.LabelEncoder()\ninput_classes = ['suzuki', 'ford', 'suzuki', 'toyota', 'ford', 'bmw']\nlabel_encoder.fit(input_classes)\nprint \"\\nClass mapping:\"\nfor i, item in enumerate(label_encoder.classes_):\nprint item, '-->', i" }, { "code": null, "e": 7777, "s": 7717, "text": "Now run the code and you can observe the following output −" }, { "code": null, "e": 7840, "s": 7777, "text": "Class mapping:\nbmw --> 0\nford --> 1\nsuzuki --> 2\ntoyota --> 3\n" }, { "code": null, "e": 7993, "s": 7840, "text": "As shown in above output, the words have been changed into 0-indexed numbers. Now, when we deal with a set of labels, we can transform them as follows −" }, { "code": null, "e": 8155, "s": 7993, "text": "labels = ['toyota', 'ford', 'suzuki']\nencoded_labels = label_encoder.transform(labels)\nprint \"\\nLabels =\", labels\nprint \"Encoded labels =\", list(encoded_labels)\n" }, { "code": null, "e": 8215, "s": 8155, "text": "Now run the code and you can observe the following output −" }, { "code": null, "e": 8281, "s": 8215, "text": "Labels = ['toyota', 'ford', 'suzuki']\nEncoded labels = [3, 1, 2]\n" }, { "code": null, "e": 8446, "s": 8281, "text": "This is efficient than manually maintaining mapping between words and numbers. You can check by transforming numbers back to word labels as shown in the code here −" }, { "code": null, "e": 8635, "s": 8446, "text": "encoded_labels = [3, 2, 0, 2, 1]\ndecoded_labels = label_encoder.inverse_transform(encoded_labels)\nprint \"\\nEncoded labels =\", encoded_labels\nprint \"Decoded labels =\", list(decoded_labels)\n" }, { "code": null, "e": 8695, "s": 8635, "text": "Now run the code and you can observe the following output −" }, { "code": null, "e": 8792, "s": 8695, "text": "Encoded labels = [3, 2, 0, 2, 1]\nDecoded labels = ['toyota', 'suzuki', 'bmw', 'suzuki', 'ford']\n" }, { "code": null, "e": 8866, "s": 8792, "text": "From the output, you can observe that the mapping is preserved perfectly." }, { "code": null, "e": 8942, "s": 8866, "text": "This section discusses data analysis in Python machine learning in detail −" }, { "code": null, "e": 9280, "s": 8942, "text": "We can load the data directly from the UCI Machine Learning repository. Note that here we are using pandas to load the data. We will also use pandas next to explore the data both with descriptive statistics and data visualization. Observe the following code and note that we are specifying the names of each column when loading the data." }, { "code": null, "e": 9459, "s": 9280, "text": "import pandas\ndata = ‘pima_indians.csv’\nnames = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', ‘Outcome’]\ndataset = pandas.read_csv(data, names = names)\n" }, { "code": null, "e": 9682, "s": 9459, "text": "When you run the code, you can observe that the dataset loads and is ready to be analyzed. Here, we have downloaded the pima_indians.csv file and moved it into our working directory and loaded it using the local file name." }, { "code": null, "e": 9741, "s": 9682, "text": "Summarizing the data can be done in many ways as follows −" }, { "code": null, "e": 9773, "s": 9741, "text": "Check dimensions of the dataset" }, { "code": null, "e": 9794, "s": 9773, "text": "List the entire data" }, { "code": null, "e": 9841, "s": 9794, "text": "View the statistical summary of all attributes" }, { "code": null, "e": 9885, "s": 9841, "text": "Breakdown of the data by the class variable" }, { "code": null, "e": 10022, "s": 9885, "text": "You can use the following command to check how many instances (rows) and attributes (columns) the data contains with the shape property." }, { "code": null, "e": 10044, "s": 10022, "text": "print(dataset.shape)\n" }, { "code": null, "e": 10131, "s": 10044, "text": "Then, for the code that we have discussed, we can see 769 instances and 6 attributes −" }, { "code": null, "e": 10141, "s": 10131, "text": "(769, 6)\n" }, { "code": null, "e": 10199, "s": 10141, "text": "You can view the entire data and understand its summary −" }, { "code": null, "e": 10224, "s": 10199, "text": "print(dataset.head(20))\n" }, { "code": null, "e": 10285, "s": 10224, "text": "This command prints the first 20 rows of the data as shown −" }, { "code": null, "e": 11589, "s": 10285, "text": "Sno Pregnancies Glucose BloodPressure SkinThickness Insulin Outcome\n1 6 148 72 35 0 1\n2 1 85 66 29 0 0\n3 8 183 64 0 0 1\n4 1 89 66 23 94 0\n5 0 137 40 35 168 1\n6 5 116 74 0 0 0\n7 3 78 50 32 88 1\n8 10 115 0 0 0 0\n9 2 197 70 45 543 1\n10 8 125 96 0 0 1\n11 4 110 92 0 0 0\n12 10 168 74 0 0 1\n13 10 139 80 0 0 0\n14 1 189 60 23 846 1\n15 5 166 72 19 175 1\n16 7 100 0 0 0 1\n17 0 118 84 47 230 1\n18 7 107 74 0 0 1\n19 1 103 30 38 83 0\n" }, { "code": null, "e": 11725, "s": 11589, "text": "You can view the statistical summary of each attribute, which includes the count, unique, top and freq, by using the following command." }, { "code": null, "e": 11752, "s": 11725, "text": "print(dataset.describe())\n" }, { "code": null, "e": 11856, "s": 11752, "text": "The above command gives you the following output that shows the statistical summary of each attribute −" }, { "code": null, "e": 12190, "s": 11856, "text": " Pregnancies Glucose BloodPressur SkinThckns Insulin Outcome\ncount 769 769 769 769 769 769\nunique 18 137 48 52 187 3\ntop 1 100 70 0 0 0\nfreq 135 17 57 227 374 500\n" }, { "code": null, "e": 12323, "s": 12190, "text": "You can also look at the number of instances (rows) that belong to each outcome as an absolute count, using the command shown here −" }, { "code": null, "e": 12365, "s": 12323, "text": "print(dataset.groupby('Outcome').size())\n" }, { "code": null, "e": 12429, "s": 12365, "text": "Then you can see the number of outcomes of instances as shown −" }, { "code": null, "e": 12493, "s": 12429, "text": "Outcome\n0 500\n1 268\nOutcome 1\ndtype: int64\n" }, { "code": null, "e": 12552, "s": 12493, "text": "You can visualize data using two types of plots as shown −" }, { "code": null, "e": 12598, "s": 12552, "text": "Univariate plots to understand each attribute" }, { "code": null, "e": 12644, "s": 12598, "text": "Univariate plots to understand each attribute" }, { "code": null, "e": 12714, "s": 12644, "text": "Multivariate plots to understand the relationships between attributes" }, { "code": null, "e": 12784, "s": 12714, "text": "Multivariate plots to understand the relationships between attributes" }, { "code": null, "e": 12997, "s": 12784, "text": "Univariate plots are plots of each individual variable. Consider a case where the input variables are numeric, and we need to create box and whisker plots of each. You can use the following code for this purpose." }, { "code": null, "e": 13282, "s": 12997, "text": "import pandas\nimport matplotlib.pyplot as plt\ndata = 'iris_df.csv'\nnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']\ndataset = pandas.read_csv(data, names=names)\ndataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)\nplt.show()" }, { "code": null, "e": 13380, "s": 13282, "text": "You can see the output with a clearer idea of the distribution of the input attributes as shown −" }, { "code": null, "e": 13498, "s": 13380, "text": "You can create a histogram of each input variable to get an idea of the distribution using the commands shown below −" }, { "code": null, "e": 13538, "s": 13498, "text": "#histograms\ndataset.hist()\nplt().show()" }, { "code": null, "e": 13722, "s": 13538, "text": "From the output, you can see that two of the input variables have a Gaussian distribution. Thus these plots help in giving an idea about the algorithms that we can use in our program." }, { "code": null, "e": 13803, "s": 13722, "text": "Multivariate plots help us to understand the interactions between the variables." }, { "code": null, "e": 13943, "s": 13803, "text": "First, let’s look at scatterplots of all pairs of attributes. This can be helpful to spot structured relationships between input variables." }, { "code": null, "e": 14022, "s": 13943, "text": "from pandas.plotting import scatter_matrix\nscatter_matrix(dataset)\nplt.show()\n" }, { "code": null, "e": 14060, "s": 14022, "text": "You can observe the output as shown −" }, { "code": null, "e": 14211, "s": 14060, "text": "Observe that in the output there is a diagonal grouping of some pairs of attributes. This indicates a high correlation and a predictable relationship." }, { "code": null, "e": 14248, "s": 14211, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 14271, "s": 14248, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 14307, "s": 14271, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 14335, "s": 14307, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 14369, "s": 14335, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 14386, "s": 14369, "text": " Abhilash Nelson" }, { "code": null, "e": 14419, "s": 14386, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 14441, "s": 14419, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 14474, "s": 14441, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 14496, "s": 14474, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 14529, "s": 14496, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 14551, "s": 14529, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 14558, "s": 14551, "text": " Print" }, { "code": null, "e": 14569, "s": 14558, "text": " Add Notes" } ]
UNPIVOT multiple columns into tidy pairs with BigQuery and a SQL UDF | by Felipe Hoffa | Towards Data Science
Important update: I left Google and joined Snowflake in 2020 — so I’m unable to keep my older posts updated. If you want to try Snowflake, join us — I’m having a lot of fun ❄️. As an example of non-tidy data, we can see how the Novel Coronavirus (COVID-19) Case (provided by JHU CSSE), and the Apple Mobility Trends Reports tables look: We don’t want multiple columns, each for one date. We want to have (date, value) pairs. Since this problem seems so common, I wrote two BigQuery persistent UDFs to solve this: fhoffa.x.unpivot() fhoffa.x.cast_kv_array_to_date_float() Let’s review how they work. Just give unpivot() a full row, and the regex of how the name of each of the columns to unpivot look. With the Apple tables: SELECT a.geo_type, region, transportation_type, unpivottedFROM `fh-bigquery.public_dump.applemobilitytrends_20200414` a , UNNEST(fhoffa.x.unpivot(a, '_2020')) unpivotted With the JHU tables: SELECT province_state, country_region, unpivottedFROM `bigquery-public-data.covid19_jhu_csse.confirmed_cases` a , UNNEST(fhoffa.x.unpivot(a, '_[0-9]')) unpivotted That’s so much better, but we are not done. How do we transform these values into dates and numbers? We can re-cast our unpivotted columns with cast_kv_array_to_date_float(). What’s even more “infuriating” when casting these columns to dates is that they use different formats for encoding dates. You don’t have to worry as the UDF can take the date format as an input too. For example, with the Apple tables: SELECT a.geo_type, region, transportation_type, unpivotted.*FROM `fh-bigquery.public_dump.applemobilitytrends_20200414` a , UNNEST(fhoffa.x.cast_kv_array_to_date_float(fhoffa.x.unpivot(a, '_2020'), '_%Y_%m_%d')) unpivotted And with the JHU tables: SELECT province_state, country_region, unpivotted.*FROM `bigquery-public-data.covid19_jhu_csse.confirmed_cases` a , UNNEST(fhoffa.x.cast_kv_array_to_date_float(fhoffa.x.unpivot(a, '_[0-9]'), '_%m_%d_%y')) unpivotted See? These results look way tidier than the starting tables. Once we have these 2 UDFs, applying them to other tables becomes really easy: SELECT county_fips_code, county_name, state, state_fips_code, unpivotted.*FROM `bigquery-public-data.covid19_usafacts.confirmed_cases` a , UNNEST(fhoffa.x.cast_kv_array_to_date_float(fhoffa.x.unpivot(a, '_[0-9]'), '_%m_%d_%y')) unpivotted Check my previous post about Persistent UDFs in BigQuery: medium.com The source code for these 2 UDFs is: CREATE OR REPLACE FUNCTION fhoffa.x.unpivot(x ANY TYPE, col_regex STRING) AS (( # https://medium.com/@hoffa/how-to-unpivot-multiple-columns-into-tidy-pairs-with-sql-and-bigquery-d9d0e74ce675 SELECT ARRAY_AGG(STRUCT( REGEXP_EXTRACT(y, '[^"]*') AS key , REGEXP_EXTRACT(y, r':([^"]*)\"?[,}\]]') AS value )) FROM UNNEST(( SELECT REGEXP_EXTRACT_ALL(json,col_regex||r'[^:]+:\"?[^"]+\"?') arr FROM (SELECT TO_JSON_STRING(x) json))) y));CREATE OR REPLACE FUNCTION fhoffa.x.cast_kv_array_to_date_float(arr ANY TYPE, date_format STRING) AS (( # https://medium.com/@hoffa/how-to-unpivot-multiple-columns-into-tidy-pairs-with-sql-and-bigquery-d9d0e74ce675 SELECT ARRAY_AGG(STRUCT(SAFE.PARSE_DATE(date_format, key) AS date, SAFE_CAST(value AS FLOAT64) AS value)) FROM UNNEST(arr))); The secret motor behind this function: Transforming a whole row into JSON with TO_JSON_STRING() and then doing a REGEXP_EXTRACT_ALL over it. My previous solution to UNPIVOT in BigQuery has received than 5k views on Stack Overflow: stackoverflow.com Once I write documentation for these functions, and we settle on their definitive name — I’ll submit them to our shared repository with community UDFs (bqutil). github.com Check Google’s public dataset program, featuring an increasing collection of COVID-19 related datasets in BigQuery: cloud.google.com I’m Felipe Hoffa, a Developer Advocate for Google Cloud. Follow me on @felipehoffa, find my previous posts on medium.com/@hoffa, and all about BigQuery on reddit.com/r/bigquery.
[ { "code": null, "e": 349, "s": 172, "text": "Important update: I left Google and joined Snowflake in 2020 — so I’m unable to keep my older posts updated. If you want to try Snowflake, join us — I’m having a lot of fun ❄️." }, { "code": null, "e": 509, "s": 349, "text": "As an example of non-tidy data, we can see how the Novel Coronavirus (COVID-19) Case (provided by JHU CSSE), and the Apple Mobility Trends Reports tables look:" }, { "code": null, "e": 685, "s": 509, "text": "We don’t want multiple columns, each for one date. We want to have (date, value) pairs. Since this problem seems so common, I wrote two BigQuery persistent UDFs to solve this:" }, { "code": null, "e": 704, "s": 685, "text": "fhoffa.x.unpivot()" }, { "code": null, "e": 743, "s": 704, "text": "fhoffa.x.cast_kv_array_to_date_float()" }, { "code": null, "e": 771, "s": 743, "text": "Let’s review how they work." }, { "code": null, "e": 873, "s": 771, "text": "Just give unpivot() a full row, and the regex of how the name of each of the columns to unpivot look." }, { "code": null, "e": 896, "s": 873, "text": "With the Apple tables:" }, { "code": null, "e": 1067, "s": 896, "text": "SELECT a.geo_type, region, transportation_type, unpivottedFROM `fh-bigquery.public_dump.applemobilitytrends_20200414` a , UNNEST(fhoffa.x.unpivot(a, '_2020')) unpivotted" }, { "code": null, "e": 1088, "s": 1067, "text": "With the JHU tables:" }, { "code": null, "e": 1253, "s": 1088, "text": "SELECT province_state, country_region, unpivottedFROM `bigquery-public-data.covid19_jhu_csse.confirmed_cases` a , UNNEST(fhoffa.x.unpivot(a, '_[0-9]')) unpivotted" }, { "code": null, "e": 1354, "s": 1253, "text": "That’s so much better, but we are not done. How do we transform these values into dates and numbers?" }, { "code": null, "e": 1428, "s": 1354, "text": "We can re-cast our unpivotted columns with cast_kv_array_to_date_float()." }, { "code": null, "e": 1627, "s": 1428, "text": "What’s even more “infuriating” when casting these columns to dates is that they use different formats for encoding dates. You don’t have to worry as the UDF can take the date format as an input too." }, { "code": null, "e": 1663, "s": 1627, "text": "For example, with the Apple tables:" }, { "code": null, "e": 1887, "s": 1663, "text": "SELECT a.geo_type, region, transportation_type, unpivotted.*FROM `fh-bigquery.public_dump.applemobilitytrends_20200414` a , UNNEST(fhoffa.x.cast_kv_array_to_date_float(fhoffa.x.unpivot(a, '_2020'), '_%Y_%m_%d')) unpivotted" }, { "code": null, "e": 1912, "s": 1887, "text": "And with the JHU tables:" }, { "code": null, "e": 2130, "s": 1912, "text": "SELECT province_state, country_region, unpivotted.*FROM `bigquery-public-data.covid19_jhu_csse.confirmed_cases` a , UNNEST(fhoffa.x.cast_kv_array_to_date_float(fhoffa.x.unpivot(a, '_[0-9]'), '_%m_%d_%y')) unpivotted" }, { "code": null, "e": 2191, "s": 2130, "text": "See? These results look way tidier than the starting tables." }, { "code": null, "e": 2269, "s": 2191, "text": "Once we have these 2 UDFs, applying them to other tables becomes really easy:" }, { "code": null, "e": 2509, "s": 2269, "text": "SELECT county_fips_code, county_name, state, state_fips_code, unpivotted.*FROM `bigquery-public-data.covid19_usafacts.confirmed_cases` a , UNNEST(fhoffa.x.cast_kv_array_to_date_float(fhoffa.x.unpivot(a, '_[0-9]'), '_%m_%d_%y')) unpivotted" }, { "code": null, "e": 2567, "s": 2509, "text": "Check my previous post about Persistent UDFs in BigQuery:" }, { "code": null, "e": 2578, "s": 2567, "text": "medium.com" }, { "code": null, "e": 2615, "s": 2578, "text": "The source code for these 2 UDFs is:" }, { "code": null, "e": 3408, "s": 2615, "text": "CREATE OR REPLACE FUNCTION fhoffa.x.unpivot(x ANY TYPE, col_regex STRING) AS (( # https://medium.com/@hoffa/how-to-unpivot-multiple-columns-into-tidy-pairs-with-sql-and-bigquery-d9d0e74ce675 SELECT ARRAY_AGG(STRUCT( REGEXP_EXTRACT(y, '[^\"]*') AS key , REGEXP_EXTRACT(y, r':([^\"]*)\\\"?[,}\\]]') AS value )) FROM UNNEST(( SELECT REGEXP_EXTRACT_ALL(json,col_regex||r'[^:]+:\\\"?[^\"]+\\\"?') arr FROM (SELECT TO_JSON_STRING(x) json))) y));CREATE OR REPLACE FUNCTION fhoffa.x.cast_kv_array_to_date_float(arr ANY TYPE, date_format STRING) AS (( # https://medium.com/@hoffa/how-to-unpivot-multiple-columns-into-tidy-pairs-with-sql-and-bigquery-d9d0e74ce675 SELECT ARRAY_AGG(STRUCT(SAFE.PARSE_DATE(date_format, key) AS date, SAFE_CAST(value AS FLOAT64) AS value)) FROM UNNEST(arr)));" }, { "code": null, "e": 3549, "s": 3408, "text": "The secret motor behind this function: Transforming a whole row into JSON with TO_JSON_STRING() and then doing a REGEXP_EXTRACT_ALL over it." }, { "code": null, "e": 3639, "s": 3549, "text": "My previous solution to UNPIVOT in BigQuery has received than 5k views on Stack Overflow:" }, { "code": null, "e": 3657, "s": 3639, "text": "stackoverflow.com" }, { "code": null, "e": 3818, "s": 3657, "text": "Once I write documentation for these functions, and we settle on their definitive name — I’ll submit them to our shared repository with community UDFs (bqutil)." }, { "code": null, "e": 3829, "s": 3818, "text": "github.com" }, { "code": null, "e": 3945, "s": 3829, "text": "Check Google’s public dataset program, featuring an increasing collection of COVID-19 related datasets in BigQuery:" }, { "code": null, "e": 3962, "s": 3945, "text": "cloud.google.com" } ]
Arithmetic operations in excel file using openpyxl in Python
Python can help us use excel files directly from the python environment. We can refer to the each cell or a range of cells in excel and apply arithmetic operators on those cells. The results of those operations can also be stored at some cells whose location can be specified by the python program. In the below examples we are performing various arithmetic operations using inbuilt functions of excel. Like sum or average of numbers inside cells. The results are also stored at specific locations. We use the openpyxl module which opens a workbook and marks it active. Then we store certain values in predefined cells and then apply the functions on those cells storing the result in other cells. import openpyxl excel = openpyxl.Workbook() excel_file = excel.active excel_file['A1'] = 50 excel_file['B1'] = 100 excel_file['C1'] = 150 excel_file['D1'] = 200 excel_file['E1'] = 250 excel_file['A3'] = 20 excel_file['B3'] = 40 excel_file['C3'] = 60 excel_file['D3'] = 80 excel_file['E3'] = 100 excel_file['A5'] = 2 excel_file['B5'] = 4 excel_file['C5'] = 6 excel_file['D5'] = 9 excel_file['E5'] = 15 excel_file['A7'] = 4 excel_file['B7'] = 11 excel_file['C7'] = 27 excel_file['D7'] = 40 excel_file['E7'] = 75 excel_file['F1'] = 'Sum(A1 to E1)' excel_file['G1'] = '= SUM(A1:E1)' excel_file['F3'] = 'Sum(A3 to E3)' excel_file['G3'] = '= AVERAGE(A3:E3)' excel_file['F5'] = 'Product(A5 to E5)' excel_file['G5'] = '= PRODUCT(A5:E5)' excel_file['F7'] = 'Count(A7 to E7)' excel_file['G7'] = '= COUNT(A7:E7)' excel.save("D:\\Arithmetic_operations.xlsx") Running the above code gives us the following result −
[ { "code": null, "e": 1361, "s": 1062, "text": "Python can help us use excel files directly from the python environment. We can refer to the each cell or a range of cells in excel and apply arithmetic operators on those cells. The results of those operations can also be stored at some cells whose location can be specified by the python program." }, { "code": null, "e": 1760, "s": 1361, "text": "In the below examples we are performing various arithmetic operations using inbuilt functions of excel. Like sum or average of numbers inside cells. The results are also stored at specific locations. We use the openpyxl module which opens a workbook and marks it active. Then we store certain values in predefined cells and then apply the functions on those cells storing the result in other cells." }, { "code": null, "e": 2615, "s": 1760, "text": "import openpyxl\n\nexcel = openpyxl.Workbook()\n\nexcel_file = excel.active\n\nexcel_file['A1'] = 50\nexcel_file['B1'] = 100\nexcel_file['C1'] = 150\nexcel_file['D1'] = 200\nexcel_file['E1'] = 250\n\nexcel_file['A3'] = 20\nexcel_file['B3'] = 40\nexcel_file['C3'] = 60\nexcel_file['D3'] = 80\nexcel_file['E3'] = 100\n\nexcel_file['A5'] = 2\nexcel_file['B5'] = 4\nexcel_file['C5'] = 6\nexcel_file['D5'] = 9\nexcel_file['E5'] = 15\n\nexcel_file['A7'] = 4\nexcel_file['B7'] = 11\nexcel_file['C7'] = 27\nexcel_file['D7'] = 40\nexcel_file['E7'] = 75\n\nexcel_file['F1'] = 'Sum(A1 to E1)'\nexcel_file['G1'] = '= SUM(A1:E1)'\nexcel_file['F3'] = 'Sum(A3 to E3)'\nexcel_file['G3'] = '= AVERAGE(A3:E3)'\nexcel_file['F5'] = 'Product(A5 to E5)'\nexcel_file['G5'] = '= PRODUCT(A5:E5)'\nexcel_file['F7'] = 'Count(A7 to E7)'\nexcel_file['G7'] = '= COUNT(A7:E7)'\n\nexcel.save(\"D:\\\\Arithmetic_operations.xlsx\")" }, { "code": null, "e": 2670, "s": 2615, "text": "Running the above code gives us the following result −" } ]
Trains - Solved Examples
Q 1 - What is 90 kmph as metres per second? A - 15 m /sec B - 20 m /sec C - 25 m /sec D - 30 m /sec Answer - C Explanation 90 kmph = ( 90 * 5/18) m/sec = 25 m /sec. Q 2 - What is 35 m/sec as km/hr? A - 123 km/hr B - 124 km/hr C - 125 km/hr D - 126 km/hr Answer - D Explanation 35 m/sec = (35 * 18 / 5 ) km/hr = 126 km/hr. Q 3 - A 75m long train is running at 54 km/hr. In how much time will it cross an electric pole? A - 25 sec B - 20 sec C - 15 sec D - 5 sec Answer - D Explanation Speed of the train = ( 54 * 5 / 18) m/sec = 15 m / sec. Time taken to cross an electric pole = Time taken to cover 75m = ( 75 / 15 ) sec = 5 sec. Q 4 - A 415 m long train is running at 63 km/hr. In how much time will it cross a tunnel 285 m long? A - 40 sec B - 50 sec C - 60 sec D - 70 sec Answer - A Explanation Speed of the train= ( 63 * 5 / 18) m/sec = 35/2 m/sec. Time taken to cross the tunnel = Time taken to cover ( 415 + 285) m = ( 700 * 2/35 ) sec = 40 sec. Q 5 - A train passes a standing man in 3 seconds and a platform 105 m long in 8 seconds. Find the length of the train and its speed? A - 59 m, 75.6 km/hr B - 61 m, 72.6 km/hr C - 63 m, 75.6 km/hr D - 66 m, 79.6 km/hr Answer - C Explanation Let the length of the train be x metres and its speed be y km/hr i.e. (5y/18 ) m/sec. Then, x / ( 5y / 18 ) = 3 ⇒ 18x = 15y ⇒ 6x = 5y. Also, ( x + 105) / ( 5y/ 18) = 8 ⇒ 18 ( x + 105 ) = 40y⇒ 9 ( x + 105 ) = 20y ⇒ 20y -9x = 945 ⇒ 24x – 9x = 945 ⇒ 15x = 945 ⇒ x= 63. ∴ 5y = ( 6 * 63 ) ⇒ y = ( 6 * 63 ) /5 = 378 / 5 = 75.6 Hence, the length of the train is 63 m and its speed is 75.6 km/hr. Q 6 - A train 125m long is running at 50 km/ hr. In what time will it pass a man , running at 5 km/hr in the same direction in which the train is going? A - 22 sec B - 20 sec C - 15 sec D - 10 sec Answer - D Explanation Speed of the train relative to man = ( 50 – 5 ) km/hr = ( 45 * 5 / 18) m/sec = 25/2 m/ sec. Distance covered in passing the man = 125m. ∴ Time taken = 125 / ( 25/2) sec = ( 125 * 2 / 25) sec = 10 sec. Q 7 - A train 110 m long is running at 60 km / hr. In what time will it pass a man, running in the direction opposite to that of the train at 6 km/hr? A - 9 sec B - 8 sec C - 7 sec D - 6 sec Answer - D Explanation Speed of the train relative to man = ( 60 + 6 km/hr = 66 km/hr = ( 66 * 15 / 18 ) m/sec = 55/3 m/sec. Distance covered in passing the man = 110m. Time taken = 110//( 55/3) sec = ( 110 * 3 / 55 ) sec = 6 sec. Q 8 - A train 100m long takes 9 seconds to cross a man walking at 5 km/hr in the direction opposite to that of the train. Find the speed of the train. A - 55 km/hr B - 45 km/hr C - 25 km/hr D - 35 km/hr Answer - D Explanation Let the speed of the train be x km/hr. Relative speed = ( x + 5 ) km /hr = 5 ( x+ 5 ) / 18 m/sec. Distance covered in passing the man = 100m. ∴ 100/ 5 ( x+5) / 18 = 9 ⇒ 45 ( x+ 5) = 1800 ⇒ x + 5 = 40 ⇒ x = 35. Speed of the train = 35 km/hr. Q 9 - Two train 128 m and 132m long are running towards each other on parallel lines at 42 km/hr and 30 km / hr respectively . In what time will they be clear of each other from the moment they meet? A - 13 sec B - 14 sec C - 15 sec D - 16 sec Answer - A Explanation Relative speed = ( 42 + 30 ) km/hr = 72 km/hr = ( 72 * 5 / 18 ) m/sec = 20 m / sec. Distance covered in passing each other = ( 128 + 132) m = 260m. ∴ Required time = 260 / 20 sec= 13 sec. 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 3936, "s": 3892, "text": "Q 1 - What is 90 kmph as metres per second?" }, { "code": null, "e": 3950, "s": 3936, "text": "A - 15 m /sec" }, { "code": null, "e": 3965, "s": 3950, "text": "B - 20 m /sec " }, { "code": null, "e": 3979, "s": 3965, "text": "C - 25 m /sec" }, { "code": null, "e": 3994, "s": 3979, "text": "D - 30 m /sec " }, { "code": null, "e": 4005, "s": 3994, "text": "Answer - C" }, { "code": null, "e": 4017, "s": 4005, "text": "Explanation" }, { "code": null, "e": 4060, "s": 4017, "text": "90 kmph = ( 90 * 5/18) m/sec = 25 m /sec.\n" }, { "code": null, "e": 4093, "s": 4060, "text": "Q 2 - What is 35 m/sec as km/hr?" }, { "code": null, "e": 4108, "s": 4093, "text": "A - 123 km/hr " }, { "code": null, "e": 4123, "s": 4108, "text": "B - 124 km/hr " }, { "code": null, "e": 4138, "s": 4123, "text": "C - 125 km/hr " }, { "code": null, "e": 4153, "s": 4138, "text": "D - 126 km/hr " }, { "code": null, "e": 4164, "s": 4153, "text": "Answer - D" }, { "code": null, "e": 4176, "s": 4164, "text": "Explanation" }, { "code": null, "e": 4222, "s": 4176, "text": "35 m/sec = (35 * 18 / 5 ) km/hr = 126 km/hr.\n" }, { "code": null, "e": 4318, "s": 4222, "text": "Q 3 - A 75m long train is running at 54 km/hr. In how much time will it cross an electric pole?" }, { "code": null, "e": 4330, "s": 4318, "text": "A - 25 sec " }, { "code": null, "e": 4342, "s": 4330, "text": "B - 20 sec " }, { "code": null, "e": 4354, "s": 4342, "text": "C - 15 sec " }, { "code": null, "e": 4364, "s": 4354, "text": "D - 5 sec" }, { "code": null, "e": 4375, "s": 4364, "text": "Answer - D" }, { "code": null, "e": 4387, "s": 4375, "text": "Explanation" }, { "code": null, "e": 4534, "s": 4387, "text": "Speed of the train = ( 54 * 5 / 18) m/sec = 15 m / sec.\nTime taken to cross an electric pole = Time taken to cover 75m\n= ( 75 / 15 ) sec = 5 sec.\n" }, { "code": null, "e": 4635, "s": 4534, "text": "Q 4 - A 415 m long train is running at 63 km/hr. In how much time will it cross a tunnel 285 m long?" }, { "code": null, "e": 4647, "s": 4635, "text": "A - 40 sec " }, { "code": null, "e": 4659, "s": 4647, "text": "B - 50 sec " }, { "code": null, "e": 4671, "s": 4659, "text": "C - 60 sec " }, { "code": null, "e": 4682, "s": 4671, "text": "D - 70 sec" }, { "code": null, "e": 4693, "s": 4682, "text": "Answer - A" }, { "code": null, "e": 4705, "s": 4693, "text": "Explanation" }, { "code": null, "e": 4861, "s": 4705, "text": "Speed of the train= ( 63 * 5 / 18) m/sec = 35/2 m/sec.\nTime taken to cross the tunnel = Time taken to cover ( 415 + 285) m\n= ( 700 * 2/35 ) sec = 40 sec.\n" }, { "code": null, "e": 4994, "s": 4861, "text": "Q 5 - A train passes a standing man in 3 seconds and a platform 105 m long in 8 seconds. Find the length of the train and its speed?" }, { "code": null, "e": 5016, "s": 4994, "text": "A - 59 m, 75.6 km/hr " }, { "code": null, "e": 5038, "s": 5016, "text": "B - 61 m, 72.6 km/hr " }, { "code": null, "e": 5059, "s": 5038, "text": "C - 63 m, 75.6 km/hr" }, { "code": null, "e": 5081, "s": 5059, "text": "D - 66 m, 79.6 km/hr " }, { "code": null, "e": 5092, "s": 5081, "text": "Answer - C" }, { "code": null, "e": 5104, "s": 5092, "text": "Explanation" }, { "code": null, "e": 5496, "s": 5104, "text": "Let the length of the train be x metres and its speed be y km/hr i.e. (5y/18 ) m/sec.\nThen, x / ( 5y / 18 ) = 3 ⇒ 18x = 15y ⇒ 6x = 5y.\nAlso, ( x + 105) / ( 5y/ 18) = 8 ⇒ 18 ( x + 105 ) = 40y⇒ 9 ( x + 105 ) = 20y\n⇒ 20y -9x = 945 ⇒ 24x – 9x = 945 ⇒ 15x = 945 ⇒ x= 63.\n∴ 5y = ( 6 * 63 ) ⇒ y = ( 6 * 63 ) /5 = 378 / 5 = 75.6\nHence, the length of the train is 63 m and its speed is 75.6 km/hr.\n" }, { "code": null, "e": 5649, "s": 5496, "text": "Q 6 - A train 125m long is running at 50 km/ hr. In what time will it pass a man , running at 5 km/hr in the same direction in which the train is going?" }, { "code": null, "e": 5661, "s": 5649, "text": "A - 22 sec" }, { "code": null, "e": 5672, "s": 5661, "text": "B - 20 sec" }, { "code": null, "e": 5683, "s": 5672, "text": "C - 15 sec" }, { "code": null, "e": 5694, "s": 5683, "text": "D - 10 sec" }, { "code": null, "e": 5705, "s": 5694, "text": "Answer - D" }, { "code": null, "e": 5717, "s": 5705, "text": "Explanation" }, { "code": null, "e": 5919, "s": 5717, "text": "Speed of the train relative to man = ( 50 – 5 ) km/hr\n= ( 45 * 5 / 18) m/sec = 25/2 m/ sec.\nDistance covered in passing the man = 125m.\n∴ Time taken = 125 / ( 25/2) sec = ( 125 * 2 / 25) sec = 10 sec.\n" }, { "code": null, "e": 6071, "s": 5919, "text": "Q 7 - A train 110 m long is running at 60 km / hr. In what time will it pass a man, running in the direction opposite to that of the train at 6 km/hr?" }, { "code": null, "e": 6081, "s": 6071, "text": "A - 9 sec" }, { "code": null, "e": 6091, "s": 6081, "text": "B - 8 sec" }, { "code": null, "e": 6101, "s": 6091, "text": "C - 7 sec" }, { "code": null, "e": 6111, "s": 6101, "text": "D - 6 sec" }, { "code": null, "e": 6122, "s": 6111, "text": "Answer - D" }, { "code": null, "e": 6134, "s": 6122, "text": "Explanation" }, { "code": null, "e": 6343, "s": 6134, "text": "Speed of the train relative to man = ( 60 + 6 km/hr = 66 km/hr\n= ( 66 * 15 / 18 ) m/sec = 55/3 m/sec.\nDistance covered in passing the man = 110m.\nTime taken = 110//( 55/3) sec = ( 110 * 3 / 55 ) sec = 6 sec.\n" }, { "code": null, "e": 6496, "s": 6343, "text": "Q 8 - A train 100m long takes 9 seconds to cross a man walking at 5 km/hr in the direction opposite to that of the train. Find the speed of the train." }, { "code": null, "e": 6509, "s": 6496, "text": "A - 55 km/hr" }, { "code": null, "e": 6522, "s": 6509, "text": "B - 45 km/hr" }, { "code": null, "e": 6535, "s": 6522, "text": "C - 25 km/hr" }, { "code": null, "e": 6548, "s": 6535, "text": "D - 35 km/hr" }, { "code": null, "e": 6559, "s": 6548, "text": "Answer - D" }, { "code": null, "e": 6571, "s": 6559, "text": "Explanation" }, { "code": null, "e": 6813, "s": 6571, "text": "Let the speed of the train be x km/hr.\nRelative speed = ( x + 5 ) km /hr = 5 ( x+ 5 ) / 18 m/sec.\nDistance covered in passing the man = 100m.\n∴ 100/ 5 ( x+5) / 18 = 9 ⇒ 45 ( x+ 5) = 1800 ⇒ x + 5 = 40 ⇒ x = 35.\nSpeed of the train = 35 km/hr.\n" }, { "code": null, "e": 7014, "s": 6813, "text": "Q 9 - Two train 128 m and 132m long are running towards each other on parallel lines at 42 km/hr and 30 km / hr respectively . In what time will they be clear of each other from the moment they meet?" }, { "code": null, "e": 7026, "s": 7014, "text": "A - 13 sec " }, { "code": null, "e": 7038, "s": 7026, "text": "B - 14 sec " }, { "code": null, "e": 7050, "s": 7038, "text": "C - 15 sec " }, { "code": null, "e": 7062, "s": 7050, "text": "D - 16 sec " }, { "code": null, "e": 7073, "s": 7062, "text": "Answer - A" }, { "code": null, "e": 7085, "s": 7073, "text": "Explanation" }, { "code": null, "e": 7275, "s": 7085, "text": "Relative speed = ( 42 + 30 ) km/hr = 72 km/hr\n= ( 72 * 5 / 18 ) m/sec = 20 m / sec.\nDistance covered in passing each other = ( 128 + 132) m = 260m.\n∴ Required time = 260 / 20 sec= 13 sec.\n" }, { "code": null, "e": 7311, "s": 7275, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 7329, "s": 7311, "text": " Programming Line" }, { "code": null, "e": 7336, "s": 7329, "text": " Print" }, { "code": null, "e": 7347, "s": 7336, "text": " Add Notes" } ]
How to get the second last record from a table in MySQL?
To get the record before the last one i.e. the second last record in MySQL, you need to use subquery. The syntax is as follows SELECT *FROM (SELECT *FROM yourTableName ORDER BY yourIdColumnName DESC LIMIT 2) anyAliasName ORDER BY yourIdColumnName LIMIT 1; Let us first create a table. The query to create a table is as follows mysql> create table lastRecordBeforeLastOne - > ( - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > Name varchar(20) DEFAULT 'John', - > Age int DEFAULT 18 - > ); Query OK, 0 rows affected (0.79 sec) Now you can insert some records in the table using insert command. The query is as follows mysql> insert into lastRecordBeforeLastOne values(); Query OK, 1 row affected (0.21 sec) mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Larry',23); Query OK, 1 row affected (0.19 sec) mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Mike',19); Query OK, 1 row affected (0.20 sec) mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Sam',24); Query OK, 1 row affected (0.22 sec) mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Bob',26); Query OK, 1 row affected (0.13 sec) mysql> insert into lastRecordBeforeLastOne(Name,Age) values('David',22); Query OK, 1 row affected (0.23 sec) mysql> insert into lastRecordBeforeLastOne(Name,Age) values('James',29); Query OK, 1 row affected (0.14 sec) mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Carol',21); Query OK, 1 row affected (0.23 sec) mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Maxwell',29); Query OK, 1 row affected (0.18 sec) mysql> insert into lastRecordBeforeLastOne(Name,Age) values('Chris',25); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement. The query is as follows mysql> select *from lastRecordBeforeLastOne; The following is the output +----+---------+------+ | Id | Name | Age | +----+---------+------+ | 1 | John | 18 | | 2 | Larry | 23 | | 3 | Mike | 19 | | 4 | Sam | 24 | | 5 | Bob | 26 | | 6 | David | 22 | | 7 | James | 29 | | 8 | Carol | 21 | | 9 | Maxwell | 29 | | 10 | Chris | 25 | +----+---------+------+ 10 rows in set (0.00 sec) Here is the query to get the second last record in MySQL mysql> SELECT *FROM - > (SELECT *FROM lastRecordBeforeLastOne ORDER BY Id DESC LIMIT 2) tbl1 - > ORDER BY Id LIMIT 1; The following is the output +----+---------+------+ | Id | Name | Age | +----+---------+------+ | 9 | Maxwell | 29 | +----+---------+------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1164, "s": 1062, "text": "To get the record before the last one i.e. the second last record in MySQL, you need to use subquery." }, { "code": null, "e": 1189, "s": 1164, "text": "The syntax is as follows" }, { "code": null, "e": 1318, "s": 1189, "text": "SELECT *FROM\n(SELECT *FROM yourTableName ORDER BY yourIdColumnName DESC LIMIT 2)\nanyAliasName\nORDER BY yourIdColumnName LIMIT 1;" }, { "code": null, "e": 1389, "s": 1318, "text": "Let us first create a table. The query to create a table is as follows" }, { "code": null, "e": 1606, "s": 1389, "text": "mysql> create table lastRecordBeforeLastOne\n - > (\n - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n - > Name varchar(20) DEFAULT 'John',\n - > Age int DEFAULT 18\n - > );\nQuery OK, 0 rows affected (0.79 sec)" }, { "code": null, "e": 1673, "s": 1606, "text": "Now you can insert some records in the table using insert command." }, { "code": null, "e": 1697, "s": 1673, "text": "The query is as follows" }, { "code": null, "e": 2764, "s": 1697, "text": "mysql> insert into lastRecordBeforeLastOne values();\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into lastRecordBeforeLastOne(Name,Age) values('Larry',23);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into lastRecordBeforeLastOne(Name,Age) values('Mike',19);\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into lastRecordBeforeLastOne(Name,Age) values('Sam',24);\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into lastRecordBeforeLastOne(Name,Age) values('Bob',26);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into lastRecordBeforeLastOne(Name,Age) values('David',22);\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into lastRecordBeforeLastOne(Name,Age) values('James',29);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into lastRecordBeforeLastOne(Name,Age) values('Carol',21);\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into lastRecordBeforeLastOne(Name,Age) values('Maxwell',29);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into lastRecordBeforeLastOne(Name,Age) values('Chris',25);\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2823, "s": 2764, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2847, "s": 2823, "text": "The query is as follows" }, { "code": null, "e": 2892, "s": 2847, "text": "mysql> select *from lastRecordBeforeLastOne;" }, { "code": null, "e": 2920, "s": 2892, "text": "The following is the output" }, { "code": null, "e": 3282, "s": 2920, "text": "+----+---------+------+\n| Id | Name | Age |\n+----+---------+------+\n| 1 | John | 18 |\n| 2 | Larry | 23 |\n| 3 | Mike | 19 |\n| 4 | Sam | 24 |\n| 5 | Bob | 26 |\n| 6 | David | 22 |\n| 7 | James | 29 |\n| 8 | Carol | 21 |\n| 9 | Maxwell | 29 |\n| 10 | Chris | 25 |\n+----+---------+------+\n10 rows in set (0.00 sec)" }, { "code": null, "e": 3339, "s": 3282, "text": "Here is the query to get the second last record in MySQL" }, { "code": null, "e": 3463, "s": 3339, "text": "mysql> SELECT *FROM\n - > (SELECT *FROM lastRecordBeforeLastOne ORDER BY Id DESC LIMIT 2) tbl1\n - > ORDER BY Id LIMIT 1;" }, { "code": null, "e": 3491, "s": 3463, "text": "The following is the output" }, { "code": null, "e": 3635, "s": 3491, "text": "+----+---------+------+\n| Id | Name | Age |\n+----+---------+------+\n| 9 | Maxwell | 29 |\n+----+---------+------+\n1 row in set (0.00 sec)" } ]
How to get random value out of an array in PHP?
To get random value out of an array in PHP, the code is as follows− Live Demo <?php $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125" ); echo "Array values ...\n"; echo "Value 1 = " . $arr["p"], "\n"; echo "Value 2 = " . $arr["q"], "\n"; echo "Value 3 = " . $arr["r"], "\n"; echo "Value 4 = " . $arr["s"], "\n"; echo "Value 5 = " . $arr["t"], "\n"; echo "Value 6 = " . $arr["u"], "\n"; echo "Value 7 = " . $arr["v"], "\n"; echo "Value 8 = " . $arr["w"], "\n"; echo "Random value from arary = ".$arr[array_rand($arr)]; ?> This will produce the following output − Array values ... Value 1 = 150 Value 2 = 100 Value 3 = 120 Value 4 = 110 Value 5 = 115 Value 6 = 103 Value 7 = 105 Value 8 = 125 Random value from arary = 110 Let us now see another example − Live Demo <?php $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115", "u"=>"103", "v"=>"105", "w"=>"125" ); echo "Array values ...\n"; echo "Value 1 = " . $arr["p"], "\n"; echo "Value 2 = " . $arr["q"], "\n"; echo "Value 3 = " . $arr["r"], "\n"; echo "Value 4 = " . $arr["s"], "\n"; echo "Value 5 = " . $arr["t"], "\n"; echo "Value 6 = " . $arr["u"], "\n"; echo "Value 7 = " . $arr["v"], "\n"; echo "Value 8 = " . $arr["w"], "\n"; $res = array_rand($arr, 2); echo "Random values from array..."; echo $arr[$res[0]]." ".$arr[$res[1]]; ?> This will produce the following output− Array values ... Value 1 = 150 Value 2 = 100 Value 3 = 120 Value 4 = 110 Value 5 = 115 Value 6 = 103 Value 7 = 105 Value 8 = 125 Random values from array...150 115
[ { "code": null, "e": 1130, "s": 1062, "text": "To get random value out of an array in PHP, the code is as follows−" }, { "code": null, "e": 1141, "s": 1130, "text": " Live Demo" }, { "code": null, "e": 1676, "s": 1141, "text": "<?php\n $arr = array( \"p\"=>\"150\", \"q\"=>\"100\", \"r\"=>\"120\", \"s\"=>\"110\", \"t\"=>\"115\", \"u\"=>\"103\", \"v\"=>\"105\", \"w\"=>\"125\" );\n echo \"Array values ...\\n\";\n echo \"Value 1 = \" . $arr[\"p\"], \"\\n\";\n echo \"Value 2 = \" . $arr[\"q\"], \"\\n\";\n echo \"Value 3 = \" . $arr[\"r\"], \"\\n\";\n echo \"Value 4 = \" . $arr[\"s\"], \"\\n\";\n echo \"Value 5 = \" . $arr[\"t\"], \"\\n\";\n echo \"Value 6 = \" . $arr[\"u\"], \"\\n\";\n echo \"Value 7 = \" . $arr[\"v\"], \"\\n\";\n echo \"Value 8 = \" . $arr[\"w\"], \"\\n\";\n echo \"Random value from arary = \".$arr[array_rand($arr)];\n?>" }, { "code": null, "e": 1717, "s": 1676, "text": "This will produce the following output −" }, { "code": null, "e": 1876, "s": 1717, "text": "Array values ...\nValue 1 = 150\nValue 2 = 100\nValue 3 = 120\nValue 4 = 110\nValue 5 = 115\nValue 6 = 103\nValue 7 = 105\nValue 8 = 125\nRandom value from arary = 110" }, { "code": null, "e": 1909, "s": 1876, "text": "Let us now see another example −" }, { "code": null, "e": 1920, "s": 1909, "text": " Live Demo" }, { "code": null, "e": 2505, "s": 1920, "text": "<?php\n $arr = array( \"p\"=>\"150\", \"q\"=>\"100\", \"r\"=>\"120\", \"s\"=>\"110\", \"t\"=>\"115\", \"u\"=>\"103\", \"v\"=>\"105\", \"w\"=>\"125\" );\n echo \"Array values ...\\n\";\n echo \"Value 1 = \" . $arr[\"p\"], \"\\n\";\n echo \"Value 2 = \" . $arr[\"q\"], \"\\n\";\n echo \"Value 3 = \" . $arr[\"r\"], \"\\n\";\n echo \"Value 4 = \" . $arr[\"s\"], \"\\n\";\n echo \"Value 5 = \" . $arr[\"t\"], \"\\n\";\n echo \"Value 6 = \" . $arr[\"u\"], \"\\n\";\n echo \"Value 7 = \" . $arr[\"v\"], \"\\n\";\n echo \"Value 8 = \" . $arr[\"w\"], \"\\n\";\n $res = array_rand($arr, 2);\n echo \"Random values from array...\";\n echo $arr[$res[0]].\" \".$arr[$res[1]];\n?>" }, { "code": null, "e": 2545, "s": 2505, "text": "This will produce the following output−" }, { "code": null, "e": 2709, "s": 2545, "text": "Array values ...\nValue 1 = 150\nValue 2 = 100\nValue 3 = 120\nValue 4 = 110\nValue 5 = 115\nValue 6 = 103\nValue 7 = 105\nValue 8 = 125\nRandom values from array...150 115" } ]
Maintain Image Quality When Applying CSS Transform & Scale
The CSS image-rendering property helps us set an algorithm for scaling our image. The syntax of CSS image-rendering property is as follows − Selector { image-rendering: /*value*/ } The following examples illustrate CSS image-rendering property. Live Demo <!DOCTYPE html> <html> <head> <style> img { height: 200px; width: 200px; } #one { image-rendering: smooth } #two { image-rendering: pixelated } #three { image-rendering: crisp-edges } </style> </head> <body> <img id="one" src="https://images.unsplash.com/photo-1610208309350-766d71494a03?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=128&ixlib=rb-1.2.1&q=80&w=128" /> <img id="two" src="https://images.unsplash.com/photo-1610208309350-766d71494a03?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=128&ixlib=rb-1.2.1&q=80&w=128" /> <img id="three" src="https://images.unsplash.com/photo-1610208309350-766d71494a03?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=128&ixlib=rb-1.2.1&q=80&w=128" /> </body> </html> This gives the following output Live Demo <!DOCTYPE html> <html> <head> <style> img { padding: 5%; border-radius: 40%; height: 20%; width: 20%; } #one { image-rendering: pixelated } #two { image-rendering: smooth } #three { image-rendering: crisp-edges } </style> </head> <body> <img id="one" src="https://images.unsplash.com/photo-1611090093783-a629a4d9f1a1?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=256&ixlib=rb-1.2.1&q=80&w=256" /> <img id="two" src="https://images.unsplash.com/photo-1611090093783-a629a4d9f1a1?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=256&ixlib=rb-1.2.1&q=80&w=256" /> <img id="three" src="https://images.unsplash.com/photo-1611090093783-a629a4d9f1a1?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=256&ixlib=rb-1.2.1&q=80&w=256" /> <br/> pixelated, smooth, crisp </body> </html> This gives the following output
[ { "code": null, "e": 1144, "s": 1062, "text": "The CSS image-rendering property helps us set an algorithm for scaling our image." }, { "code": null, "e": 1203, "s": 1144, "text": "The syntax of CSS image-rendering property is as follows −" }, { "code": null, "e": 1246, "s": 1203, "text": "Selector {\n image-rendering: /*value*/\n}" }, { "code": null, "e": 1310, "s": 1246, "text": "The following examples illustrate CSS image-rendering property." }, { "code": null, "e": 1321, "s": 1310, "text": " Live Demo" }, { "code": null, "e": 2192, "s": 1321, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n img {\n height: 200px;\n width: 200px;\n }\n #one {\n image-rendering: smooth\n }\n #two {\n image-rendering: pixelated\n }\n #three {\n image-rendering: crisp-edges\n }\n </style>\n </head>\n <body>\n <img id=\"one\" src=\"https://images.unsplash.com/photo-1610208309350-766d71494a03?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=128&ixlib=rb-1.2.1&q=80&w=128\" />\n <img id=\"two\" src=\"https://images.unsplash.com/photo-1610208309350-766d71494a03?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=128&ixlib=rb-1.2.1&q=80&w=128\" />\n <img id=\"three\" src=\"https://images.unsplash.com/photo-1610208309350-766d71494a03?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=128&ixlib=rb-1.2.1&q=80&w=128\" />\n </body>\n</html>" }, { "code": null, "e": 2224, "s": 2192, "text": "This gives the following output" }, { "code": null, "e": 2235, "s": 2224, "text": " Live Demo" }, { "code": null, "e": 3202, "s": 2235, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n img {\n padding: 5%;\n border-radius: 40%;\n height: 20%;\n width: 20%;\n }\n #one {\n image-rendering: pixelated\n }\n #two {\n image-rendering: smooth\n }\n #three {\n image-rendering: crisp-edges\n }\n </style>\n </head>\n <body>\n <img id=\"one\" src=\"https://images.unsplash.com/photo-1611090093783-a629a4d9f1a1?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=256&ixlib=rb-1.2.1&q=80&w=256\" />\n <img id=\"two\" src=\"https://images.unsplash.com/photo-1611090093783-a629a4d9f1a1?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=256&ixlib=rb-1.2.1&q=80&w=256\" />\n <img id=\"three\" src=\"https://images.unsplash.com/photo-1611090093783-a629a4d9f1a1?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=256&ixlib=rb-1.2.1&q=80&w=256\" />\n <br/>\n pixelated, smooth, crisp\n </body>\n</html>" }, { "code": null, "e": 3234, "s": 3202, "text": "This gives the following output" } ]
Get the Name of a Member Object in Java
The getName() method is used to get the names of the entities such as interface, class, array class, void etc. that are represented by the class objects. These names are returned in the form of a string. A program that gets the name of the member objects using getName() method is given as follows − Live Demo import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class Main { public static void main(String[] argv) throws Exception { Class c = java.lang.Integer.class; Method m = c.getMethods()[0]; Field f = c.getFields()[0]; Constructor cons = c.getConstructors()[0]; String name; name = c.getName(); System.out.println("Name of class: " + name); name = m.getName(); System.out.println("Name of method: " + name); name = f.getName(); System.out.println("Name of field: " + name); name = cons.getName(); System.out.println("Name of constructor: " + name); } } Name of class: java.lang.Integer Name of method: numberOfLeadingZeros Name of field: MIN_VALUE Name of constructor: java.lang.Integer Now let us understand the above program. The getName() method is used to get the names of the class, method, field and constructor. Then these are displayed. A code snippet which demonstrates this is as follows − Class c = java.lang.Integer.class; Method m = c.getMethods()[0]; Field f = c.getFields()[0]; Constructor cons = c.getConstructors()[0]; String name; name = c.getName(); System.out.println("Name of class: " + name); name = m.getName(); System.out.println("Name of method: " + name); name = f.getName(); System.out.println("Name of field: " + name); name = cons.getName(); System.out.println("Name of constructor: " + name);
[ { "code": null, "e": 1266, "s": 1062, "text": "The getName() method is used to get the names of the entities such as interface, class, array class, void etc. that are represented by the class objects. These names are returned in the form of a string." }, { "code": null, "e": 1362, "s": 1266, "text": "A program that gets the name of the member objects using getName() method is given as follows −" }, { "code": null, "e": 1373, "s": 1362, "text": " Live Demo" }, { "code": null, "e": 2065, "s": 1373, "text": "import java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\npublic class Main {\n public static void main(String[] argv) throws Exception {\n Class c = java.lang.Integer.class;\n Method m = c.getMethods()[0];\n Field f = c.getFields()[0];\n Constructor cons = c.getConstructors()[0];\n String name;\n name = c.getName();\n System.out.println(\"Name of class: \" + name);\n name = m.getName();\n System.out.println(\"Name of method: \" + name);\n name = f.getName();\n System.out.println(\"Name of field: \" + name);\n name = cons.getName();\n System.out.println(\"Name of constructor: \" + name);\n }\n}" }, { "code": null, "e": 2199, "s": 2065, "text": "Name of class: java.lang.Integer\nName of method: numberOfLeadingZeros\nName of field: MIN_VALUE\nName of constructor: java.lang.Integer" }, { "code": null, "e": 2240, "s": 2199, "text": "Now let us understand the above program." }, { "code": null, "e": 2412, "s": 2240, "text": "The getName() method is used to get the names of the class, method, field and constructor. Then these are displayed. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2835, "s": 2412, "text": "Class c = java.lang.Integer.class;\nMethod m = c.getMethods()[0];\nField f = c.getFields()[0];\nConstructor cons = c.getConstructors()[0];\nString name;\nname = c.getName();\nSystem.out.println(\"Name of class: \" + name);\nname = m.getName();\nSystem.out.println(\"Name of method: \" + name);\nname = f.getName();\nSystem.out.println(\"Name of field: \" + name);\nname = cons.getName();\nSystem.out.println(\"Name of constructor: \" + name);" } ]
Java.util.TimerTask class in Java - GeeksforGeeks
22 Apr, 2022 TimerTask is an abstract class defined in java.util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden. The run method is implicitly invoked when a timer object schdedules it to do so. Note: An instance of TimerTask class is used to define a task the needs to run periodically. Constructors: TimerTask(): Creates a new timer task Declaration: public abstract class TimerTask extends Object implements Runnable Methods: cancel(): java.util.TimerTask.cancel() Cancels this timer task Syntax: cancel(): java.util.TimerTask.cancel() Cancels this timer task Syntax: public boolean cancel() Returns: true if this task is scheduled for one-time execution and has not yet run, or this task is scheduled for repeated execution. Returns false if the task was scheduled for one-time execution and has already run, or if the task was never scheduled, or if the task was already cancelled. run(): java.util.TimerTask.run() The action to be performed by this timer task Syntax: run(): java.util.TimerTask.run() The action to be performed by this timer task Syntax: public abstract void run() Description: The action to be performed by this timer task scheduledExecutionTime(): java.util.TimerTask.scheduledExecutionTime() Returns the scheduled execution time of the most recent actual execution of this task Syntax: scheduledExecutionTime(): java.util.TimerTask.scheduledExecutionTime() Returns the scheduled execution time of the most recent actual execution of this task Syntax: public long scheduledExecutionTime() Returns: the time at which the most recent execution of this task was scheduled to occur, in the format returned by Date.getTime(). The return value is undefined if the task has yet to commence its first execution Methods inherited from class java.lang.Object clone equals finalize getClass hashCode notify notifyAll toString wait Java program to demonstrate usage of TimerTask class Java // Java program to demonstrate// working of TimerTask classimport java.util.Timer;import java.util.TimerTask; class Helper extends TimerTask{ public static int i = 0; public void run() { System.out.println("Timer ran" + ++i); if(i == 4) { synchronized(Test.obj) { Test.obj.notify(); } } } } public class Test{ public static Test obj; public static void main(String[] args) throws InterruptedException { obj = new Test(); // creating an instance of timer class Timer timer = new Timer(); // creating an instance of task to be scheduled TimerTask task = new Helper(); // scheduling the timer instance timer.schedule(task, 1000, 3000); // fetching the scheduled execution time of // the most recent actual execution of the task System.out.println(task.scheduledExecutionTime()); synchronized(obj) { //this thread waits until i reaches 4 obj.wait(); } //canceling the task assigned System.out.println("Cancel the timer task: " + task.cancel()); // at this point timer is still running // without any task assigned to it // canceling the timer instance created timer.cancel(); }} Output: 1495715853591 Timer ran 1 Timer ran 2 Timer ran 3 Timer ran 4 Cancel the timer task: true Reference: Oracle This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java - util package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24509, "s": 24481, "text": "\n22 Apr, 2022" }, { "code": null, "e": 24980, "s": 24509, "text": "TimerTask is an abstract class defined in java.util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden. The run method is implicitly invoked when a timer object schdedules it to do so. Note: An instance of TimerTask class is used to define a task the needs to run periodically. Constructors:" }, { "code": null, "e": 25018, "s": 24980, "text": "TimerTask(): Creates a new timer task" }, { "code": null, "e": 25031, "s": 25018, "text": "Declaration:" }, { "code": null, "e": 25114, "s": 25031, "text": "public abstract class TimerTask\n extends Object\n implements Runnable" }, { "code": null, "e": 25123, "s": 25114, "text": "Methods:" }, { "code": null, "e": 25194, "s": 25123, "text": "cancel(): java.util.TimerTask.cancel() Cancels this timer task Syntax:" }, { "code": null, "e": 25265, "s": 25194, "text": "cancel(): java.util.TimerTask.cancel() Cancels this timer task Syntax:" }, { "code": null, "e": 25584, "s": 25265, "text": "public boolean cancel()\nReturns:\ntrue if this task is scheduled for one-time execution and\nhas not yet run, or this task is scheduled for repeated execution. \nReturns false if the task was scheduled for one-time \nexecution and has already run, or if the task was never scheduled, \nor if the task was already cancelled." }, { "code": null, "e": 25671, "s": 25584, "text": "run(): java.util.TimerTask.run() The action to be performed by this timer task Syntax:" }, { "code": null, "e": 25758, "s": 25671, "text": "run(): java.util.TimerTask.run() The action to be performed by this timer task Syntax:" }, { "code": null, "e": 25844, "s": 25758, "text": "public abstract void run()\nDescription:\nThe action to be performed by this timer task" }, { "code": null, "e": 26009, "s": 25844, "text": "scheduledExecutionTime(): java.util.TimerTask.scheduledExecutionTime() Returns the scheduled execution time of the most recent actual execution of this task Syntax:" }, { "code": null, "e": 26174, "s": 26009, "text": "scheduledExecutionTime(): java.util.TimerTask.scheduledExecutionTime() Returns the scheduled execution time of the most recent actual execution of this task Syntax:" }, { "code": null, "e": 26429, "s": 26174, "text": "public long scheduledExecutionTime()\nReturns: \nthe time at which the most recent execution of this task was \nscheduled to occur, in the format returned by Date.getTime(). \nThe return value is undefined if the task has yet to \ncommence its first execution" }, { "code": null, "e": 26475, "s": 26429, "text": "Methods inherited from class java.lang.Object" }, { "code": null, "e": 26481, "s": 26475, "text": "clone" }, { "code": null, "e": 26488, "s": 26481, "text": "equals" }, { "code": null, "e": 26497, "s": 26488, "text": "finalize" }, { "code": null, "e": 26506, "s": 26497, "text": "getClass" }, { "code": null, "e": 26515, "s": 26506, "text": "hashCode" }, { "code": null, "e": 26522, "s": 26515, "text": "notify" }, { "code": null, "e": 26532, "s": 26522, "text": "notifyAll" }, { "code": null, "e": 26541, "s": 26532, "text": "toString" }, { "code": null, "e": 26546, "s": 26541, "text": "wait" }, { "code": null, "e": 26599, "s": 26546, "text": "Java program to demonstrate usage of TimerTask class" }, { "code": null, "e": 26604, "s": 26599, "text": "Java" }, { "code": "// Java program to demonstrate// working of TimerTask classimport java.util.Timer;import java.util.TimerTask; class Helper extends TimerTask{ public static int i = 0; public void run() { System.out.println(\"Timer ran\" + ++i); if(i == 4) { synchronized(Test.obj) { Test.obj.notify(); } } } } public class Test{ public static Test obj; public static void main(String[] args) throws InterruptedException { obj = new Test(); // creating an instance of timer class Timer timer = new Timer(); // creating an instance of task to be scheduled TimerTask task = new Helper(); // scheduling the timer instance timer.schedule(task, 1000, 3000); // fetching the scheduled execution time of // the most recent actual execution of the task System.out.println(task.scheduledExecutionTime()); synchronized(obj) { //this thread waits until i reaches 4 obj.wait(); } //canceling the task assigned System.out.println(\"Cancel the timer task: \" + task.cancel()); // at this point timer is still running // without any task assigned to it // canceling the timer instance created timer.cancel(); }}", "e": 28007, "s": 26604, "text": null }, { "code": null, "e": 28015, "s": 28007, "text": "Output:" }, { "code": null, "e": 28105, "s": 28015, "text": "1495715853591\nTimer ran 1\nTimer ran 2\nTimer ran 3\nTimer ran 4\nCancel the timer task: true" }, { "code": null, "e": 28116, "s": 28105, "text": "Reference:" }, { "code": null, "e": 28123, "s": 28116, "text": "Oracle" }, { "code": null, "e": 28544, "s": 28123, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28564, "s": 28544, "text": "Java - util package" }, { "code": null, "e": 28569, "s": 28564, "text": "Java" }, { "code": null, "e": 28574, "s": 28569, "text": "Java" }, { "code": null, "e": 28672, "s": 28574, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28681, "s": 28672, "text": "Comments" }, { "code": null, "e": 28694, "s": 28681, "text": "Old Comments" }, { "code": null, "e": 28745, "s": 28694, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28775, "s": 28745, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28806, "s": 28775, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28838, "s": 28806, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28857, "s": 28838, "text": "Interfaces in Java" }, { "code": null, "e": 28875, "s": 28857, "text": "ArrayList in Java" }, { "code": null, "e": 28907, "s": 28875, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28927, "s": 28907, "text": "Stack Class in Java" }, { "code": null, "e": 28951, "s": 28927, "text": "Singleton Class in Java" } ]
How to Build Neural Network from Scratch | by Arseny Turin | Towards Data Science
Step by step tutorial on how to build a simple neural network from scratch In this post, we will build our own neural network from scratch with one hidden layer and a sigmoid activation function. We will take a closer look at the derivatives and a chain rule to have a clear picture of the backpropagation implementation. Our network would be able to solve a linear regression task with the same accuracy as a Keras analog. The code for this project you can find in this GitHub repository. We used to see neural networks as interconnected layers of neurons, where we have an input layer on the left, hidden layers in the middle and output layer on the right side. It’s easier to digest visually, but ultimately, the neural network is just one big function that takes other functions as an input; and depends on the depth of the network those inner functions could also take other functions as input and so on. Those inner functions are in fact “layers”. Let's take a look at the diagram of the network we will build: It has an input layer with two features, a hidden layer with three neurons and an output layer. Each neuron in the hidden layer is a sigmoid activation function that takes input values (x1, x2), weights (w1,...,w6) and biases (b1, b2, b3) as an input and produces value ranging from 0 to 1 as an output. In the beginning we assign random values to the weights and biases ranging from 0 to 1. The output layer contains just one neuron that does a similar job as neurons from the hidden layer. You might’ve guessed that ŷ is in fact that big function I mentioned earlier. The type of network we described above is called Dence Network, because neurons are fully connected with elements from the previous layer, in our case with input. The most crucial part to understand is that the neural network is trained only by adjusting weights and biases to minimize output error. The training process consists of feedforward and backpropagation. Feedforward predicts output and the backpropagation is adjusting weights and biases to minimize the error of the output, i.e. difference between predicted and true values. When we want to predict output, we use a feedforward function. This function takes input x1 and x2, these input values go into neurons in the hidden layer along with weights and biases and each neuron returns a value [0–1]; then the output layer takes those values and produces the output. Let's take a closer look at the first neuron in the hidden layer and understand what it’s actually doing. As I mentioned earlier, each neuron is just a sigmoid function: Similar to linear regression, where we have parameters such as slopes and intercept to make predictions, in the neural networks we have weights and bias. Each neuron will produce a value [0-1] which we will use as an input to the output layer. In some neural networks, it’s not necessary to have an output layer as a sigmoid or any other activation function, it could be just a sum of values from the previous layer. The code for this function looks like this: def sigmoid(x): return 1 / (1 + np.e**-x)def feedforward(x1, x2): n1 = sigmoid(x1 * w1 + x2 * w2 + b1) n2 = sigmoid(x1 * w3 + x2 * w4 + b2) n3 = sigmoid(x1 * w5 + x2 * w6 + b3) y_hat = sigmoid(n1 * w7 + n2 * w8 + n3 * w9 + b4) return y_hat After we have predicted the value we can compare it to the true value by using Mean Squared Error (MSE). The role of the bias is to provide an additional parameter to the neuron that is not affected by previous layers because it’s not connected to them in any way. At first, our network would do a terrible job at predicting, because weights and biases are just random numbers. Now backpropagation comes into play to help us train these parameters. Each time network makes a prediction, we use MSE to compare it with the true value, and then we go back to adjust each weight and bias to reduce error ever so slightly. There are several elements we should know about to understand backpropagation: Derivatives — what direction to change each weight and biasChain Rule — how to access each weightGradient Descent — an iterative process of adjusting weights and biases Derivatives — what direction to change each weight and bias Chain Rule — how to access each weight Gradient Descent — an iterative process of adjusting weights and biases Thanks to derivatives we always know in which direction we change each parameter (make it slightly bigger or smaller). Let's say we want to adjust one weight (w = 0.75) in order to make MSE a bit smaller. To do that we should take a partial derivative of a function with respect to this weight. Then we plug numbers into the derived function and get a number (0.05), positive or negative. Then we subtract that number from our weight (w -= 0.05). That's how the adjustment is done. And that should happen to each weight in the network. Because networks are ultimately very complex functions, it’s quite difficult to find a derivative of a parameter that buried inside a myriad of other functions. Luckily, derivatives have a chain rule that simplifies that process for us. If we need to find a derivative of a function that contains another function, we use the chain rule. This rule says that we take a derivative of an outside function, keep the inside function untouched, then we multiply everything by the derivative of the inside function. Once we know all the derivatives, we gradually adjust each weight and bias each time we do backpropagation. What’s important to know here is that gradient descent has a learning rate parameter, which is usually a small number that we add to the result of the derivative either to slow down or speed up training. Let's see on practice how to take a partial derivative of the w1. Once we understand how it works for one weight, it would be easy to implement for others, because for the most part, it is almost exactly the same process. Now, to take a partial derivative with respect to w1, we should start with the MSE function. It’s the root function that contains all other functions in the network. As we know, MSE is a squared difference between a true and predicted value (y-ŷ)2. If we would unfold the entire network to see where w1 sits inside, it would look like this: We should remember by now that network is a function that contains other functions, and to adjust each parameter in this function we need to use the chain rule: All that's left is to take derivatives of each function. For w1 it’s four derivatives, but for w8 it would be just three because it sits in ŷ and we don’t need to go that deep to get there. In the end, we get this scary-looking equation that explains how w1 affects MSE. Lets elaborate on what’s happening in each step. First, we took a derivative of MSE (y-ŷ)2, which is 2(y-ŷ), because the derivative of x2 is 2x, the same rule applies here. We didn’t touch what’s inside a squared function as the chain rule requires. Then we took a partial derivative of (y-ŷ) with respect to ŷ, which resulted in (0-sigmoid’(...)). Remember ŷ is a sigmoid function. With respect to ŷ because it’s the leading path to the weight w1. Next, we took a partial derivative of another sigmoid function with respect to n1 and finally the last derivative of x1*w1, which is x1, because the derivative of w1 is 1, and the coefficient x1 stays the same. Then we multiply each derivative and we’re good to go. To put everything together, we get: Where a learning rate is a small number, usually ranging from 0.01 to 0.05, but it could be larger. Same logic we apply for finding all the other weights and biases. You can imagine that if we have hundreds of neurons, we would have thousands of weights and biases, so for illustration purposes, we have kept the number of neurons very small. Please see GitHub for the rest of the code. Our network did a very good job of predicting home prices based on two parameters: median income and average rooms. Data was taken from the “california_housing” dataset from sklearn library. The network converged pretty fast, just over 6 epochs, and resulted in MSE = 0.028, exactly the same result I got from Keras analog. Our network is great for educational purposes, but it has limitations: we cannot change the number of neurons in the hidden layer or add another layer to the network. We have only one activation function and our network can solve only simple tasks, such as linear regression. If we want to use it for classification problems, we would need to find derivatives for the Cross-Entropy or Softmax loss function. All these changes could be done in the current setup. Let me know in the comments if you have any questions or what was hard to understand. Thank you for reading.
[ { "code": null, "e": 247, "s": 172, "text": "Step by step tutorial on how to build a simple neural network from scratch" }, { "code": null, "e": 596, "s": 247, "text": "In this post, we will build our own neural network from scratch with one hidden layer and a sigmoid activation function. We will take a closer look at the derivatives and a chain rule to have a clear picture of the backpropagation implementation. Our network would be able to solve a linear regression task with the same accuracy as a Keras analog." }, { "code": null, "e": 662, "s": 596, "text": "The code for this project you can find in this GitHub repository." }, { "code": null, "e": 1189, "s": 662, "text": "We used to see neural networks as interconnected layers of neurons, where we have an input layer on the left, hidden layers in the middle and output layer on the right side. It’s easier to digest visually, but ultimately, the neural network is just one big function that takes other functions as an input; and depends on the depth of the network those inner functions could also take other functions as input and so on. Those inner functions are in fact “layers”. Let's take a look at the diagram of the network we will build:" }, { "code": null, "e": 1493, "s": 1189, "text": "It has an input layer with two features, a hidden layer with three neurons and an output layer. Each neuron in the hidden layer is a sigmoid activation function that takes input values (x1, x2), weights (w1,...,w6) and biases (b1, b2, b3) as an input and produces value ranging from 0 to 1 as an output." }, { "code": null, "e": 1581, "s": 1493, "text": "In the beginning we assign random values to the weights and biases ranging from 0 to 1." }, { "code": null, "e": 1760, "s": 1581, "text": "The output layer contains just one neuron that does a similar job as neurons from the hidden layer. You might’ve guessed that ŷ is in fact that big function I mentioned earlier." }, { "code": null, "e": 1923, "s": 1760, "text": "The type of network we described above is called Dence Network, because neurons are fully connected with elements from the previous layer, in our case with input." }, { "code": null, "e": 2298, "s": 1923, "text": "The most crucial part to understand is that the neural network is trained only by adjusting weights and biases to minimize output error. The training process consists of feedforward and backpropagation. Feedforward predicts output and the backpropagation is adjusting weights and biases to minimize the error of the output, i.e. difference between predicted and true values." }, { "code": null, "e": 2588, "s": 2298, "text": "When we want to predict output, we use a feedforward function. This function takes input x1 and x2, these input values go into neurons in the hidden layer along with weights and biases and each neuron returns a value [0–1]; then the output layer takes those values and produces the output." }, { "code": null, "e": 2694, "s": 2588, "text": "Let's take a closer look at the first neuron in the hidden layer and understand what it’s actually doing." }, { "code": null, "e": 2758, "s": 2694, "text": "As I mentioned earlier, each neuron is just a sigmoid function:" }, { "code": null, "e": 2912, "s": 2758, "text": "Similar to linear regression, where we have parameters such as slopes and intercept to make predictions, in the neural networks we have weights and bias." }, { "code": null, "e": 3175, "s": 2912, "text": "Each neuron will produce a value [0-1] which we will use as an input to the output layer. In some neural networks, it’s not necessary to have an output layer as a sigmoid or any other activation function, it could be just a sum of values from the previous layer." }, { "code": null, "e": 3219, "s": 3175, "text": "The code for this function looks like this:" }, { "code": null, "e": 3474, "s": 3219, "text": "def sigmoid(x): return 1 / (1 + np.e**-x)def feedforward(x1, x2): n1 = sigmoid(x1 * w1 + x2 * w2 + b1) n2 = sigmoid(x1 * w3 + x2 * w4 + b2) n3 = sigmoid(x1 * w5 + x2 * w6 + b3) y_hat = sigmoid(n1 * w7 + n2 * w8 + n3 * w9 + b4) return y_hat" }, { "code": null, "e": 3579, "s": 3474, "text": "After we have predicted the value we can compare it to the true value by using Mean Squared Error (MSE)." }, { "code": null, "e": 3739, "s": 3579, "text": "The role of the bias is to provide an additional parameter to the neuron that is not affected by previous layers because it’s not connected to them in any way." }, { "code": null, "e": 3923, "s": 3739, "text": "At first, our network would do a terrible job at predicting, because weights and biases are just random numbers. Now backpropagation comes into play to help us train these parameters." }, { "code": null, "e": 4092, "s": 3923, "text": "Each time network makes a prediction, we use MSE to compare it with the true value, and then we go back to adjust each weight and bias to reduce error ever so slightly." }, { "code": null, "e": 4171, "s": 4092, "text": "There are several elements we should know about to understand backpropagation:" }, { "code": null, "e": 4340, "s": 4171, "text": "Derivatives — what direction to change each weight and biasChain Rule — how to access each weightGradient Descent — an iterative process of adjusting weights and biases" }, { "code": null, "e": 4400, "s": 4340, "text": "Derivatives — what direction to change each weight and bias" }, { "code": null, "e": 4439, "s": 4400, "text": "Chain Rule — how to access each weight" }, { "code": null, "e": 4511, "s": 4439, "text": "Gradient Descent — an iterative process of adjusting weights and biases" }, { "code": null, "e": 5047, "s": 4511, "text": "Thanks to derivatives we always know in which direction we change each parameter (make it slightly bigger or smaller). Let's say we want to adjust one weight (w = 0.75) in order to make MSE a bit smaller. To do that we should take a partial derivative of a function with respect to this weight. Then we plug numbers into the derived function and get a number (0.05), positive or negative. Then we subtract that number from our weight (w -= 0.05). That's how the adjustment is done. And that should happen to each weight in the network." }, { "code": null, "e": 5284, "s": 5047, "text": "Because networks are ultimately very complex functions, it’s quite difficult to find a derivative of a parameter that buried inside a myriad of other functions. Luckily, derivatives have a chain rule that simplifies that process for us." }, { "code": null, "e": 5385, "s": 5284, "text": "If we need to find a derivative of a function that contains another function, we use the chain rule." }, { "code": null, "e": 5556, "s": 5385, "text": "This rule says that we take a derivative of an outside function, keep the inside function untouched, then we multiply everything by the derivative of the inside function." }, { "code": null, "e": 5868, "s": 5556, "text": "Once we know all the derivatives, we gradually adjust each weight and bias each time we do backpropagation. What’s important to know here is that gradient descent has a learning rate parameter, which is usually a small number that we add to the result of the derivative either to slow down or speed up training." }, { "code": null, "e": 6090, "s": 5868, "text": "Let's see on practice how to take a partial derivative of the w1. Once we understand how it works for one weight, it would be easy to implement for others, because for the most part, it is almost exactly the same process." }, { "code": null, "e": 6256, "s": 6090, "text": "Now, to take a partial derivative with respect to w1, we should start with the MSE function. It’s the root function that contains all other functions in the network." }, { "code": null, "e": 6432, "s": 6256, "text": "As we know, MSE is a squared difference between a true and predicted value (y-ŷ)2. If we would unfold the entire network to see where w1 sits inside, it would look like this:" }, { "code": null, "e": 6593, "s": 6432, "text": "We should remember by now that network is a function that contains other functions, and to adjust each parameter in this function we need to use the chain rule:" }, { "code": null, "e": 6784, "s": 6593, "text": "All that's left is to take derivatives of each function. For w1 it’s four derivatives, but for w8 it would be just three because it sits in ŷ and we don’t need to go that deep to get there." }, { "code": null, "e": 6914, "s": 6784, "text": "In the end, we get this scary-looking equation that explains how w1 affects MSE. Lets elaborate on what’s happening in each step." }, { "code": null, "e": 7117, "s": 6914, "text": "First, we took a derivative of MSE (y-ŷ)2, which is 2(y-ŷ), because the derivative of x2 is 2x, the same rule applies here. We didn’t touch what’s inside a squared function as the chain rule requires." }, { "code": null, "e": 7586, "s": 7117, "text": "Then we took a partial derivative of (y-ŷ) with respect to ŷ, which resulted in (0-sigmoid’(...)). Remember ŷ is a sigmoid function. With respect to ŷ because it’s the leading path to the weight w1. Next, we took a partial derivative of another sigmoid function with respect to n1 and finally the last derivative of x1*w1, which is x1, because the derivative of w1 is 1, and the coefficient x1 stays the same. Then we multiply each derivative and we’re good to go." }, { "code": null, "e": 7622, "s": 7586, "text": "To put everything together, we get:" }, { "code": null, "e": 7788, "s": 7622, "text": "Where a learning rate is a small number, usually ranging from 0.01 to 0.05, but it could be larger. Same logic we apply for finding all the other weights and biases." }, { "code": null, "e": 8009, "s": 7788, "text": "You can imagine that if we have hundreds of neurons, we would have thousands of weights and biases, so for illustration purposes, we have kept the number of neurons very small. Please see GitHub for the rest of the code." }, { "code": null, "e": 8333, "s": 8009, "text": "Our network did a very good job of predicting home prices based on two parameters: median income and average rooms. Data was taken from the “california_housing” dataset from sklearn library. The network converged pretty fast, just over 6 epochs, and resulted in MSE = 0.028, exactly the same result I got from Keras analog." }, { "code": null, "e": 8795, "s": 8333, "text": "Our network is great for educational purposes, but it has limitations: we cannot change the number of neurons in the hidden layer or add another layer to the network. We have only one activation function and our network can solve only simple tasks, such as linear regression. If we want to use it for classification problems, we would need to find derivatives for the Cross-Entropy or Softmax loss function. All these changes could be done in the current setup." }, { "code": null, "e": 8881, "s": 8795, "text": "Let me know in the comments if you have any questions or what was hard to understand." } ]
Checkpointing Deep Learning Models in Keras | by Renu Khandelwal | Towards Data Science
Different methods to save and load the deep learning model are using JSON files YAML files Checkpoints In this article, you will learn how to checkpoint a deep learning model built using Keras and then reinstate the model architecture and trained weights to a new model or resume the training from you left off Allow us to use a pre-trained model for inference without having to retrain the model Resume the training process from where we left off in case it was interrupted or for fine-tuning the model It acts like an autosave for your model in case training is interrupted for any reason. Create the model Specify the path where we want to save the checkpoint files Create the callback function to save the model Apply the callback function during the training Evaluate the model on test data Load the pre-trained weights on a new model using load_weights() or restoring the weights from the latest checkpoint We have created the multi-class classification model for Fashion MNIST dataset # Define the model architecture def create_model(): model = tf.keras.Sequential() # Must define the input shape in the first layer of the neural network model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(28,28,1))) model.add(tf.keras.layers.MaxPooling2D(pool_size=2)) model.add(tf.keras.layers.Dropout(0.3)) model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=2, padding='same', activation='relu')) model.add(tf.keras.layers.MaxPooling2D(pool_size=2)) model.add(tf.keras.layers.Dropout(0.3)) model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(256, activation='relu')) model.add(tf.keras.layers.Dropout(0.5)) model.add(tf.keras.layers.Dense(10, activation='softmax')) #Compiling the model model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model#create the modelmodel_ckpt= create_model() Specify the path where the checkpoint files will be stored checkpoint_path = "train_ckpt/cp.ckpt" Create the callback function to save the model. Callback functions are applied at different stages of training to give a view on the internal training states. We create a callback function to save the model weights using ModelCheckpoint. If we set save_weight_only to True, then only the weights will be saved. Model architecture, loss, and the optimizer will not be saved. We can also specify if we want to save the model at every epoch or every n number of epochs. # Create a callback that saves the model's weightscp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,save_best_only=True, save_weights_only=True, verbose=1) ModelCheckpoint callback class has the following arguments: filepath: specify the path or filename where we want to save the model monitor: the metrics that we want to monitor such as loss or accuracy verbosity: 0 for debug mode and 1 for info save_weights_only: If set to True, then only model weights will be saved else the full model is saved, including the model architecture, weights, loss function, and optimizer. save_best_only: If set to True, then only the best model will be saved based on the quantity we are monitoring. If we are monitoring accuracy and save_best_only is set to True, then the model will be saved every time we get higher accuracy than the previous accuracy. mode: It has three options- auto, min, or max. If we are monitoring accuracy, then set it to the max, and if we are monitoring loss, then set it to min. If we set the mode to auto, then the direction is inferred automatically based on the quantity being monitored save_freq or period: set it to ‘epoch’ or a number. When it set it to epoch, then the model is saved after each epoch. When we specify a number say 5, then the model is saved after every five epochs as shown in the code below # Create a callback that saves the model's weights every 5 epochscp_callback = tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_path, verbose=1, save_weights_only=True, save_freq=5) Apply the callback during the training process # Train the model with the new callback# Pass callback to trainingmodel_ckpt.fit(train_images, train_labels, batch_size=64, epochs=10, validation_data=(test_images,test_labels), callbacks=[cp_callback]) We can see that if the val_loss does not improve, then the weights are not saved. Whenever the loss is reduced then those weights are saved to the checkpoint file Evaluating the model on test images loss,acc = model_ckpt.evaluate(test_images, test_labels, verbose=2) Checkpoint file stores the trained weights to a collection of checkpoint formatted files in a binary format The TensorFlow save() saves three kinds of files: checkpoint file, index file, and data file. It stores the graph structure separately from the variable values. checkpoint file: contains prefixes for both an index file as well as for one or more data files Index files: indicates which weights are stored in which shard. As I trained the model on one machine, we see cp.ckpt.data-00000-of-00002 and cp.ckpt.data-00001-of-00002 data file: saves values for all the variables, without the structure. There can be one or more data files Reasons for loading the pre-trained weights Continue from where we left off or Resume after an interruption or Load the pre-trained weight for inference We create a new model to load the pre-trained weights. When loading a new model with the pre-trained weights, the new model should have the same architecture as the original model. # Create a basic model instancemodel_ckpt2 = create_model() We load the pre-trained weights into our new model using load_weights(). model_ckpt2.load_weights(checkpoint_path) We can make inferences using the new model on the test images loss,acc = model_ckpt2.evaluate(test_images, test_labels, verbose=2)print("Restored model, accuracy: {:5.2f}%".format(100*acc)) An untrained model will perform at chance levels (~10% accuracy) model_ckpt2.fit(train_images, train_labels, batch_size=64, epochs=10, validation_data=(test_images,test_labels), callbacks=[cp_callback]) we see that the accuracy has changed now loss,acc = model_ckpt2.evaluate(test_images, test_labels, verbose=2)print("Restored model, accuracy: {:5.2f}%".format(100*acc)) latest_checkoint() find the filename of the latest saved checkpoint file #get the latest checkpoint filecheckpoint_dir = os.path.dirname(checkpoint_path)latest = tf.train.latest_checkpoint(checkpoint_dir) We create a new model, load the weights from the latest checkpoint and make inferences Create a new model instancemodel_latest_checkpoint = create_model()# Load the previously saved weightsmodel_latest_checkpoint.load_weights(latest)# Re-evaluate the modelloss, acc = model_latest_checkpoint.evaluate(test_images, test_labels, verbose=2)print("Restored model, accuracy: {:5.2f}%".format(100*acc)) Including epoch number in the filename # Include the epoch in the file name (uses `str.format`)checkpoint_path = "training2/cp-{epoch:04d}.ckpt" code for saving the model and reloading model using Fashion MNIST We now understand how to create a callback function using ModelCheckpoint class, the different checkpoint files that get created and then how we can restore the pre-trained weights
[ { "code": null, "e": 241, "s": 172, "text": "Different methods to save and load the deep learning model are using" }, { "code": null, "e": 252, "s": 241, "text": "JSON files" }, { "code": null, "e": 263, "s": 252, "text": "YAML files" }, { "code": null, "e": 275, "s": 263, "text": "Checkpoints" }, { "code": null, "e": 483, "s": 275, "text": "In this article, you will learn how to checkpoint a deep learning model built using Keras and then reinstate the model architecture and trained weights to a new model or resume the training from you left off" }, { "code": null, "e": 569, "s": 483, "text": "Allow us to use a pre-trained model for inference without having to retrain the model" }, { "code": null, "e": 676, "s": 569, "text": "Resume the training process from where we left off in case it was interrupted or for fine-tuning the model" }, { "code": null, "e": 764, "s": 676, "text": "It acts like an autosave for your model in case training is interrupted for any reason." }, { "code": null, "e": 781, "s": 764, "text": "Create the model" }, { "code": null, "e": 841, "s": 781, "text": "Specify the path where we want to save the checkpoint files" }, { "code": null, "e": 888, "s": 841, "text": "Create the callback function to save the model" }, { "code": null, "e": 936, "s": 888, "text": "Apply the callback function during the training" }, { "code": null, "e": 968, "s": 936, "text": "Evaluate the model on test data" }, { "code": null, "e": 1085, "s": 968, "text": "Load the pre-trained weights on a new model using load_weights() or restoring the weights from the latest checkpoint" }, { "code": null, "e": 1164, "s": 1085, "text": "We have created the multi-class classification model for Fashion MNIST dataset" }, { "code": null, "e": 2160, "s": 1164, "text": "# Define the model architecture def create_model(): model = tf.keras.Sequential() # Must define the input shape in the first layer of the neural network model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(28,28,1))) model.add(tf.keras.layers.MaxPooling2D(pool_size=2)) model.add(tf.keras.layers.Dropout(0.3)) model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=2, padding='same', activation='relu')) model.add(tf.keras.layers.MaxPooling2D(pool_size=2)) model.add(tf.keras.layers.Dropout(0.3)) model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(256, activation='relu')) model.add(tf.keras.layers.Dropout(0.5)) model.add(tf.keras.layers.Dense(10, activation='softmax')) #Compiling the model model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model#create the modelmodel_ckpt= create_model()" }, { "code": null, "e": 2219, "s": 2160, "text": "Specify the path where the checkpoint files will be stored" }, { "code": null, "e": 2258, "s": 2219, "text": "checkpoint_path = \"train_ckpt/cp.ckpt\"" }, { "code": null, "e": 2306, "s": 2258, "text": "Create the callback function to save the model." }, { "code": null, "e": 2417, "s": 2306, "text": "Callback functions are applied at different stages of training to give a view on the internal training states." }, { "code": null, "e": 2496, "s": 2417, "text": "We create a callback function to save the model weights using ModelCheckpoint." }, { "code": null, "e": 2632, "s": 2496, "text": "If we set save_weight_only to True, then only the weights will be saved. Model architecture, loss, and the optimizer will not be saved." }, { "code": null, "e": 2725, "s": 2632, "text": "We can also specify if we want to save the model at every epoch or every n number of epochs." }, { "code": null, "e": 2905, "s": 2725, "text": "# Create a callback that saves the model's weightscp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,save_best_only=True, save_weights_only=True, verbose=1)" }, { "code": null, "e": 2965, "s": 2905, "text": "ModelCheckpoint callback class has the following arguments:" }, { "code": null, "e": 3036, "s": 2965, "text": "filepath: specify the path or filename where we want to save the model" }, { "code": null, "e": 3106, "s": 3036, "text": "monitor: the metrics that we want to monitor such as loss or accuracy" }, { "code": null, "e": 3149, "s": 3106, "text": "verbosity: 0 for debug mode and 1 for info" }, { "code": null, "e": 3325, "s": 3149, "text": "save_weights_only: If set to True, then only model weights will be saved else the full model is saved, including the model architecture, weights, loss function, and optimizer." }, { "code": null, "e": 3593, "s": 3325, "text": "save_best_only: If set to True, then only the best model will be saved based on the quantity we are monitoring. If we are monitoring accuracy and save_best_only is set to True, then the model will be saved every time we get higher accuracy than the previous accuracy." }, { "code": null, "e": 3857, "s": 3593, "text": "mode: It has three options- auto, min, or max. If we are monitoring accuracy, then set it to the max, and if we are monitoring loss, then set it to min. If we set the mode to auto, then the direction is inferred automatically based on the quantity being monitored" }, { "code": null, "e": 4083, "s": 3857, "text": "save_freq or period: set it to ‘epoch’ or a number. When it set it to epoch, then the model is saved after each epoch. When we specify a number say 5, then the model is saved after every five epochs as shown in the code below" }, { "code": null, "e": 4286, "s": 4083, "text": "# Create a callback that saves the model's weights every 5 epochscp_callback = tf.keras.callbacks.ModelCheckpoint( filepath=checkpoint_path, verbose=1, save_weights_only=True, save_freq=5)" }, { "code": null, "e": 4333, "s": 4286, "text": "Apply the callback during the training process" }, { "code": null, "e": 4584, "s": 4333, "text": "# Train the model with the new callback# Pass callback to trainingmodel_ckpt.fit(train_images, train_labels, batch_size=64, epochs=10, validation_data=(test_images,test_labels), callbacks=[cp_callback])" }, { "code": null, "e": 4747, "s": 4584, "text": "We can see that if the val_loss does not improve, then the weights are not saved. Whenever the loss is reduced then those weights are saved to the checkpoint file" }, { "code": null, "e": 4783, "s": 4747, "text": "Evaluating the model on test images" }, { "code": null, "e": 4852, "s": 4783, "text": "loss,acc = model_ckpt.evaluate(test_images, test_labels, verbose=2)" }, { "code": null, "e": 4960, "s": 4852, "text": "Checkpoint file stores the trained weights to a collection of checkpoint formatted files in a binary format" }, { "code": null, "e": 5121, "s": 4960, "text": "The TensorFlow save() saves three kinds of files: checkpoint file, index file, and data file. It stores the graph structure separately from the variable values." }, { "code": null, "e": 5217, "s": 5121, "text": "checkpoint file: contains prefixes for both an index file as well as for one or more data files" }, { "code": null, "e": 5387, "s": 5217, "text": "Index files: indicates which weights are stored in which shard. As I trained the model on one machine, we see cp.ckpt.data-00000-of-00002 and cp.ckpt.data-00001-of-00002" }, { "code": null, "e": 5493, "s": 5387, "text": "data file: saves values for all the variables, without the structure. There can be one or more data files" }, { "code": null, "e": 5537, "s": 5493, "text": "Reasons for loading the pre-trained weights" }, { "code": null, "e": 5572, "s": 5537, "text": "Continue from where we left off or" }, { "code": null, "e": 5604, "s": 5572, "text": "Resume after an interruption or" }, { "code": null, "e": 5646, "s": 5604, "text": "Load the pre-trained weight for inference" }, { "code": null, "e": 5701, "s": 5646, "text": "We create a new model to load the pre-trained weights." }, { "code": null, "e": 5827, "s": 5701, "text": "When loading a new model with the pre-trained weights, the new model should have the same architecture as the original model." }, { "code": null, "e": 5887, "s": 5827, "text": "# Create a basic model instancemodel_ckpt2 = create_model()" }, { "code": null, "e": 5960, "s": 5887, "text": "We load the pre-trained weights into our new model using load_weights()." }, { "code": null, "e": 6002, "s": 5960, "text": "model_ckpt2.load_weights(checkpoint_path)" }, { "code": null, "e": 6064, "s": 6002, "text": "We can make inferences using the new model on the test images" }, { "code": null, "e": 6193, "s": 6064, "text": "loss,acc = model_ckpt2.evaluate(test_images, test_labels, verbose=2)print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))" }, { "code": null, "e": 6258, "s": 6193, "text": "An untrained model will perform at chance levels (~10% accuracy)" }, { "code": null, "e": 6444, "s": 6258, "text": "model_ckpt2.fit(train_images, train_labels, batch_size=64, epochs=10, validation_data=(test_images,test_labels), callbacks=[cp_callback])" }, { "code": null, "e": 6485, "s": 6444, "text": "we see that the accuracy has changed now" }, { "code": null, "e": 6614, "s": 6485, "text": "loss,acc = model_ckpt2.evaluate(test_images, test_labels, verbose=2)print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))" }, { "code": null, "e": 6687, "s": 6614, "text": "latest_checkoint() find the filename of the latest saved checkpoint file" }, { "code": null, "e": 6819, "s": 6687, "text": "#get the latest checkpoint filecheckpoint_dir = os.path.dirname(checkpoint_path)latest = tf.train.latest_checkpoint(checkpoint_dir)" }, { "code": null, "e": 6906, "s": 6819, "text": "We create a new model, load the weights from the latest checkpoint and make inferences" }, { "code": null, "e": 7217, "s": 6906, "text": "Create a new model instancemodel_latest_checkpoint = create_model()# Load the previously saved weightsmodel_latest_checkpoint.load_weights(latest)# Re-evaluate the modelloss, acc = model_latest_checkpoint.evaluate(test_images, test_labels, verbose=2)print(\"Restored model, accuracy: {:5.2f}%\".format(100*acc))" }, { "code": null, "e": 7256, "s": 7217, "text": "Including epoch number in the filename" }, { "code": null, "e": 7362, "s": 7256, "text": "# Include the epoch in the file name (uses `str.format`)checkpoint_path = \"training2/cp-{epoch:04d}.ckpt\"" }, { "code": null, "e": 7428, "s": 7362, "text": "code for saving the model and reloading model using Fashion MNIST" } ]
Compare two Files line by line in Python - GeeksforGeeks
17 Feb, 2021 In Python, there are many methods available to this comparison. In this Article, We’ll find out how to Compare two different files line by line. Python supports many modules to do so and here we will discuss approaches using its various modules. This article uses two sample files for implementation. Files in use: file.txt file1.txt Python has a Module which is specially used for comparing the differences between the files. To get differences using the difflib library, we have to call the unified_diff() function to this comparison. Syntax: unified_diff(file1, file2, fromfile, tofile, lineterm) Parameter: file1: List of String such as file_1_text file2: List of String such as file_2_text fromfile: first file name with extension tofile: second file name with extension lineterm: argument to “” so that the output will be automcally uniformly newline free Approach Import module Open files Compare using unified_diff() with appropriate attributes Example: Python3 # Importing difflibimport difflib with open('file1.txt') as file_1: file_1_text = file_1.readlines() with open('file2.txt') as file_2: file_2_text = file_2.readlines() # Find and print the diff:for line in difflib.unified_diff( file_1_text, file_2_text, fromfile='file1.txt', tofile='file2.txt', lineterm=''): print(line) Output: — file1.txt +++ file2.txt @@ -1,5 +1,5 @@ Learning Python is -too -simple. +so +easy. There is one Class available for comparing the differences between the files which named as Differ inside the difflib library. This class is used for comparing sequences of lines of text, and producing human-readable differences or deltas. ‘-‘ ‘+’ ‘ ‘ ‘?’ Approach Import module Open files Read contents line bt line Call compare function with the use of differ class object Example: Python3 from difflib import Differ with open('file1.txt') as file_1, open('file2.txt') as file_2: differ = Differ() for line in differ.compare(file_1.readlines(), file_2.readlines()): print(line) Output: Learning Python is – too – simple. + so + easy. Approach Open both files in read mode Store list of strings Start comparing both files with the help of intersection() method for common strings Compare both files for differences using while loop Close both files Example: Python3 # Open File in Read Modefile_1 = open('file1.txt', 'r')file_2 = open('file2.txt', 'r') print("Comparing files ", " @ " + 'file1.txt', " # " + 'file2.txt', sep='\n') file_1_line = file_1.readline()file_2_line = file_2.readline() # Use as a COunterline_no = 1 print() with open('file1.txt') as file1: with open('file2.txt') as file2: same = set(file1).intersection(file2) print("Common Lines in Both Files") for line in same: print(line, end='') print('\n')print("Difference Lines in Both Files")while file_1_line != '' or file_2_line != '': # Removing whitespaces file_1_line = file_1_line.rstrip() file_2_line = file_2_line.rstrip() # Compare the lines from both file if file_1_line != file_2_line: # otherwise output the line on file1 and use @ sign if file_1_line == '': print("@", "Line-%d" % line_no, file_1_line) else: print("@-", "Line-%d" % line_no, file_1_line) # otherwise output the line on file2 and use # sign if file_2_line == '': print("#", "Line-%d" % line_no, file_2_line) else: print("#+", "Line-%d" % line_no, file_2_line) # Print a empty line print() # Read the next line from the file file_1_line = file_1.readline() file_2_line = file_2.readline() line_no += 1 file_1.close()file_2.close() Output: Comparing files @ file1.txt # file2.txt Common Lines in Both Files Learning Python is Difference Lines in Both Files @- Line-4 too #+ Line-4 so @- Line-5 simple. #+ Line-5 easy. Picked Python file-handling-programs python-file-handling Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24225, "s": 24197, "text": "\n17 Feb, 2021" }, { "code": null, "e": 24471, "s": 24225, "text": "In Python, there are many methods available to this comparison. In this Article, We’ll find out how to Compare two different files line by line. Python supports many modules to do so and here we will discuss approaches using its various modules." }, { "code": null, "e": 24526, "s": 24471, "text": "This article uses two sample files for implementation." }, { "code": null, "e": 24540, "s": 24526, "text": "Files in use:" }, { "code": null, "e": 24549, "s": 24540, "text": "file.txt" }, { "code": null, "e": 24559, "s": 24549, "text": "file1.txt" }, { "code": null, "e": 24764, "s": 24559, "text": "Python has a Module which is specially used for comparing the differences between the files. To get differences using the difflib library, we have to call the unified_diff() function to this comparison. " }, { "code": null, "e": 24772, "s": 24764, "text": "Syntax:" }, { "code": null, "e": 24827, "s": 24772, "text": "unified_diff(file1, file2, fromfile, tofile, lineterm)" }, { "code": null, "e": 24838, "s": 24827, "text": "Parameter:" }, { "code": null, "e": 24880, "s": 24838, "text": "file1: List of String such as file_1_text" }, { "code": null, "e": 24922, "s": 24880, "text": "file2: List of String such as file_2_text" }, { "code": null, "e": 24963, "s": 24922, "text": "fromfile: first file name with extension" }, { "code": null, "e": 25003, "s": 24963, "text": "tofile: second file name with extension" }, { "code": null, "e": 25089, "s": 25003, "text": "lineterm: argument to “” so that the output will be automcally uniformly newline free" }, { "code": null, "e": 25098, "s": 25089, "text": "Approach" }, { "code": null, "e": 25112, "s": 25098, "text": "Import module" }, { "code": null, "e": 25123, "s": 25112, "text": "Open files" }, { "code": null, "e": 25180, "s": 25123, "text": "Compare using unified_diff() with appropriate attributes" }, { "code": null, "e": 25189, "s": 25180, "text": "Example:" }, { "code": null, "e": 25197, "s": 25189, "text": "Python3" }, { "code": "# Importing difflibimport difflib with open('file1.txt') as file_1: file_1_text = file_1.readlines() with open('file2.txt') as file_2: file_2_text = file_2.readlines() # Find and print the diff:for line in difflib.unified_diff( file_1_text, file_2_text, fromfile='file1.txt', tofile='file2.txt', lineterm=''): print(line)", "e": 25546, "s": 25197, "text": null }, { "code": null, "e": 25554, "s": 25546, "text": "Output:" }, { "code": null, "e": 25566, "s": 25554, "text": "— file1.txt" }, { "code": null, "e": 25580, "s": 25566, "text": "+++ file2.txt" }, { "code": null, "e": 25596, "s": 25580, "text": "@@ -1,5 +1,5 @@" }, { "code": null, "e": 25606, "s": 25596, "text": " Learning" }, { "code": null, "e": 25614, "s": 25606, "text": " Python" }, { "code": null, "e": 25618, "s": 25614, "text": " is" }, { "code": null, "e": 25623, "s": 25618, "text": "-too" }, { "code": null, "e": 25632, "s": 25623, "text": "-simple." }, { "code": null, "e": 25636, "s": 25632, "text": "+so" }, { "code": null, "e": 25643, "s": 25636, "text": "+easy." }, { "code": null, "e": 25883, "s": 25643, "text": "There is one Class available for comparing the differences between the files which named as Differ inside the difflib library. This class is used for comparing sequences of lines of text, and producing human-readable differences or deltas." }, { "code": null, "e": 25887, "s": 25883, "text": "‘-‘" }, { "code": null, "e": 25891, "s": 25887, "text": "‘+’" }, { "code": null, "e": 25895, "s": 25891, "text": "‘ ‘" }, { "code": null, "e": 25899, "s": 25895, "text": "‘?’" }, { "code": null, "e": 25908, "s": 25899, "text": "Approach" }, { "code": null, "e": 25922, "s": 25908, "text": "Import module" }, { "code": null, "e": 25933, "s": 25922, "text": "Open files" }, { "code": null, "e": 25960, "s": 25933, "text": "Read contents line bt line" }, { "code": null, "e": 26018, "s": 25960, "text": "Call compare function with the use of differ class object" }, { "code": null, "e": 26027, "s": 26018, "text": "Example:" }, { "code": null, "e": 26035, "s": 26027, "text": "Python3" }, { "code": "from difflib import Differ with open('file1.txt') as file_1, open('file2.txt') as file_2: differ = Differ() for line in differ.compare(file_1.readlines(), file_2.readlines()): print(line)", "e": 26239, "s": 26035, "text": null }, { "code": null, "e": 26247, "s": 26239, "text": "Output:" }, { "code": null, "e": 26256, "s": 26247, "text": "Learning" }, { "code": null, "e": 26263, "s": 26256, "text": "Python" }, { "code": null, "e": 26266, "s": 26263, "text": "is" }, { "code": null, "e": 26272, "s": 26266, "text": "– too" }, { "code": null, "e": 26282, "s": 26272, "text": "– simple." }, { "code": null, "e": 26287, "s": 26282, "text": "+ so" }, { "code": null, "e": 26295, "s": 26287, "text": "+ easy." }, { "code": null, "e": 26304, "s": 26295, "text": "Approach" }, { "code": null, "e": 26333, "s": 26304, "text": "Open both files in read mode" }, { "code": null, "e": 26355, "s": 26333, "text": "Store list of strings" }, { "code": null, "e": 26440, "s": 26355, "text": "Start comparing both files with the help of intersection() method for common strings" }, { "code": null, "e": 26492, "s": 26440, "text": "Compare both files for differences using while loop" }, { "code": null, "e": 26509, "s": 26492, "text": "Close both files" }, { "code": null, "e": 26518, "s": 26509, "text": "Example:" }, { "code": null, "e": 26526, "s": 26518, "text": "Python3" }, { "code": "# Open File in Read Modefile_1 = open('file1.txt', 'r')file_2 = open('file2.txt', 'r') print(\"Comparing files \", \" @ \" + 'file1.txt', \" # \" + 'file2.txt', sep='\\n') file_1_line = file_1.readline()file_2_line = file_2.readline() # Use as a COunterline_no = 1 print() with open('file1.txt') as file1: with open('file2.txt') as file2: same = set(file1).intersection(file2) print(\"Common Lines in Both Files\") for line in same: print(line, end='') print('\\n')print(\"Difference Lines in Both Files\")while file_1_line != '' or file_2_line != '': # Removing whitespaces file_1_line = file_1_line.rstrip() file_2_line = file_2_line.rstrip() # Compare the lines from both file if file_1_line != file_2_line: # otherwise output the line on file1 and use @ sign if file_1_line == '': print(\"@\", \"Line-%d\" % line_no, file_1_line) else: print(\"@-\", \"Line-%d\" % line_no, file_1_line) # otherwise output the line on file2 and use # sign if file_2_line == '': print(\"#\", \"Line-%d\" % line_no, file_2_line) else: print(\"#+\", \"Line-%d\" % line_no, file_2_line) # Print a empty line print() # Read the next line from the file file_1_line = file_1.readline() file_2_line = file_2.readline() line_no += 1 file_1.close()file_2.close()", "e": 27918, "s": 26526, "text": null }, { "code": null, "e": 27926, "s": 27918, "text": "Output:" }, { "code": null, "e": 27943, "s": 27926, "text": "Comparing files " }, { "code": null, "e": 27956, "s": 27943, "text": " @ file1.txt" }, { "code": null, "e": 27969, "s": 27956, "text": " # file2.txt" }, { "code": null, "e": 27996, "s": 27969, "text": "Common Lines in Both Files" }, { "code": null, "e": 28005, "s": 27996, "text": "Learning" }, { "code": null, "e": 28012, "s": 28005, "text": "Python" }, { "code": null, "e": 28015, "s": 28012, "text": "is" }, { "code": null, "e": 28046, "s": 28015, "text": "Difference Lines in Both Files" }, { "code": null, "e": 28060, "s": 28046, "text": "@- Line-4 too" }, { "code": null, "e": 28073, "s": 28060, "text": "#+ Line-4 so" }, { "code": null, "e": 28091, "s": 28073, "text": "@- Line-5 simple." }, { "code": null, "e": 28107, "s": 28091, "text": "#+ Line-5 easy." }, { "code": null, "e": 28114, "s": 28107, "text": "Picked" }, { "code": null, "e": 28144, "s": 28114, "text": "Python file-handling-programs" }, { "code": null, "e": 28165, "s": 28144, "text": "python-file-handling" }, { "code": null, "e": 28189, "s": 28165, "text": "Technical Scripter 2020" }, { "code": null, "e": 28196, "s": 28189, "text": "Python" }, { "code": null, "e": 28215, "s": 28196, "text": "Technical Scripter" }, { "code": null, "e": 28313, "s": 28215, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28322, "s": 28313, "text": "Comments" }, { "code": null, "e": 28335, "s": 28322, "text": "Old Comments" }, { "code": null, "e": 28353, "s": 28335, "text": "Python Dictionary" }, { "code": null, "e": 28388, "s": 28353, "text": "Read a file line by line in Python" }, { "code": null, "e": 28410, "s": 28388, "text": "Enumerate() in Python" }, { "code": null, "e": 28442, "s": 28410, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28472, "s": 28442, "text": "Iterate over a list in Python" }, { "code": null, "e": 28514, "s": 28472, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28540, "s": 28514, "text": "Python String | replace()" }, { "code": null, "e": 28583, "s": 28540, "text": "Python program to convert a list to string" }, { "code": null, "e": 28627, "s": 28583, "text": "Reading and Writing to text files in Python" } ]
What is the K-Nearest Neighbor?. An introduction with a Python example | by Andrew Udell | Towards Data Science
K-Nearest Neighbor (KNN) is an easy to understand, but essential and broadly applicable supervised machine learning technique. To understand the intuition behind KNN, examine the scatterplot below. The plot shows the relationship between two arbitrary dimensions, x and y. The blue points represent members of group A and the orange points represent the members of group B. This will represent the training data for KNN. Now suppose a new, unclassified data point is presented and plotted to the graph. The KNN would classify it based on the K nearest points (or, nearest neighbors), take a majority vote, and classify according. Note that K is set beforehand and represents how many points should be taken to make a vote. For example, if K= 1, KNN would look at the nearest data point and classify the new data point as the same classification. In the example below, the “X” represents a new data point for classification. Because the X is closest to a known data point in group B, “X” would also be classified as group B. Now suppose K = 3. KNN would look at the 3 nearest data points and take a vote for classification. If 2 or more of the nearest neighbors belong to a group, the new data point is classified with the majority. In the example below, the new data point “X” moves. Of the 3 nearest points, 2 belong to group A and 1 belongs to group B. Because most of the points belong to group A, the new data point “X” is classified as group A. If a tie occurs (which might happen in K=2), the majority is taken from K-1 nearest neighbors. Non-parametric: KNN makes no assumptions about the underlying data. Consequently, it may be applied to a broad set of problems without the need to worry about the properties of the data. Lazy Learning: The algorithm has no training phase. Instead, it makes a calculation at the moment of classification. This allows KNN to be a pretty dynamic machine learning technique by allowing additional data to be added without the need to re-train it. Highly Non-Linear Data: Because no assumptions are made on the data and because no formal model is calculated, KNN works well to predict highly non-linear data. Multi-Class Problems: Unlike some other algorithms that require tweaking for classifications involving more than 2 classes, KNN can be generalized into as many classes as necessary. Intuitive: the algorithm is relatively simple to understand and interpret even to a non-technical audience. Memory-Intensive: Because a new data point must be compared to every other data point in the training data, KNN often uses a lot of processing power to make a classification, especially on bigger data sets. Curse of Dimensionality: Like other algorithms that use distance as a metric, KNN struggles to predict data with a lot of input variables. Sensitive to Outliers: Outliers present a fundamental issue to KNN. By simply choosing the nearest neighbors, no matter how far they may be, outliers can skew its predictions. Missing Data: KNN has no approach to handle missing data. If anything is missing, the entire data point cannot be predicted accurately. Since K is the only parameter to tune, great care should be given to select a good value. In general, there are two basic suggestions: an estimation and the Elbow Method. As a good point of reference, taking the square root of the number of observations as K is sometimes suggested. For example, if 100 observations are fed into KNN, K = 10 would work as a quick estimation. Note that this is more of a rule of thumb than a rigorous method. The more empirical approach, however, is the Elbow Method. Based on the principle of diminishing margin returns, the idea is to run KNN on test data, progressively increasing the K-value and looking at how it affects model performance. If done visually, then at the “elbow” of the graph (the inflection point in more technical terms), the optimized value for K is represented at the point where the best performance is returned before the cost outweighs the benefit. The red circle on the illustration below demonstrates the principle. Real world data, however, won’t always be as clear. If the data becomes noisier, choosing the smallest possible K at a local minimum is a viable option. As with many other machine learning algorithms, the Scikit-Learn module offers a great implementation of KNN. from sklearn.neighbors import KNeighborsClassifierfrom sklearn.preprocessing import StandardScalerimport pandas as pdimport numpy as np In addition to the KNN module, the StandardScaler is imported for standardize the data, and pandas and numpy are imported to handle the data. # Store the data in a dictionarydata = { "X1": [1,1,3,4,5,2,0,4,0.5,3.3,1.1,4.7,0.2,2,4.5,3.3,2.5], "X2": [1,2,4,4,6,1,1,5,0.5,4.2,1.4,5.2,2,0.03,5.1,4.8,2.5], "Member": [A,A,B,B,B,A,A,B,A,B,A,B,A,A,B,B,A]}# Convert the data into a dataframedf = pd.DataFrame.from_dict(data) Next, the data set is generated and placed into a dictionary. This set of numbers was actually used to generate the examples at the beginning of the article. The dictionary is then converted into a Dataframe for convenience. # Separate the the independent and dependent variablesfeatures = df_sample.filter(["X1", "X2"])category = df_sample["Member"]scaler = StandardScaler()scaler.fit(features)scaled_features = scaler.transform(features) Because KNN uses distance as a metric and because the inputs may not necessarily use the same scale, the standard scaler is called to normalize the numerical data. This is an essential step to prevent bias from units in the data. k = 5knn = KNeighborsClassifier(n_neighbors=k)knn.fit(scaled_features, category) The final step to actually fit the KNN simply calls the function and uses the scaled features and the category as an argument. Note the argument n_neighbors which denotes how many K-nearest neighbors to use. If the Elbow Method should be used, however, a slightly different approach is required. # Separate the data into training and test data setsX_train, X_test, Y_train, Y_test = train_test_split(scaled_features, color_category, test_size=0.30)# Import Matplotlib for visualizationimport matplotlib.pyplot as plt# Create an empty list to catch the error rateerror_rate = []# Iterate through K = 1-20for i in range(1,20): knn = KNeighborsClassifier(n_neighbors=i) knn.fit(X_train,Y_train) pred_i = knn.predict(X_test) error_rate.append(np.mean(pred_i != Y_test))# plot the error rate plt.figure(figsize=(10,6))plt.plot(range(1,20),error_rate,color='blue', linestyle='dashed', marker='o', markerfacecolor='red', markersize=10)plt.title('Error Rate vs. K Value')plt.xlabel('K')plt.ylabel('Error Rate') First, the data is split into training and testing subsets (which should be standard procedure anyway). Next, the model is trained and evaluated on the test data for K = 1, K = 2, and so on until K = 20. Finally, the results are returned on a graph. KNN is a simple, but powerful supervised machine learning technique. Its robust approach allows its application to a wide variety of problems. Additionally, a single parameter, K, makes parameter tuning relatively easily. A simple and easy-to-use implementation in Python makes using KNN a matter of a few lines.
[ { "code": null, "e": 593, "s": 172, "text": "K-Nearest Neighbor (KNN) is an easy to understand, but essential and broadly applicable supervised machine learning technique. To understand the intuition behind KNN, examine the scatterplot below. The plot shows the relationship between two arbitrary dimensions, x and y. The blue points represent members of group A and the orange points represent the members of group B. This will represent the training data for KNN." }, { "code": null, "e": 895, "s": 593, "text": "Now suppose a new, unclassified data point is presented and plotted to the graph. The KNN would classify it based on the K nearest points (or, nearest neighbors), take a majority vote, and classify according. Note that K is set beforehand and represents how many points should be taken to make a vote." }, { "code": null, "e": 1196, "s": 895, "text": "For example, if K= 1, KNN would look at the nearest data point and classify the new data point as the same classification. In the example below, the “X” represents a new data point for classification. Because the X is closest to a known data point in group B, “X” would also be classified as group B." }, { "code": null, "e": 1404, "s": 1196, "text": "Now suppose K = 3. KNN would look at the 3 nearest data points and take a vote for classification. If 2 or more of the nearest neighbors belong to a group, the new data point is classified with the majority." }, { "code": null, "e": 1622, "s": 1404, "text": "In the example below, the new data point “X” moves. Of the 3 nearest points, 2 belong to group A and 1 belongs to group B. Because most of the points belong to group A, the new data point “X” is classified as group A." }, { "code": null, "e": 1717, "s": 1622, "text": "If a tie occurs (which might happen in K=2), the majority is taken from K-1 nearest neighbors." }, { "code": null, "e": 1904, "s": 1717, "text": "Non-parametric: KNN makes no assumptions about the underlying data. Consequently, it may be applied to a broad set of problems without the need to worry about the properties of the data." }, { "code": null, "e": 2160, "s": 1904, "text": "Lazy Learning: The algorithm has no training phase. Instead, it makes a calculation at the moment of classification. This allows KNN to be a pretty dynamic machine learning technique by allowing additional data to be added without the need to re-train it." }, { "code": null, "e": 2321, "s": 2160, "text": "Highly Non-Linear Data: Because no assumptions are made on the data and because no formal model is calculated, KNN works well to predict highly non-linear data." }, { "code": null, "e": 2503, "s": 2321, "text": "Multi-Class Problems: Unlike some other algorithms that require tweaking for classifications involving more than 2 classes, KNN can be generalized into as many classes as necessary." }, { "code": null, "e": 2611, "s": 2503, "text": "Intuitive: the algorithm is relatively simple to understand and interpret even to a non-technical audience." }, { "code": null, "e": 2818, "s": 2611, "text": "Memory-Intensive: Because a new data point must be compared to every other data point in the training data, KNN often uses a lot of processing power to make a classification, especially on bigger data sets." }, { "code": null, "e": 2957, "s": 2818, "text": "Curse of Dimensionality: Like other algorithms that use distance as a metric, KNN struggles to predict data with a lot of input variables." }, { "code": null, "e": 3133, "s": 2957, "text": "Sensitive to Outliers: Outliers present a fundamental issue to KNN. By simply choosing the nearest neighbors, no matter how far they may be, outliers can skew its predictions." }, { "code": null, "e": 3269, "s": 3133, "text": "Missing Data: KNN has no approach to handle missing data. If anything is missing, the entire data point cannot be predicted accurately." }, { "code": null, "e": 3440, "s": 3269, "text": "Since K is the only parameter to tune, great care should be given to select a good value. In general, there are two basic suggestions: an estimation and the Elbow Method." }, { "code": null, "e": 3710, "s": 3440, "text": "As a good point of reference, taking the square root of the number of observations as K is sometimes suggested. For example, if 100 observations are fed into KNN, K = 10 would work as a quick estimation. Note that this is more of a rule of thumb than a rigorous method." }, { "code": null, "e": 3946, "s": 3710, "text": "The more empirical approach, however, is the Elbow Method. Based on the principle of diminishing margin returns, the idea is to run KNN on test data, progressively increasing the K-value and looking at how it affects model performance." }, { "code": null, "e": 4246, "s": 3946, "text": "If done visually, then at the “elbow” of the graph (the inflection point in more technical terms), the optimized value for K is represented at the point where the best performance is returned before the cost outweighs the benefit. The red circle on the illustration below demonstrates the principle." }, { "code": null, "e": 4399, "s": 4246, "text": "Real world data, however, won’t always be as clear. If the data becomes noisier, choosing the smallest possible K at a local minimum is a viable option." }, { "code": null, "e": 4509, "s": 4399, "text": "As with many other machine learning algorithms, the Scikit-Learn module offers a great implementation of KNN." }, { "code": null, "e": 4645, "s": 4509, "text": "from sklearn.neighbors import KNeighborsClassifierfrom sklearn.preprocessing import StandardScalerimport pandas as pdimport numpy as np" }, { "code": null, "e": 4787, "s": 4645, "text": "In addition to the KNN module, the StandardScaler is imported for standardize the data, and pandas and numpy are imported to handle the data." }, { "code": null, "e": 5071, "s": 4787, "text": "# Store the data in a dictionarydata = { \"X1\": [1,1,3,4,5,2,0,4,0.5,3.3,1.1,4.7,0.2,2,4.5,3.3,2.5], \"X2\": [1,2,4,4,6,1,1,5,0.5,4.2,1.4,5.2,2,0.03,5.1,4.8,2.5], \"Member\": [A,A,B,B,B,A,A,B,A,B,A,B,A,A,B,B,A]}# Convert the data into a dataframedf = pd.DataFrame.from_dict(data)" }, { "code": null, "e": 5296, "s": 5071, "text": "Next, the data set is generated and placed into a dictionary. This set of numbers was actually used to generate the examples at the beginning of the article. The dictionary is then converted into a Dataframe for convenience." }, { "code": null, "e": 5511, "s": 5296, "text": "# Separate the the independent and dependent variablesfeatures = df_sample.filter([\"X1\", \"X2\"])category = df_sample[\"Member\"]scaler = StandardScaler()scaler.fit(features)scaled_features = scaler.transform(features)" }, { "code": null, "e": 5741, "s": 5511, "text": "Because KNN uses distance as a metric and because the inputs may not necessarily use the same scale, the standard scaler is called to normalize the numerical data. This is an essential step to prevent bias from units in the data." }, { "code": null, "e": 5822, "s": 5741, "text": "k = 5knn = KNeighborsClassifier(n_neighbors=k)knn.fit(scaled_features, category)" }, { "code": null, "e": 6030, "s": 5822, "text": "The final step to actually fit the KNN simply calls the function and uses the scaled features and the category as an argument. Note the argument n_neighbors which denotes how many K-nearest neighbors to use." }, { "code": null, "e": 6118, "s": 6030, "text": "If the Elbow Method should be used, however, a slightly different approach is required." }, { "code": null, "e": 6841, "s": 6118, "text": "# Separate the data into training and test data setsX_train, X_test, Y_train, Y_test = train_test_split(scaled_features, color_category, test_size=0.30)# Import Matplotlib for visualizationimport matplotlib.pyplot as plt# Create an empty list to catch the error rateerror_rate = []# Iterate through K = 1-20for i in range(1,20): knn = KNeighborsClassifier(n_neighbors=i) knn.fit(X_train,Y_train) pred_i = knn.predict(X_test) error_rate.append(np.mean(pred_i != Y_test))# plot the error rate plt.figure(figsize=(10,6))plt.plot(range(1,20),error_rate,color='blue', linestyle='dashed', marker='o', markerfacecolor='red', markersize=10)plt.title('Error Rate vs. K Value')plt.xlabel('K')plt.ylabel('Error Rate')" }, { "code": null, "e": 7091, "s": 6841, "text": "First, the data is split into training and testing subsets (which should be standard procedure anyway). Next, the model is trained and evaluated on the test data for K = 1, K = 2, and so on until K = 20. Finally, the results are returned on a graph." } ]
How to get device id in android?
This example demonstrate about How to get device id in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <TextView android:id="@+id/text" android:textSize="30sp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have taken a text view to show device id. Step 3 − Add the following code to java/MainActivity.xml package com.example.myapplication; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.telephony.TelephonyManager; import android.widget.TextView; import static android.Manifest.permission.READ_PHONE_NUMBERS; import static android.Manifest.permission.READ_PHONE_STATE; import static android.Manifest.permission.READ_SMS; public class MainActivity extends AppCompatActivity { private static final int PERMISSION_REQUEST_CODE = 100; TextView textView; TelephonyManager telephonyManager; @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); if (ActivityCompat.checkSelfPermission(this, READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{READ_SMS, READ_PHONE_NUMBERS, READ_PHONE_STATE}, PERMISSION_REQUEST_CODE); } else { textView.setText(""+telephonyManager.getDeviceId()); } } @RequiresApi(api = Build.VERSION_CODES.P) @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case PERMISSION_REQUEST_CODE: if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return; } else { textView.setText(""+telephonyManager.getDeviceId()); } } } } Step 3 − Add the following code toAndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapplication"> <uses-permission android:name="android.permission.READ_PHONE_NUMBERS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <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 Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1126, "s": 1062, "text": "This example demonstrate about How to get device id in android." }, { "code": null, "e": 1255, "s": 1126, "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": 1320, "s": 1255, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1888, "s": 1320, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:gravity=\"center\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"30sp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 1952, "s": 1888, "text": "In the above code, we have taken a text view to show device id." }, { "code": null, "e": 2009, "s": 1952, "text": "Step 3 − Add the following code to java/MainActivity.xml" }, { "code": null, "e": 4585, "s": 2009, "text": "package com.example.myapplication;\n\nimport android.Manifest;\nimport android.content.Context;\nimport android.content.pm.PackageManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.telephony.TelephonyManager;\nimport android.widget.TextView;\n\nimport static android.Manifest.permission.READ_PHONE_NUMBERS;\nimport static android.Manifest.permission.READ_PHONE_STATE;\nimport static android.Manifest.permission.READ_SMS;\n\npublic class MainActivity extends AppCompatActivity {\n private static final int PERMISSION_REQUEST_CODE = 100;\n TextView textView;\n TelephonyManager telephonyManager;\n\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);\n if (ActivityCompat.checkSelfPermission(this, READ_SMS) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {\n ActivityCompat.requestPermissions(this, new String[]{READ_SMS, READ_PHONE_NUMBERS, READ_PHONE_STATE}, PERMISSION_REQUEST_CODE);\n } else {\n textView.setText(\"\"+telephonyManager.getDeviceId());\n }\n }\n\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n switch (requestCode) {\n case PERMISSION_REQUEST_CODE:\n if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) !=\n PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,\n Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) !=\n PackageManager.PERMISSION_GRANTED) {\n return;\n } else {\n textView.setText(\"\"+telephonyManager.getDeviceId());\n }\n }\n }\n}" }, { "code": null, "e": 4639, "s": 4585, "text": "Step 3 − Add the following code toAndroidManifest.xml" }, { "code": null, "e": 5471, "s": 4639, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"com.example.myapplication\">\n\n <uses-permission android:name=\"android.permission.READ_PHONE_NUMBERS\" />\n <uses-permission android:name=\"android.permission.READ_PHONE_STATE\" />\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": 5818, "s": 5471, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 5858, "s": 5818, "text": "Click here to download the project code" } ]
Keras - Model Evaluation and Model Prediction
This chapter deals with the model evaluation and model prediction in Keras. Let us begin by understanding the model evaluation. Evaluation is a process during development of the model to check whether the model is best fit for the given problem and corresponding data. Keras model provides a function, evaluate which does the evaluation of the model. It has three main arguments, Test data Test data label verbose - true or false Let us evaluate the model, which we created in the previous chapter using test data. score = model.evaluate(x_test, y_test, verbose = 0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) Executing the above code will output the below information. 0 The test accuracy is 98.28%. We have created a best model to identify the handwriting digits. On the positive side, we can still scope to improve our model. Prediction is the final step and our expected outcome of the model generation. Keras provides a method, predict to get the prediction of the trained model. The signature of the predict method is as follows, predict( x, batch_size = None, verbose = 0, steps = None, callbacks = None, max_queue_size = 10, workers = 1, use_multiprocessing = False ) Here, all arguments are optional except the first argument, which refers the unknown input data. The shape should be maintained to get the proper prediction. Let us do prediction for our MPL model created in previous chapter using below code − pred = model.predict(x_test) pred = np.argmax(pred, axis = 1)[:5] label = np.argmax(y_test,axis = 1)[:5] print(pred) print(label) Here, Line 1 call the predict function using test data. Line 1 call the predict function using test data. Line 2 gets the first five prediction Line 2 gets the first five prediction Line 3 gets the first five labels of the test data. Line 3 gets the first five labels of the test data. Line 5 - 6 prints the prediction and actual label. Line 5 - 6 prints the prediction and actual label. The output of the above application is as follows − [7 2 1 0 4] [7 2 1 0 4] The output of both array is identical and it indicate that our model predicts correctly the first five images. 87 Lectures 11 hours Abhilash Nelson 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 68 Lectures 2 hours Mike West Print Add Notes Bookmark this page
[ { "code": null, "e": 2127, "s": 2051, "text": "This chapter deals with the model evaluation and model prediction in Keras." }, { "code": null, "e": 2179, "s": 2127, "text": "Let us begin by understanding the model evaluation." }, { "code": null, "e": 2431, "s": 2179, "text": "Evaluation is a process during development of the model to check whether the model is best fit for the given problem and corresponding data. Keras model provides a function, evaluate which does the evaluation of the model. It has three main arguments," }, { "code": null, "e": 2441, "s": 2431, "text": "Test data" }, { "code": null, "e": 2457, "s": 2441, "text": "Test data label" }, { "code": null, "e": 2481, "s": 2457, "text": "verbose - true or false" }, { "code": null, "e": 2566, "s": 2481, "text": "Let us evaluate the model, which we created in the previous chapter using test data." }, { "code": null, "e": 2685, "s": 2566, "text": "score = model.evaluate(x_test, y_test, verbose = 0) \n\nprint('Test loss:', score[0]) \nprint('Test accuracy:', score[1])" }, { "code": null, "e": 2745, "s": 2685, "text": "Executing the above code will output the below information." }, { "code": null, "e": 2748, "s": 2745, "text": "0\n" }, { "code": null, "e": 2905, "s": 2748, "text": "The test accuracy is 98.28%. We have created a best model to identify the handwriting digits. On the positive side, we can still scope to improve our model." }, { "code": null, "e": 3112, "s": 2905, "text": "Prediction is the final step and our expected outcome of the model generation. Keras provides a method, predict to get the prediction of the trained model. The signature of the predict method is as follows," }, { "code": null, "e": 3283, "s": 3112, "text": "predict(\n x, \n batch_size = None, \n verbose = 0, \n steps = None, \n callbacks = None, \n max_queue_size = 10, \n workers = 1, \n use_multiprocessing = False\n)" }, { "code": null, "e": 3441, "s": 3283, "text": "Here, all arguments are optional except the first argument, which refers the unknown input data. The shape should be maintained to get the proper prediction." }, { "code": null, "e": 3527, "s": 3441, "text": "Let us do prediction for our MPL model created in previous chapter using below code −" }, { "code": null, "e": 3662, "s": 3527, "text": "pred = model.predict(x_test) \npred = np.argmax(pred, axis = 1)[:5] \nlabel = np.argmax(y_test,axis = 1)[:5] \n\nprint(pred) \nprint(label)" }, { "code": null, "e": 3668, "s": 3662, "text": "Here," }, { "code": null, "e": 3718, "s": 3668, "text": "Line 1 call the predict function using test data." }, { "code": null, "e": 3768, "s": 3718, "text": "Line 1 call the predict function using test data." }, { "code": null, "e": 3806, "s": 3768, "text": "Line 2 gets the first five prediction" }, { "code": null, "e": 3844, "s": 3806, "text": "Line 2 gets the first five prediction" }, { "code": null, "e": 3896, "s": 3844, "text": "Line 3 gets the first five labels of the test data." }, { "code": null, "e": 3948, "s": 3896, "text": "Line 3 gets the first five labels of the test data." }, { "code": null, "e": 3999, "s": 3948, "text": "Line 5 - 6 prints the prediction and actual label." }, { "code": null, "e": 4050, "s": 3999, "text": "Line 5 - 6 prints the prediction and actual label." }, { "code": null, "e": 4102, "s": 4050, "text": "The output of the above application is as follows −" }, { "code": null, "e": 4128, "s": 4102, "text": "[7 2 1 0 4] \n[7 2 1 0 4]\n" }, { "code": null, "e": 4239, "s": 4128, "text": "The output of both array is identical and it indicate that our model predicts correctly the first five images." }, { "code": null, "e": 4273, "s": 4239, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 4290, "s": 4273, "text": " Abhilash Nelson" }, { "code": null, "e": 4323, "s": 4290, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 4345, "s": 4323, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4378, "s": 4345, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 4400, "s": 4378, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4433, "s": 4400, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 4455, "s": 4433, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4488, "s": 4455, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 4510, "s": 4488, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4543, "s": 4510, "text": "\n 68 Lectures \n 2 hours \n" }, { "code": null, "e": 4554, "s": 4543, "text": " Mike West" }, { "code": null, "e": 4561, "s": 4554, "text": " Print" }, { "code": null, "e": 4572, "s": 4561, "text": " Add Notes" } ]
Docker + OpenCV: Real-Time Facial Recognition in 1 minute | by Chamal Gomes | Towards Data Science
Integrating Docker, OpenCV.js and Nginx for quick deployment of real-time facial recognition machine learning models. This is a convenient solution for the Mac Docker community who is struggling to get webcam access due to the drawbacks of the Docker hyper kit support with the help of Nginx. This solution could easily be extended to include any readymade machine learning model from OpenCV, Keras, Tensorflow, etc.. Motivation: The process of building OpenCV.js from source, though recommended, requires LLVM-to-JavaScript compiler and CMAKE which is quite involved.Accessing the Mac webcam from Docker container was not possible due to the drawbacks of the Docker hyper kit support. Thus, deploying real-time facial recognition models was not possible on a Mac. The process of building OpenCV.js from source, though recommended, requires LLVM-to-JavaScript compiler and CMAKE which is quite involved. Accessing the Mac webcam from Docker container was not possible due to the drawbacks of the Docker hyper kit support. Thus, deploying real-time facial recognition models was not possible on a Mac. Hence, I decided to make it easy as possible for anyone to deploy an OpenCV model with the help of Docker within a matter of seconds. I overcame point 1 by using a nightly build and point 2 with the use of Nginx. This is strictly designed to acquaint the reader on the deployment aspect of machine learning with Docker and is NOT concerned with building a machine learning model for facial recognition. Project Structure: Clone the project from the Github repo here. . ├── Version1 │ ├── Dockerfile #Building the image │ ├── docker-compose.yml #Defining the files for mounting │ ├── CV #OpenCV.js soure code| ├──js_face_recognition.html| ├──opencv.js| ├──utils.js Dockerfile Dockerfile 2. docker-compose.yml Please update the path to your project folder in this file. Note Nginx server is set to run on port 80. The CV folder resides the source code for the project inclusive of the nightly build of OpenCV.js. I have used the facial recognition code from the tutorials of OpenCV.js official site, it is available from the official GitHub repo of OpenCV as well. The tutorials they provide is really helpful and is where I learned most of the OpenCV.js applications. #Clone the repo git clone git@github.com:gomesc166/MediumRepo.git#Go to ObjectDetection directory cd Version1 #Build the imagedocker build -t object-detection-image . #Start the Containerdocker-compose up NOTE: Edit the path to the project on your host. Visit localhost:80 on your browser Click the download model button. Once the model is downloaded you can add as many people as you like for the recognition. If you want to add your custom Keras/Tensorflow models, you will have to tweak the JS scripts. If you have any concerns regarding the code please leave a response and I will get back to you. I have used the JS script from the tutorials at the official OpenCV.js. Keep in mind the key objective of this post is to acquaint the user on how to deploy ready-made models easily with Docker and overcome the Docker hyper kit limitations when using on Mac. Cheers..
[ { "code": null, "e": 590, "s": 172, "text": "Integrating Docker, OpenCV.js and Nginx for quick deployment of real-time facial recognition machine learning models. This is a convenient solution for the Mac Docker community who is struggling to get webcam access due to the drawbacks of the Docker hyper kit support with the help of Nginx. This solution could easily be extended to include any readymade machine learning model from OpenCV, Keras, Tensorflow, etc.." }, { "code": null, "e": 602, "s": 590, "text": "Motivation:" }, { "code": null, "e": 937, "s": 602, "text": "The process of building OpenCV.js from source, though recommended, requires LLVM-to-JavaScript compiler and CMAKE which is quite involved.Accessing the Mac webcam from Docker container was not possible due to the drawbacks of the Docker hyper kit support. Thus, deploying real-time facial recognition models was not possible on a Mac." }, { "code": null, "e": 1076, "s": 937, "text": "The process of building OpenCV.js from source, though recommended, requires LLVM-to-JavaScript compiler and CMAKE which is quite involved." }, { "code": null, "e": 1273, "s": 1076, "text": "Accessing the Mac webcam from Docker container was not possible due to the drawbacks of the Docker hyper kit support. Thus, deploying real-time facial recognition models was not possible on a Mac." }, { "code": null, "e": 1676, "s": 1273, "text": "Hence, I decided to make it easy as possible for anyone to deploy an OpenCV model with the help of Docker within a matter of seconds. I overcame point 1 by using a nightly build and point 2 with the use of Nginx. This is strictly designed to acquaint the reader on the deployment aspect of machine learning with Docker and is NOT concerned with building a machine learning model for facial recognition." }, { "code": null, "e": 1740, "s": 1676, "text": "Project Structure: Clone the project from the Github repo here." }, { "code": null, "e": 2017, "s": 1740, "text": ". ├── Version1 │ ├── Dockerfile #Building the image │ ├── docker-compose.yml #Defining the files for mounting │ ├── CV #OpenCV.js soure code| ├──js_face_recognition.html| ├──opencv.js| ├──utils.js" }, { "code": null, "e": 2028, "s": 2017, "text": "Dockerfile" }, { "code": null, "e": 2039, "s": 2028, "text": "Dockerfile" }, { "code": null, "e": 2061, "s": 2039, "text": "2. docker-compose.yml" }, { "code": null, "e": 2165, "s": 2061, "text": "Please update the path to your project folder in this file. Note Nginx server is set to run on port 80." }, { "code": null, "e": 2520, "s": 2165, "text": "The CV folder resides the source code for the project inclusive of the nightly build of OpenCV.js. I have used the facial recognition code from the tutorials of OpenCV.js official site, it is available from the official GitHub repo of OpenCV as well. The tutorials they provide is really helpful and is where I learned most of the OpenCV.js applications." }, { "code": null, "e": 2630, "s": 2520, "text": "#Clone the repo git clone git@github.com:gomesc166/MediumRepo.git#Go to ObjectDetection directory cd Version1" }, { "code": null, "e": 2687, "s": 2630, "text": "#Build the imagedocker build -t object-detection-image ." }, { "code": null, "e": 2725, "s": 2687, "text": "#Start the Containerdocker-compose up" }, { "code": null, "e": 2774, "s": 2725, "text": "NOTE: Edit the path to the project on your host." }, { "code": null, "e": 2809, "s": 2774, "text": "Visit localhost:80 on your browser" }, { "code": null, "e": 3026, "s": 2809, "text": "Click the download model button. Once the model is downloaded you can add as many people as you like for the recognition. If you want to add your custom Keras/Tensorflow models, you will have to tweak the JS scripts." } ]
VB.Net - Forms
Let's start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio - File → New Project → Windows Forms Applications Finally, select OK, Microsoft Visual Studio creates your project and displays following window Form with a name Form1. Visual Basic Form is the container for all the controls that make up the user interface. Every window you see in a running visual basic application is a form, thus the terms form and window describe the same entity. Visual Studio creates a default form for you when you create a Windows Forms Application. Every form will have title bar on which the form's caption is displayed and there will be buttons to close, maximize and minimize the form shown below − If you click the icon on the top left corner, it opens the control menu, which contains the various commands to control the form like to move control from one place to another place, to maximize or minimize the form or to close the form. Following table lists down various important properties related to a form. These properties can be set or read during application execution. You can refer to Microsoft documentation for a complete list of properties associated with a Form control − AcceptButton The button that's automatically activated when you press Enter, no matter which control has the focus at the time. Usually the OK button on a form is set as AcceptButton for a form. CancelButton The button that's automatically activated when you hit the Esc key. Usually, the Cancel button on a form is set as CancelButton for a form. AutoScale This Boolean property determines whether the controls you place on the form are automatically scaled to the height of the current font. The default value of this property is True. This is a property of the form, but it affects the controls on the form. AutoScroll This Boolean property indicates whether scroll bars will be automatically attached to the form if it is resized to a point that not all its controls are visible. AutoScrollMinSize This property lets you specify the minimum size of the form, before the scroll bars are attached. AutoScrollPosition The AutoScrollPosition is the number of pixels by which the two scroll bars were displaced from their initial locations. BackColor Sets the form background color. BorderStyle The BorderStyle property determines the style of the form's border and the appearance of the form − None − Borderless window that can't be resized. None − Borderless window that can't be resized. Sizable − This is default value and will be used for resizable window that's used for displaying regular forms. Sizable − This is default value and will be used for resizable window that's used for displaying regular forms. Fixed3D − Window with a visible border, "raised" relative to the main area. In this case, windows can't be resized. Fixed3D − Window with a visible border, "raised" relative to the main area. In this case, windows can't be resized. FixedDialog − A fixed window, used to create dialog boxes. FixedDialog − A fixed window, used to create dialog boxes. FixedSingle − A fixed window with a single line border. FixedSingle − A fixed window with a single line border. FixedToolWindow − A fixed window with a Close button only. It looks like the toolbar displayed by the drawing and imaging applications. FixedToolWindow − A fixed window with a Close button only. It looks like the toolbar displayed by the drawing and imaging applications. SizableToolWindow − Same as the FixedToolWindow but resizable. In addition, its caption font is smaller than the usual. SizableToolWindow − Same as the FixedToolWindow but resizable. In addition, its caption font is smaller than the usual. ControlBox By default, this property is True and you can set it to False to hide the icon and disable the Control menu. Enabled If True, allows the form to respond to mouse and keyboard events; if False, disables form. Font This property specify font type, style, size HelpButton Determines whether a Help button should be displayed in the caption box of the form. Height This is the height of the Form in pixels. MinimizeBox By default, this property is True and you can set it to False to hide the Minimize button on the title bar. MaximizeBox By default, this property is True and you can set it to False to hide the Maximize button on the title bar. MinimumSize This specifies the minimum height and width of the window you can minimize. MaximumSize This specifies the maximum height and width of the window you maximize. Name This is the actual name of the form. StartPosition This property determines the initial position of the form when it's first displayed. It will have any of the following values − CenterParent − The form is centered in the area of its parent form. CenterParent − The form is centered in the area of its parent form. CenterScreen − The form is centered on the monitor. CenterScreen − The form is centered on the monitor. Manual − The location and size of the form will determine its starting position. Manual − The location and size of the form will determine its starting position. WindowsDefaultBounds − The form is positioned at the default location and size determined by Windows. WindowsDefaultBounds − The form is positioned at the default location and size determined by Windows. WindowsDefaultLocation − The form is positioned at the Windows default location and has the dimensions you've set at design time. WindowsDefaultLocation − The form is positioned at the Windows default location and has the dimensions you've set at design time. Text The text, which will appear at the title bar of the form. Top, Left These two properties set or return the coordinates of the form's top-left corner in pixels. TopMost This property is a True/False value that lets you specify whether the form will remain on top of all other forms in your application. Its default property is False. Width This is the width of the form in pixel. The following are some of the commonly used methods of the Form class. You can refer to Microsoft documentation for a complete list of methods associated with forms control − Activate Activates the form and gives it focus. ActivateMdiChild Activates the MDI child of a form. AddOwnedForm Adds an owned form to this form. BringToFront Brings the control to the front of the z-order. CenterToParent Centers the position of the form within the bounds of the parent form. CenterToScreen Centers the form on the current screen. Close Closes the form. Contains Retrieves a value indicating whether the specified control is a child of the control. Focus Sets input focus to the control. Hide Conceals the control from the user. Refresh Forces the control to invalidate its client area and immediately redraw itself and any child controls. Scale(SizeF) Scales the control and all child controls by the specified scaling factor. ScaleControl Scales the location, size, padding, and margin of a control. ScaleCore Performs scaling of the form. Select Activates the control. SendToBack Sends the control to the back of the z-order. SetAutoScrollMargin Sets the size of the auto-scroll margins. SetDesktopBounds Sets the bounds of the form in desktop coordinates. SetDesktopLocation Sets the location of the form in desktop coordinates. SetDisplayRectLocation Positions the display window to the specified value. Show Displays the control to the user. ShowDialog Shows the form as a modal dialog box. Following table lists down various important events related to a form. You can refer to Microsoft documentation for a complete list of events associated with forms control − Activated Occurs when the form is activated in code or by the user. Click Occurs when the form is clicked. Closed Occurs before the form is closed. Closing Occurs when the form is closing. DoubleClick Occurs when the form control is double-clicked. DragDrop Occurs when a drag-and-drop operation is completed. Enter Occurs when the form is entered. GotFocus Occurs when the form control receives focus. HelpButtonClicked Occurs when the Help button is clicked. KeyDown Occurs when a key is pressed while the form has focus. KeyPress Occurs when a key is pressed while the form has focus. KeyUp Occurs when a key is released while the form has focus. Load Occurs before a form is displayed for the first time. LostFocus Occurs when the form loses focus. MouseDown Occurs when the mouse pointer is over the form and a mouse button is pressed. MouseEnter Occurs when the mouse pointer enters the form. MouseHover Occurs when the mouse pointer rests on the form. MouseLeave Occurs when the mouse pointer leaves the form. MouseMove Occurs when the mouse pointer is moved over the form. MouseUp Occurs when the mouse pointer is over the form and a mouse button is released. MouseWheel Occurs when the mouse wheel moves while the control has focus. Move Occurs when the form is moved. Resize Occurs when the control is resized. Scroll Occurs when the user or code scrolls through the client area. Shown Occurs whenever the form is first displayed. VisibleChanged Occurs when the Visible property value changes. Following is an example, which shows how we create two buttons at the time of form load event and different properties are being set at the same time. Because Form1 is being referenced within its own event handler, so it will be written as Me instead of using its name, but if we access the same form inside any other control's event handler, then it will be accessed using its name Form1. Let's double click on the Form and put the follow code in the opened window. Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Create two buttons to use as the accept and cancel buttons. Dim button1 As New Button() Dim button2 As New Button() ' Set the text of button1 to "OK". button1.Text = "OK" ' Set the position of the button on the form. button1.Location = New Point(10, 10) ' Set the text of button2 to "Cancel". button2.Text = "Cancel" ' Set the position of the button based on the location of button1. button2.Location = _ New Point(button1.Left, button1.Height + button1.Top + 10) ' Set the caption bar text of the form. Me.Text = "tutorialspoint.com" ' Display a help button on the form. Me.HelpButton = True ' Define the border style of the form to a dialog box. Me.FormBorderStyle = FormBorderStyle.FixedDialog ' Set the MaximizeBox to false to remove the maximize box. Me.MaximizeBox = False ' Set the MinimizeBox to false to remove the minimize box. Me.MinimizeBox = False ' Set the accept button of the form to button1. Me.AcceptButton = button1 ' Set the cancel button of the form to button2. Me.CancelButton = button2 ' Set the start position of the form to the center of the screen. Me.StartPosition = FormStartPosition.CenterScreen ' Set window width and height Me.Height = 300 Me.Width = 560 ' Add button1 to the form. Me.Controls.Add(button1) ' Add button2 to the form. Me.Controls.Add(button2) End Sub End Class When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window − 63 Lectures 4 hours Frahaan Hussain 103 Lectures 12 hours Arnold Higuit 60 Lectures 9.5 hours Arnold Higuit 97 Lectures 9 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2464, "s": 2300, "text": "Let's start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio - File → New Project → Windows Forms Applications" }, { "code": null, "e": 2583, "s": 2464, "text": "Finally, select OK, Microsoft Visual Studio creates your project and displays following window Form with a name Form1." }, { "code": null, "e": 2891, "s": 2583, "text": "Visual Basic Form is the container for all the controls that make up the user interface. Every window you see in a running visual basic application is a form, thus the terms form and window describe the same entity. Visual Studio creates a default form for you when you create a Windows Forms Application." }, { "code": null, "e": 3044, "s": 2891, "text": "Every form will have title bar on which the form's caption is displayed and there will be buttons to close, maximize and minimize the form shown below −" }, { "code": null, "e": 3282, "s": 3044, "text": "If you click the icon on the top left corner, it opens the control menu, which contains the various commands to control the form like to move control from one place to another place, to maximize or minimize the form or to close the form." }, { "code": null, "e": 3531, "s": 3282, "text": "Following table lists down various important properties related to a form. These properties can be set or read during application execution. You can refer to Microsoft documentation for a complete list of properties associated with a Form control −" }, { "code": null, "e": 3544, "s": 3531, "text": "AcceptButton" }, { "code": null, "e": 3726, "s": 3544, "text": "The button that's automatically activated when you press Enter, no matter which control has the focus at the time. Usually the OK button on a form is set as AcceptButton for a form." }, { "code": null, "e": 3739, "s": 3726, "text": "CancelButton" }, { "code": null, "e": 3807, "s": 3739, "text": "The button that's automatically activated when you hit the Esc key." }, { "code": null, "e": 3879, "s": 3807, "text": "Usually, the Cancel button on a form is set as CancelButton for a form." }, { "code": null, "e": 3889, "s": 3879, "text": "AutoScale" }, { "code": null, "e": 4142, "s": 3889, "text": "This Boolean property determines whether the controls you place on the form are automatically scaled to the height of the current font. The default value of this property is True. This is a property of the form, but it affects the controls on the form." }, { "code": null, "e": 4153, "s": 4142, "text": "AutoScroll" }, { "code": null, "e": 4315, "s": 4153, "text": "This Boolean property indicates whether scroll bars will be automatically attached to the form if it is resized to a point that not all its controls are visible." }, { "code": null, "e": 4333, "s": 4315, "text": "AutoScrollMinSize" }, { "code": null, "e": 4431, "s": 4333, "text": "This property lets you specify the minimum size of the form, before the scroll bars are attached." }, { "code": null, "e": 4450, "s": 4431, "text": "AutoScrollPosition" }, { "code": null, "e": 4571, "s": 4450, "text": "The AutoScrollPosition is the number of pixels by which the two scroll bars were displaced from their initial locations." }, { "code": null, "e": 4581, "s": 4571, "text": "BackColor" }, { "code": null, "e": 4613, "s": 4581, "text": "Sets the form background color." }, { "code": null, "e": 4625, "s": 4613, "text": "BorderStyle" }, { "code": null, "e": 4726, "s": 4625, "text": "The BorderStyle property determines the style of the form's border and the appearance of the form −\n" }, { "code": null, "e": 4774, "s": 4726, "text": "None − Borderless window that can't be resized." }, { "code": null, "e": 4822, "s": 4774, "text": "None − Borderless window that can't be resized." }, { "code": null, "e": 4934, "s": 4822, "text": "Sizable − This is default value and will be used for resizable window that's used for displaying regular forms." }, { "code": null, "e": 5046, "s": 4934, "text": "Sizable − This is default value and will be used for resizable window that's used for displaying regular forms." }, { "code": null, "e": 5162, "s": 5046, "text": "Fixed3D − Window with a visible border, \"raised\" relative to the main area. In this case, windows can't be resized." }, { "code": null, "e": 5278, "s": 5162, "text": "Fixed3D − Window with a visible border, \"raised\" relative to the main area. In this case, windows can't be resized." }, { "code": null, "e": 5337, "s": 5278, "text": "FixedDialog − A fixed window, used to create dialog boxes." }, { "code": null, "e": 5396, "s": 5337, "text": "FixedDialog − A fixed window, used to create dialog boxes." }, { "code": null, "e": 5452, "s": 5396, "text": "FixedSingle − A fixed window with a single line border." }, { "code": null, "e": 5508, "s": 5452, "text": "FixedSingle − A fixed window with a single line border." }, { "code": null, "e": 5644, "s": 5508, "text": "FixedToolWindow − A fixed window with a Close button only. It looks like the toolbar displayed by the drawing and imaging applications." }, { "code": null, "e": 5780, "s": 5644, "text": "FixedToolWindow − A fixed window with a Close button only. It looks like the toolbar displayed by the drawing and imaging applications." }, { "code": null, "e": 5900, "s": 5780, "text": "SizableToolWindow − Same as the FixedToolWindow but resizable. In addition, its caption font is smaller than the usual." }, { "code": null, "e": 6020, "s": 5900, "text": "SizableToolWindow − Same as the FixedToolWindow but resizable. In addition, its caption font is smaller than the usual." }, { "code": null, "e": 6031, "s": 6020, "text": "ControlBox" }, { "code": null, "e": 6140, "s": 6031, "text": "By default, this property is True and you can set it to False to hide the icon and disable the Control menu." }, { "code": null, "e": 6148, "s": 6140, "text": "Enabled" }, { "code": null, "e": 6239, "s": 6148, "text": "If True, allows the form to respond to mouse and keyboard events; if False, disables form." }, { "code": null, "e": 6244, "s": 6239, "text": "Font" }, { "code": null, "e": 6289, "s": 6244, "text": "This property specify font type, style, size" }, { "code": null, "e": 6300, "s": 6289, "text": "HelpButton" }, { "code": null, "e": 6385, "s": 6300, "text": "Determines whether a Help button should be displayed in the caption box of the form." }, { "code": null, "e": 6392, "s": 6385, "text": "Height" }, { "code": null, "e": 6434, "s": 6392, "text": "This is the height of the Form in pixels." }, { "code": null, "e": 6446, "s": 6434, "text": "MinimizeBox" }, { "code": null, "e": 6554, "s": 6446, "text": "By default, this property is True and you can set it to False to hide the Minimize button on the title bar." }, { "code": null, "e": 6566, "s": 6554, "text": "MaximizeBox" }, { "code": null, "e": 6674, "s": 6566, "text": "By default, this property is True and you can set it to False to hide the Maximize button on the title bar." }, { "code": null, "e": 6686, "s": 6674, "text": "MinimumSize" }, { "code": null, "e": 6762, "s": 6686, "text": "This specifies the minimum height and width of the window you can minimize." }, { "code": null, "e": 6774, "s": 6762, "text": "MaximumSize" }, { "code": null, "e": 6846, "s": 6774, "text": "This specifies the maximum height and width of the window you maximize." }, { "code": null, "e": 6851, "s": 6846, "text": "Name" }, { "code": null, "e": 6888, "s": 6851, "text": "This is the actual name of the form." }, { "code": null, "e": 6902, "s": 6888, "text": "StartPosition" }, { "code": null, "e": 7031, "s": 6902, "text": "This property determines the initial position of the form when it's first displayed. It will have any of the following values −\n" }, { "code": null, "e": 7099, "s": 7031, "text": "CenterParent − The form is centered in the area of its parent form." }, { "code": null, "e": 7167, "s": 7099, "text": "CenterParent − The form is centered in the area of its parent form." }, { "code": null, "e": 7219, "s": 7167, "text": "CenterScreen − The form is centered on the monitor." }, { "code": null, "e": 7271, "s": 7219, "text": "CenterScreen − The form is centered on the monitor." }, { "code": null, "e": 7352, "s": 7271, "text": "Manual − The location and size of the form will determine its starting position." }, { "code": null, "e": 7433, "s": 7352, "text": "Manual − The location and size of the form will determine its starting position." }, { "code": null, "e": 7535, "s": 7433, "text": "WindowsDefaultBounds − The form is positioned at the default location and size determined by Windows." }, { "code": null, "e": 7637, "s": 7535, "text": "WindowsDefaultBounds − The form is positioned at the default location and size determined by Windows." }, { "code": null, "e": 7767, "s": 7637, "text": "WindowsDefaultLocation − The form is positioned at the Windows default location and has the dimensions you've set at design time." }, { "code": null, "e": 7897, "s": 7767, "text": "WindowsDefaultLocation − The form is positioned at the Windows default location and has the dimensions you've set at design time." }, { "code": null, "e": 7902, "s": 7897, "text": "Text" }, { "code": null, "e": 7960, "s": 7902, "text": "The text, which will appear at the title bar of the form." }, { "code": null, "e": 7970, "s": 7960, "text": "Top, Left" }, { "code": null, "e": 8062, "s": 7970, "text": "These two properties set or return the coordinates of the form's top-left corner in pixels." }, { "code": null, "e": 8070, "s": 8062, "text": "TopMost" }, { "code": null, "e": 8235, "s": 8070, "text": "This property is a True/False value that lets you specify whether the form will remain on top of all other forms in your application. Its default property is False." }, { "code": null, "e": 8241, "s": 8235, "text": "Width" }, { "code": null, "e": 8281, "s": 8241, "text": "This is the width of the form in pixel." }, { "code": null, "e": 8456, "s": 8281, "text": "The following are some of the commonly used methods of the Form class. You can refer to Microsoft documentation for a complete list of methods associated with forms control −" }, { "code": null, "e": 8465, "s": 8456, "text": "Activate" }, { "code": null, "e": 8504, "s": 8465, "text": "Activates the form and gives it focus." }, { "code": null, "e": 8521, "s": 8504, "text": "ActivateMdiChild" }, { "code": null, "e": 8556, "s": 8521, "text": "Activates the MDI child of a form." }, { "code": null, "e": 8569, "s": 8556, "text": "AddOwnedForm" }, { "code": null, "e": 8602, "s": 8569, "text": "Adds an owned form to this form." }, { "code": null, "e": 8615, "s": 8602, "text": "BringToFront" }, { "code": null, "e": 8663, "s": 8615, "text": "Brings the control to the front of the z-order." }, { "code": null, "e": 8678, "s": 8663, "text": "CenterToParent" }, { "code": null, "e": 8749, "s": 8678, "text": "Centers the position of the form within the bounds of the parent form." }, { "code": null, "e": 8764, "s": 8749, "text": "CenterToScreen" }, { "code": null, "e": 8804, "s": 8764, "text": "Centers the form on the current screen." }, { "code": null, "e": 8810, "s": 8804, "text": "Close" }, { "code": null, "e": 8827, "s": 8810, "text": "Closes the form." }, { "code": null, "e": 8836, "s": 8827, "text": "Contains" }, { "code": null, "e": 8922, "s": 8836, "text": "Retrieves a value indicating whether the specified control is a child of the control." }, { "code": null, "e": 8928, "s": 8922, "text": "Focus" }, { "code": null, "e": 8961, "s": 8928, "text": "Sets input focus to the control." }, { "code": null, "e": 8966, "s": 8961, "text": "Hide" }, { "code": null, "e": 9002, "s": 8966, "text": "Conceals the control from the user." }, { "code": null, "e": 9010, "s": 9002, "text": "Refresh" }, { "code": null, "e": 9113, "s": 9010, "text": "Forces the control to invalidate its client area and immediately redraw itself and any child controls." }, { "code": null, "e": 9126, "s": 9113, "text": "Scale(SizeF)" }, { "code": null, "e": 9201, "s": 9126, "text": "Scales the control and all child controls by the specified scaling factor." }, { "code": null, "e": 9214, "s": 9201, "text": "ScaleControl" }, { "code": null, "e": 9275, "s": 9214, "text": "Scales the location, size, padding, and margin of a control." }, { "code": null, "e": 9285, "s": 9275, "text": "ScaleCore" }, { "code": null, "e": 9315, "s": 9285, "text": "Performs scaling of the form." }, { "code": null, "e": 9322, "s": 9315, "text": "Select" }, { "code": null, "e": 9345, "s": 9322, "text": "Activates the control." }, { "code": null, "e": 9356, "s": 9345, "text": "SendToBack" }, { "code": null, "e": 9402, "s": 9356, "text": "Sends the control to the back of the z-order." }, { "code": null, "e": 9422, "s": 9402, "text": "SetAutoScrollMargin" }, { "code": null, "e": 9464, "s": 9422, "text": "Sets the size of the auto-scroll margins." }, { "code": null, "e": 9481, "s": 9464, "text": "SetDesktopBounds" }, { "code": null, "e": 9533, "s": 9481, "text": "Sets the bounds of the form in desktop coordinates." }, { "code": null, "e": 9552, "s": 9533, "text": "SetDesktopLocation" }, { "code": null, "e": 9606, "s": 9552, "text": "Sets the location of the form in desktop coordinates." }, { "code": null, "e": 9629, "s": 9606, "text": "SetDisplayRectLocation" }, { "code": null, "e": 9682, "s": 9629, "text": "Positions the display window to the specified value." }, { "code": null, "e": 9687, "s": 9682, "text": "Show" }, { "code": null, "e": 9721, "s": 9687, "text": "Displays the control to the user." }, { "code": null, "e": 9732, "s": 9721, "text": "ShowDialog" }, { "code": null, "e": 9770, "s": 9732, "text": "Shows the form as a modal dialog box." }, { "code": null, "e": 9944, "s": 9770, "text": "Following table lists down various important events related to a form. You can refer to Microsoft documentation for a complete list of events associated with forms control −" }, { "code": null, "e": 9954, "s": 9944, "text": "Activated" }, { "code": null, "e": 10012, "s": 9954, "text": "Occurs when the form is activated in code or by the user." }, { "code": null, "e": 10018, "s": 10012, "text": "Click" }, { "code": null, "e": 10051, "s": 10018, "text": "Occurs when the form is clicked." }, { "code": null, "e": 10058, "s": 10051, "text": "Closed" }, { "code": null, "e": 10092, "s": 10058, "text": "Occurs before the form is closed." }, { "code": null, "e": 10100, "s": 10092, "text": "Closing" }, { "code": null, "e": 10133, "s": 10100, "text": "Occurs when the form is closing." }, { "code": null, "e": 10145, "s": 10133, "text": "DoubleClick" }, { "code": null, "e": 10193, "s": 10145, "text": "Occurs when the form control is double-clicked." }, { "code": null, "e": 10202, "s": 10193, "text": "DragDrop" }, { "code": null, "e": 10254, "s": 10202, "text": "Occurs when a drag-and-drop operation is completed." }, { "code": null, "e": 10260, "s": 10254, "text": "Enter" }, { "code": null, "e": 10293, "s": 10260, "text": "Occurs when the form is entered." }, { "code": null, "e": 10302, "s": 10293, "text": "GotFocus" }, { "code": null, "e": 10347, "s": 10302, "text": "Occurs when the form control receives focus." }, { "code": null, "e": 10365, "s": 10347, "text": "HelpButtonClicked" }, { "code": null, "e": 10405, "s": 10365, "text": "Occurs when the Help button is clicked." }, { "code": null, "e": 10413, "s": 10405, "text": "KeyDown" }, { "code": null, "e": 10469, "s": 10413, "text": "Occurs when a key is pressed while the form has focus." }, { "code": null, "e": 10478, "s": 10469, "text": "KeyPress" }, { "code": null, "e": 10534, "s": 10478, "text": "Occurs when a key is pressed while the form has focus." }, { "code": null, "e": 10540, "s": 10534, "text": "KeyUp" }, { "code": null, "e": 10596, "s": 10540, "text": "Occurs when a key is released while the form has focus." }, { "code": null, "e": 10601, "s": 10596, "text": "Load" }, { "code": null, "e": 10655, "s": 10601, "text": "Occurs before a form is displayed for the first time." }, { "code": null, "e": 10665, "s": 10655, "text": "LostFocus" }, { "code": null, "e": 10699, "s": 10665, "text": "Occurs when the form loses focus." }, { "code": null, "e": 10709, "s": 10699, "text": "MouseDown" }, { "code": null, "e": 10787, "s": 10709, "text": "Occurs when the mouse pointer is over the form and a mouse button is pressed." }, { "code": null, "e": 10798, "s": 10787, "text": "MouseEnter" }, { "code": null, "e": 10845, "s": 10798, "text": "Occurs when the mouse pointer enters the form." }, { "code": null, "e": 10856, "s": 10845, "text": "MouseHover" }, { "code": null, "e": 10905, "s": 10856, "text": "Occurs when the mouse pointer rests on the form." }, { "code": null, "e": 10916, "s": 10905, "text": "MouseLeave" }, { "code": null, "e": 10963, "s": 10916, "text": "Occurs when the mouse pointer leaves the form." }, { "code": null, "e": 10973, "s": 10963, "text": "MouseMove" }, { "code": null, "e": 11027, "s": 10973, "text": "Occurs when the mouse pointer is moved over the form." }, { "code": null, "e": 11035, "s": 11027, "text": "MouseUp" }, { "code": null, "e": 11115, "s": 11035, "text": "Occurs when the mouse pointer is over the form and a mouse button is released." }, { "code": null, "e": 11126, "s": 11115, "text": "MouseWheel" }, { "code": null, "e": 11189, "s": 11126, "text": "Occurs when the mouse wheel moves while the control has focus." }, { "code": null, "e": 11194, "s": 11189, "text": "Move" }, { "code": null, "e": 11225, "s": 11194, "text": "Occurs when the form is moved." }, { "code": null, "e": 11232, "s": 11225, "text": "Resize" }, { "code": null, "e": 11268, "s": 11232, "text": "Occurs when the control is resized." }, { "code": null, "e": 11275, "s": 11268, "text": "Scroll" }, { "code": null, "e": 11337, "s": 11275, "text": "Occurs when the user or code scrolls through the client area." }, { "code": null, "e": 11343, "s": 11337, "text": "Shown" }, { "code": null, "e": 11388, "s": 11343, "text": "Occurs whenever the form is first displayed." }, { "code": null, "e": 11403, "s": 11388, "text": "VisibleChanged" }, { "code": null, "e": 11451, "s": 11403, "text": "Occurs when the Visible property value changes." }, { "code": null, "e": 11602, "s": 11451, "text": "Following is an example, which shows how we create two buttons at the time of form load event and different properties are being set at the same time." }, { "code": null, "e": 11841, "s": 11602, "text": "Because Form1 is being referenced within its own event handler, so it will be written as Me instead of using its name, but if we access the same form inside any other control's event handler, then it will be accessed using its name Form1." }, { "code": null, "e": 11918, "s": 11841, "text": "Let's double click on the Form and put the follow code in the opened window." }, { "code": null, "e": 13603, "s": 11918, "text": "Public Class Form1\n Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n ' Create two buttons to use as the accept and cancel buttons. \n Dim button1 As New Button()\n Dim button2 As New Button()\n ' Set the text of button1 to \"OK\".\n \n button1.Text = \"OK\"\n ' Set the position of the button on the form.\n button1.Location = New Point(10, 10)\n ' Set the text of button2 to \"Cancel\".\n \n button2.Text = \"Cancel\"\n ' Set the position of the button based on the location of button1.\n button2.Location = _\n New Point(button1.Left, button1.Height + button1.Top + 10)\n ' Set the caption bar text of the form. \n \n Me.Text = \"tutorialspoint.com\"\n ' Display a help button on the form.\n Me.HelpButton = True\n ' Define the border style of the form to a dialog box.\n \n Me.FormBorderStyle = FormBorderStyle.FixedDialog\n ' Set the MaximizeBox to false to remove the maximize box.\n Me.MaximizeBox = False\n ' Set the MinimizeBox to false to remove the minimize box.\n \n Me.MinimizeBox = False\n ' Set the accept button of the form to button1.\n Me.AcceptButton = button1\n ' Set the cancel button of the form to button2.\n \n Me.CancelButton = button2\n ' Set the start position of the form to the center of the screen.\n Me.StartPosition = FormStartPosition.CenterScreen\n ' Set window width and height\n \n Me.Height = 300\n Me.Width = 560\n ' Add button1 to the form.\n \n Me.Controls.Add(button1)\n ' Add button2 to the form.\n Me.Controls.Add(button2)\n End Sub\nEnd Class" }, { "code": null, "e": 13749, "s": 13603, "text": "When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −" }, { "code": null, "e": 13782, "s": 13749, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 13799, "s": 13782, "text": " Frahaan Hussain" }, { "code": null, "e": 13834, "s": 13799, "text": "\n 103 Lectures \n 12 hours \n" }, { "code": null, "e": 13849, "s": 13834, "text": " Arnold Higuit" }, { "code": null, "e": 13884, "s": 13849, "text": "\n 60 Lectures \n 9.5 hours \n" }, { "code": null, "e": 13899, "s": 13884, "text": " Arnold Higuit" }, { "code": null, "e": 13932, "s": 13899, "text": "\n 97 Lectures \n 9 hours \n" }, { "code": null, "e": 13947, "s": 13932, "text": " Arnold Higuit" }, { "code": null, "e": 13954, "s": 13947, "text": " Print" }, { "code": null, "e": 13965, "s": 13954, "text": " Add Notes" } ]
Program to convert Array to List in Java
The array is as follows − String arr[] = { "One", "Two", "Three", "Four", "Five" }; Now, using the Array.asList() to convert the above array to list − List<String>myList = Arrays.asList(arr); Following is the program to convert Array to List in Java − import java.util.*; public class Demo { public static void main(String[] args) { String arr[] = { "One", "Two", "Three", "Four", "Five" }; System.out.println("Array = "+ Arrays.toString(arr)); List<String>myList = Arrays.asList(arr); System.out.println("List (Array to List) = " + myList); } } Array = [One, Two, Three, Four, Five] List (Array to List) = [One, Two, Three, Four, Five]
[ { "code": null, "e": 1088, "s": 1062, "text": "The array is as follows −" }, { "code": null, "e": 1146, "s": 1088, "text": "String arr[] = { \"One\", \"Two\", \"Three\", \"Four\", \"Five\" };" }, { "code": null, "e": 1213, "s": 1146, "text": "Now, using the Array.asList() to convert the above array to list −" }, { "code": null, "e": 1254, "s": 1213, "text": "List<String>myList = Arrays.asList(arr);" }, { "code": null, "e": 1314, "s": 1254, "text": "Following is the program to convert Array to List in Java −" }, { "code": null, "e": 1638, "s": 1314, "text": "import java.util.*;\npublic class Demo {\n public static void main(String[] args) {\n String arr[] = { \"One\", \"Two\", \"Three\", \"Four\", \"Five\" };\n System.out.println(\"Array = \"+ Arrays.toString(arr));\n List<String>myList = Arrays.asList(arr);\n System.out.println(\"List (Array to List) = \" + myList);\n }\n}" }, { "code": null, "e": 1729, "s": 1638, "text": "Array = [One, Two, Three, Four, Five]\nList (Array to List) = [One, Two, Three, Four, Five]" } ]
Understanding RNNs (Recurrent Neural Networks) | by Tony Yiu | Towards Data Science
The first time I heard of a RNN (Recurrent Neural Network), I was perplexed. The article I read was claiming that a RNN is a neural net with memory — that it could remember the sequential ups and downs of the data in order to make more informed predictions. My first thought back then was — how is a RNN different from a linear regression with many lags (an autoregressive model)? Turns out a RNN is not only a lot different but also more versatile and more powerful. But before we add it to our forecasting toolkit, we should do our best to develop an intuitive understanding of how it works — starting with how an RNN is able to remember the past. Let’s find out. A RNN is a neural network that works best on sequential data. If you are unfamiliar with neural nets, then you should start with my Understanding Neural Networks post. Going forward in this article, I will assume that the reader has a basic understanding of what a neural net is and how one works. What’s sequential data — it is data where the order matters. Some examples of sequential data include stock prices and interest rates (ordered by time), the words in a blog post (the order of the words convey context and meaning), or the average temperature for each day (ordered by time). Usually with sequential data we want to predict what’s coming next. For example, we might want to forecast what the temperature will be tomorrow or whether a stock’s price will be higher or lower next month. The simplest forecast that I can think of is an AR(1) model (an autoregressive model with a single lag) where you simply use the previous observation to attempt to forecast the next one. Let’s use stock returns as our example: We want to forecast Ret, Apple’s return over the next month. This is our target variable. Our lone feature variable is the most recent month’s return. Our dataset consists of a 20 year time series of Apple’s monthly stock returns (calculated as the percentage change in price of Apple stock from the last day of the previous month to the last day of the current month). An AR(1) model would have the following equation: Predicted_Ret(t) = m*Ret(t-1) + B This should look familiar as it’s the equation for a line (Y = mX + B). The picture below depicts our AR(1) model in more detail. Let’s go through it piece by piece: We use our data to estimate the optimal values of the parameters in green — m is the slope of our line and B is the intercept. Notice that the equation on the left produces an output with a hat symbol (^). The hat denotes that the output is merely an estimate of our target variable, the actual stock return. Our goal is to minimize the differences between the forecasted return (^) and the actual return. Notice that horizontally Ret(0), the first month return, lines up with Ret(1), the second monthly return, and Ret(1) lines up with Ret(2) and so on. This is what we mean when we say that we use the previous observation (our feature) to forecast the next one (our target) — given last month’s return and our estimated values of m and B, we can produce a forecast of next month’s return. You don’t need to have been around the market for very long to know that this is not a good model. Stock prices can move for various reasons (company fundamentals, economic shocks, investor fear/euphoria) or sometimes no reason at all. So we shouldn’t expect a simple AR(1) model to do a good job. Rather we should look further beyond just the most recent observation and consider the entire sequence (really we should be considering data beyond price movements, but that is a story for another day). RNNs allow us to do just that. Before we dive into RNNs, one question an alert reader might have is “Why not just increase the number of lags in our autoregressive model?” That is instead of using a single lag, why not use something like AR(20), which forecasts next month’s return using the 20 most recent monthly returns. The answer is twofold: The number of monthly returns to use for our model is actually an important parameter that we need to tune. Choosing the wrong number could lead to poor performance. Moreover, depending on the economic regime, the optimal number of monthly returns to use can potentially vary widely. An RNN gets around this because it can see the entire available history of returns — and more importantly, it automatically decides at each point in time how much weight to give to the historical returns. So we don’t need to tell a RNN to look at the previous 5, 10, or 20 returns because it inherently already knows to do so.Autoregressive models are linear models and thus assume a linear relationship between our features and the target. In situations where there is non-linearity, this could cause performance issues. RNNs, especially when stacked on more RNNs or on dense layers (a dense layer is a layer of normal neural net neurons), can detect and capture all the nonlinear relationships in our data. In fact, with RNNs (and neural nets in general) we should worry more about over-fitting rather than under-fitting. The number of monthly returns to use for our model is actually an important parameter that we need to tune. Choosing the wrong number could lead to poor performance. Moreover, depending on the economic regime, the optimal number of monthly returns to use can potentially vary widely. An RNN gets around this because it can see the entire available history of returns — and more importantly, it automatically decides at each point in time how much weight to give to the historical returns. So we don’t need to tell a RNN to look at the previous 5, 10, or 20 returns because it inherently already knows to do so. Autoregressive models are linear models and thus assume a linear relationship between our features and the target. In situations where there is non-linearity, this could cause performance issues. RNNs, especially when stacked on more RNNs or on dense layers (a dense layer is a layer of normal neural net neurons), can detect and capture all the nonlinear relationships in our data. In fact, with RNNs (and neural nets in general) we should worry more about over-fitting rather than under-fitting. Let us recreate our AR(1) model using a neural net neuron. Nothing complicated here — recall that a singular neuron (if you are unfamiliar with neurons, please take a second and read my previous blog on neural nets) takes an input, multiplies it by a weight (m), and adds a bias (B) to it. Those are exactly the operations of a single variable linear regression, which is what an AR(1) model is. Note that we are neglecting the activation function here to simplify the explanation. Now let’s think about how we can add memory to this model. What is memory in the case of a quantitative model? There’s no 100% correct answer, but in my opinion, memory is the ability to draw from relevant past experiences in order to aid decision making. In modeling terms, we want the model to be dynamic — in other words, we want it to be able to shift according to its read of the situation (based on its past experiences). Our AR(1) model might be trained with historical data (recall that we fed it the last 20 years of Apple’s monthly stock returns), but it definitely doesn’t have memory. The AR(1) model equally weights each data point that we give it when estimating the regression parameters m and B. Thus, it is not able to decide which data points are more relevant and which are less (the regression parameters are static, once estimated). It is static, not dynamic. Finally it’s time to give our model memory. It actually requires just a simple trick. Notice the additions at the bottom in the picture below: The key addition is that we are now taking in the previous output, Output(t-1), multiplying it against a new parameter u, and adding it to what we previously had. So our updated equation looks like: Predicted_Ret(t) = u*Predicted_Ret(t-1) + m*Ret(t-1) + B Or with a more general notation: Output(t) = u*Output(t-1) + m*Ret(t-1) + B So why exactly does this constitute memory? To see why, we need to jump ahead a bit and first understand how an RNN analyzes data. Here’s some Python pseudocode for how an RNN generates its predictions: # Our input data is 20 years of Apple's monthly returnsinputs = appl_monthy_returnstime_steps = range(inputs.shape[0])# List to store outputspredictions = []# Initialize state to 0 (state is output[t-1] from above)state = 0# Initialize u, m, and Bu = 1m = 1B = 1for t in time_steps: input_t = inputs[t] current_prediction = (u * state) + (m * input_t) + B predictions.append(current_prediction) state = current_prediction # Function that updates m and B via backpropagation through time u, m, B = BPTT(state, predictions, inputs) OK, now let’s walk through the code: First we initialize state, which is what I am calling Output(t-1), to 0 because there is no previous state at t=0.Then we start the loop. The loop will run for as many times as there are inputs — in our case we have 20 years of monthly returns so it will run 20*12 = 240 times.In each iteration of the loop, we calculate the current prediction. We then append the calculated prediction to our output list, predictions — this list is our predictions of the next month’s return.Next, we set state equal to the current prediction so that we can use it in the next loop — that is, we need the prediction from t=0 to calculate the prediction at t=1.Finally, we use backpropagation through time (beyond the scope of this post) to update the RNN’s parameters u, m, and B. First we initialize state, which is what I am calling Output(t-1), to 0 because there is no previous state at t=0. Then we start the loop. The loop will run for as many times as there are inputs — in our case we have 20 years of monthly returns so it will run 20*12 = 240 times. In each iteration of the loop, we calculate the current prediction. We then append the calculated prediction to our output list, predictions — this list is our predictions of the next month’s return. Next, we set state equal to the current prediction so that we can use it in the next loop — that is, we need the prediction from t=0 to calculate the prediction at t=1. Finally, we use backpropagation through time (beyond the scope of this post) to update the RNN’s parameters u, m, and B. Take note of a few key things: The state is where the memory comes from. The state at time t is the previous output (from time t-1) — and this previous output includes the previous model parameters (time t-1’s u, m, and B) as well as the output from time t-2. When the current time-step of the RNN (each time-step is one iteration of the for loop) looks at the output from the previous time-step (state), it is in essence looking at its past self. The previous output is the RNN’s way of snapshotting its past self and passing it forward. That’s why I call it state in my pseudocode — it’s just one way to summarize (very roughly) the most up to date state of the model’s decision making process. We multiply state by the parameter u. This allows the RNN to decide how much or how little to use its memory (past snapshots of itself). The last thing we do in each iteration of our for loop is update the RNN’s parameters (u, m, and B). This means that in each iteration of the loop we may and probably will see different values for u, m, and B. The purpose of the for loop is to move the RNN forward through time. Unlike linear regression where the model is estimated all at once, the RNN gradually converges by incrementally examining the sequential data one time-step at a time. Let’s write out the equation (using simpler notation) to make sure we understand everything. I will call the output at time t, O(t), and the input, X(t). Let’s write out O(3): O(3) = u * O(2) + m * X (3) + B We can also write out O(2): O(2) = u_2 * O(1) + m_2* X (2) + B_2 Substituting for O(2), we get: O(3) = u * (u_2 * O(1) + m_2* X (2) + B_2) + m * X (3) + B See how the output at time t=3 includes previous parameters (u_2, m_2, and B_2) — these parameters are how the RNN made its decisions at time t=2 and they have now been passed on to the current iteration of the model. If we wanted to, we could expand O(1) as well to see that the parameters from time t=1 are included as well. Recall that we defined model memory as being dynamic and able to shift based on the situation. The RNN can do that now — by including past snapshots of itself via its previous output, the RNN acquires access to its historical parameters and can, as the situation requires, decide whether or not to include them in its decision making process. I learned a great deal writing this post. Previously I knew at a very high level how RNNs worked, but I always wanted to better understand what people meant when they said that RNNs had memory. I hope you understand it better now too. Our work is not yet finished though. Theoretically RNNs should be able to masterfully harness past experience to make decisions. But in reality, they suffer from something called the vanishing gradient problem. In a future post, we will explore why this is so and how an augmented RNN called a LSTM helps us get around this problem. Until then, cheers! More Data Science and Business Related Posts By Me: Business Strategy For Data Scientists How Much Analysis Is Too Much Business Simulations With Python Understanding PCA Understanding Bayes’ Theorem Understanding The Naive Bayes Classifier
[ { "code": null, "e": 429, "s": 171, "text": "The first time I heard of a RNN (Recurrent Neural Network), I was perplexed. The article I read was claiming that a RNN is a neural net with memory — that it could remember the sequential ups and downs of the data in order to make more informed predictions." }, { "code": null, "e": 639, "s": 429, "text": "My first thought back then was — how is a RNN different from a linear regression with many lags (an autoregressive model)? Turns out a RNN is not only a lot different but also more versatile and more powerful." }, { "code": null, "e": 837, "s": 639, "text": "But before we add it to our forecasting toolkit, we should do our best to develop an intuitive understanding of how it works — starting with how an RNN is able to remember the past. Let’s find out." }, { "code": null, "e": 1135, "s": 837, "text": "A RNN is a neural network that works best on sequential data. If you are unfamiliar with neural nets, then you should start with my Understanding Neural Networks post. Going forward in this article, I will assume that the reader has a basic understanding of what a neural net is and how one works." }, { "code": null, "e": 1425, "s": 1135, "text": "What’s sequential data — it is data where the order matters. Some examples of sequential data include stock prices and interest rates (ordered by time), the words in a blog post (the order of the words convey context and meaning), or the average temperature for each day (ordered by time)." }, { "code": null, "e": 1633, "s": 1425, "text": "Usually with sequential data we want to predict what’s coming next. For example, we might want to forecast what the temperature will be tomorrow or whether a stock’s price will be higher or lower next month." }, { "code": null, "e": 1860, "s": 1633, "text": "The simplest forecast that I can think of is an AR(1) model (an autoregressive model with a single lag) where you simply use the previous observation to attempt to forecast the next one. Let’s use stock returns as our example:" }, { "code": null, "e": 1950, "s": 1860, "text": "We want to forecast Ret, Apple’s return over the next month. This is our target variable." }, { "code": null, "e": 2011, "s": 1950, "text": "Our lone feature variable is the most recent month’s return." }, { "code": null, "e": 2230, "s": 2011, "text": "Our dataset consists of a 20 year time series of Apple’s monthly stock returns (calculated as the percentage change in price of Apple stock from the last day of the previous month to the last day of the current month)." }, { "code": null, "e": 2280, "s": 2230, "text": "An AR(1) model would have the following equation:" }, { "code": null, "e": 2314, "s": 2280, "text": "Predicted_Ret(t) = m*Ret(t-1) + B" }, { "code": null, "e": 2480, "s": 2314, "text": "This should look familiar as it’s the equation for a line (Y = mX + B). The picture below depicts our AR(1) model in more detail. Let’s go through it piece by piece:" }, { "code": null, "e": 2607, "s": 2480, "text": "We use our data to estimate the optimal values of the parameters in green — m is the slope of our line and B is the intercept." }, { "code": null, "e": 2789, "s": 2607, "text": "Notice that the equation on the left produces an output with a hat symbol (^). The hat denotes that the output is merely an estimate of our target variable, the actual stock return." }, { "code": null, "e": 2886, "s": 2789, "text": "Our goal is to minimize the differences between the forecasted return (^) and the actual return." }, { "code": null, "e": 3272, "s": 2886, "text": "Notice that horizontally Ret(0), the first month return, lines up with Ret(1), the second monthly return, and Ret(1) lines up with Ret(2) and so on. This is what we mean when we say that we use the previous observation (our feature) to forecast the next one (our target) — given last month’s return and our estimated values of m and B, we can produce a forecast of next month’s return." }, { "code": null, "e": 3570, "s": 3272, "text": "You don’t need to have been around the market for very long to know that this is not a good model. Stock prices can move for various reasons (company fundamentals, economic shocks, investor fear/euphoria) or sometimes no reason at all. So we shouldn’t expect a simple AR(1) model to do a good job." }, { "code": null, "e": 3804, "s": 3570, "text": "Rather we should look further beyond just the most recent observation and consider the entire sequence (really we should be considering data beyond price movements, but that is a story for another day). RNNs allow us to do just that." }, { "code": null, "e": 4120, "s": 3804, "text": "Before we dive into RNNs, one question an alert reader might have is “Why not just increase the number of lags in our autoregressive model?” That is instead of using a single lag, why not use something like AR(20), which forecasts next month’s return using the 20 most recent monthly returns. The answer is twofold:" }, { "code": null, "e": 5228, "s": 4120, "text": "The number of monthly returns to use for our model is actually an important parameter that we need to tune. Choosing the wrong number could lead to poor performance. Moreover, depending on the economic regime, the optimal number of monthly returns to use can potentially vary widely. An RNN gets around this because it can see the entire available history of returns — and more importantly, it automatically decides at each point in time how much weight to give to the historical returns. So we don’t need to tell a RNN to look at the previous 5, 10, or 20 returns because it inherently already knows to do so.Autoregressive models are linear models and thus assume a linear relationship between our features and the target. In situations where there is non-linearity, this could cause performance issues. RNNs, especially when stacked on more RNNs or on dense layers (a dense layer is a layer of normal neural net neurons), can detect and capture all the nonlinear relationships in our data. In fact, with RNNs (and neural nets in general) we should worry more about over-fitting rather than under-fitting." }, { "code": null, "e": 5839, "s": 5228, "text": "The number of monthly returns to use for our model is actually an important parameter that we need to tune. Choosing the wrong number could lead to poor performance. Moreover, depending on the economic regime, the optimal number of monthly returns to use can potentially vary widely. An RNN gets around this because it can see the entire available history of returns — and more importantly, it automatically decides at each point in time how much weight to give to the historical returns. So we don’t need to tell a RNN to look at the previous 5, 10, or 20 returns because it inherently already knows to do so." }, { "code": null, "e": 6337, "s": 5839, "text": "Autoregressive models are linear models and thus assume a linear relationship between our features and the target. In situations where there is non-linearity, this could cause performance issues. RNNs, especially when stacked on more RNNs or on dense layers (a dense layer is a layer of normal neural net neurons), can detect and capture all the nonlinear relationships in our data. In fact, with RNNs (and neural nets in general) we should worry more about over-fitting rather than under-fitting." }, { "code": null, "e": 6819, "s": 6337, "text": "Let us recreate our AR(1) model using a neural net neuron. Nothing complicated here — recall that a singular neuron (if you are unfamiliar with neurons, please take a second and read my previous blog on neural nets) takes an input, multiplies it by a weight (m), and adds a bias (B) to it. Those are exactly the operations of a single variable linear regression, which is what an AR(1) model is. Note that we are neglecting the activation function here to simplify the explanation." }, { "code": null, "e": 7247, "s": 6819, "text": "Now let’s think about how we can add memory to this model. What is memory in the case of a quantitative model? There’s no 100% correct answer, but in my opinion, memory is the ability to draw from relevant past experiences in order to aid decision making. In modeling terms, we want the model to be dynamic — in other words, we want it to be able to shift according to its read of the situation (based on its past experiences)." }, { "code": null, "e": 7700, "s": 7247, "text": "Our AR(1) model might be trained with historical data (recall that we fed it the last 20 years of Apple’s monthly stock returns), but it definitely doesn’t have memory. The AR(1) model equally weights each data point that we give it when estimating the regression parameters m and B. Thus, it is not able to decide which data points are more relevant and which are less (the regression parameters are static, once estimated). It is static, not dynamic." }, { "code": null, "e": 7843, "s": 7700, "text": "Finally it’s time to give our model memory. It actually requires just a simple trick. Notice the additions at the bottom in the picture below:" }, { "code": null, "e": 8042, "s": 7843, "text": "The key addition is that we are now taking in the previous output, Output(t-1), multiplying it against a new parameter u, and adding it to what we previously had. So our updated equation looks like:" }, { "code": null, "e": 8099, "s": 8042, "text": "Predicted_Ret(t) = u*Predicted_Ret(t-1) + m*Ret(t-1) + B" }, { "code": null, "e": 8132, "s": 8099, "text": "Or with a more general notation:" }, { "code": null, "e": 8175, "s": 8132, "text": "Output(t) = u*Output(t-1) + m*Ret(t-1) + B" }, { "code": null, "e": 8378, "s": 8175, "text": "So why exactly does this constitute memory? To see why, we need to jump ahead a bit and first understand how an RNN analyzes data. Here’s some Python pseudocode for how an RNN generates its predictions:" }, { "code": null, "e": 8930, "s": 8378, "text": "# Our input data is 20 years of Apple's monthly returnsinputs = appl_monthy_returnstime_steps = range(inputs.shape[0])# List to store outputspredictions = []# Initialize state to 0 (state is output[t-1] from above)state = 0# Initialize u, m, and Bu = 1m = 1B = 1for t in time_steps: input_t = inputs[t] current_prediction = (u * state) + (m * input_t) + B predictions.append(current_prediction) state = current_prediction # Function that updates m and B via backpropagation through time u, m, B = BPTT(state, predictions, inputs)" }, { "code": null, "e": 8967, "s": 8930, "text": "OK, now let’s walk through the code:" }, { "code": null, "e": 9732, "s": 8967, "text": "First we initialize state, which is what I am calling Output(t-1), to 0 because there is no previous state at t=0.Then we start the loop. The loop will run for as many times as there are inputs — in our case we have 20 years of monthly returns so it will run 20*12 = 240 times.In each iteration of the loop, we calculate the current prediction. We then append the calculated prediction to our output list, predictions — this list is our predictions of the next month’s return.Next, we set state equal to the current prediction so that we can use it in the next loop — that is, we need the prediction from t=0 to calculate the prediction at t=1.Finally, we use backpropagation through time (beyond the scope of this post) to update the RNN’s parameters u, m, and B." }, { "code": null, "e": 9847, "s": 9732, "text": "First we initialize state, which is what I am calling Output(t-1), to 0 because there is no previous state at t=0." }, { "code": null, "e": 10011, "s": 9847, "text": "Then we start the loop. The loop will run for as many times as there are inputs — in our case we have 20 years of monthly returns so it will run 20*12 = 240 times." }, { "code": null, "e": 10211, "s": 10011, "text": "In each iteration of the loop, we calculate the current prediction. We then append the calculated prediction to our output list, predictions — this list is our predictions of the next month’s return." }, { "code": null, "e": 10380, "s": 10211, "text": "Next, we set state equal to the current prediction so that we can use it in the next loop — that is, we need the prediction from t=0 to calculate the prediction at t=1." }, { "code": null, "e": 10501, "s": 10380, "text": "Finally, we use backpropagation through time (beyond the scope of this post) to update the RNN’s parameters u, m, and B." }, { "code": null, "e": 10532, "s": 10501, "text": "Take note of a few key things:" }, { "code": null, "e": 11198, "s": 10532, "text": "The state is where the memory comes from. The state at time t is the previous output (from time t-1) — and this previous output includes the previous model parameters (time t-1’s u, m, and B) as well as the output from time t-2. When the current time-step of the RNN (each time-step is one iteration of the for loop) looks at the output from the previous time-step (state), it is in essence looking at its past self. The previous output is the RNN’s way of snapshotting its past self and passing it forward. That’s why I call it state in my pseudocode — it’s just one way to summarize (very roughly) the most up to date state of the model’s decision making process." }, { "code": null, "e": 11335, "s": 11198, "text": "We multiply state by the parameter u. This allows the RNN to decide how much or how little to use its memory (past snapshots of itself)." }, { "code": null, "e": 11545, "s": 11335, "text": "The last thing we do in each iteration of our for loop is update the RNN’s parameters (u, m, and B). This means that in each iteration of the loop we may and probably will see different values for u, m, and B." }, { "code": null, "e": 11781, "s": 11545, "text": "The purpose of the for loop is to move the RNN forward through time. Unlike linear regression where the model is estimated all at once, the RNN gradually converges by incrementally examining the sequential data one time-step at a time." }, { "code": null, "e": 11957, "s": 11781, "text": "Let’s write out the equation (using simpler notation) to make sure we understand everything. I will call the output at time t, O(t), and the input, X(t). Let’s write out O(3):" }, { "code": null, "e": 11989, "s": 11957, "text": "O(3) = u * O(2) + m * X (3) + B" }, { "code": null, "e": 12017, "s": 11989, "text": "We can also write out O(2):" }, { "code": null, "e": 12054, "s": 12017, "text": "O(2) = u_2 * O(1) + m_2* X (2) + B_2" }, { "code": null, "e": 12085, "s": 12054, "text": "Substituting for O(2), we get:" }, { "code": null, "e": 12144, "s": 12085, "text": "O(3) = u * (u_2 * O(1) + m_2* X (2) + B_2) + m * X (3) + B" }, { "code": null, "e": 12471, "s": 12144, "text": "See how the output at time t=3 includes previous parameters (u_2, m_2, and B_2) — these parameters are how the RNN made its decisions at time t=2 and they have now been passed on to the current iteration of the model. If we wanted to, we could expand O(1) as well to see that the parameters from time t=1 are included as well." }, { "code": null, "e": 12814, "s": 12471, "text": "Recall that we defined model memory as being dynamic and able to shift based on the situation. The RNN can do that now — by including past snapshots of itself via its previous output, the RNN acquires access to its historical parameters and can, as the situation requires, decide whether or not to include them in its decision making process." }, { "code": null, "e": 13049, "s": 12814, "text": "I learned a great deal writing this post. Previously I knew at a very high level how RNNs worked, but I always wanted to better understand what people meant when they said that RNNs had memory. I hope you understand it better now too." }, { "code": null, "e": 13402, "s": 13049, "text": "Our work is not yet finished though. Theoretically RNNs should be able to masterfully harness past experience to make decisions. But in reality, they suffer from something called the vanishing gradient problem. In a future post, we will explore why this is so and how an augmented RNN called a LSTM helps us get around this problem. Until then, cheers!" }, { "code": null, "e": 13454, "s": 13402, "text": "More Data Science and Business Related Posts By Me:" }, { "code": null, "e": 13492, "s": 13454, "text": "Business Strategy For Data Scientists" }, { "code": null, "e": 13522, "s": 13492, "text": "How Much Analysis Is Too Much" }, { "code": null, "e": 13555, "s": 13522, "text": "Business Simulations With Python" }, { "code": null, "e": 13573, "s": 13555, "text": "Understanding PCA" }, { "code": null, "e": 13602, "s": 13573, "text": "Understanding Bayes’ Theorem" } ]
Graphical Approach to Exploratory Data Analysis in Python | by Kieran Tan Kah Wang | Towards Data Science
Exploratory Data Analysis (EDA) is one of the most important aspect in every data science or data analysis problem. It provides us greater understanding on our data and can possibly unravel hidden insights that aren’t that obvious to us. The first article I’ve wrote on Medium is also on performing EDA in R, you can check it out here. This post will focus more on graphical EDA in Python using matplotlib, regression line and even motion chart! The dataset we are using for this article can be obtained from Gapminder, and drilling down into Population, Gender Equality in Education and Income. The Population data contains yearly data regarding the estimated resident population, grouped by countries around the world between 1800 and 2018. The Gender Equality in Education data contains yearly data between 1970 and 2015 on the ratio between female to male in schools, among 25 to 34 years old which includes primary, secondary and tertiary education across different countries The Income data contains yearly data of income per person adjusted for differences in purchasing power (in international dollars) across different countries around the world, for the period between 1800 and 2018. Let’s first plot the population data over time, and focus mainly on the three countries Singapore, United States and China. We will use matplotlib library to plot 3 different line charts on the same figure. import pandas as pdimport matplotlib.pylab as plt%matplotlib inline# read in datapopulation = pd.read_csv('./population.csv')# plot for the 3 countriesplt.plot(population.Year,population.Singapore,label="Singapore")plt.plot(population.Year,population.China,label="China")plt.plot(population.Year,population["United States"],label="United States")# add legends, labels and titleplt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Population')plt.title('Population Growth over time')plt.show() As seen in the figure, the population values for the 3 countries Singapore, China and United States are increasing over time, though Singapore is not that visible since the axis is in billions, while the population in Singapore is only in the millions. Now, let’s try to fit a linear regression line using linregressto the Singapore population data and plot the linear fit. We can even try predicting the Singapore population in 2020 and 2100. from scipy.stats import linregress# set up regression lineslope, intercept, r_value, p_value, std_err = linregress(population.Year,population.Singapore)line = [slope*xi + intercept for xi in population.Year]# plot the regression line and the linear fitplt.plot(population.Year,line,'r-', linewidth=3,label='Linear Regression Line')plt.scatter(population.Year, population.Singapore,label='Population of Singapore')plt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Population')plt.title('Population Growth of Singapore over time')plt.show()# Calculate correlation coefficient to see how well is the linear fitprint("The correlation coefficient is " + str(r_value))## Use the linear fit to predict the resident population in Singapore in 2020 and 2100.# Using equation y=mx + c, i.e. population=slope*year + interceptprint("The predicted population in Singapore in 2020 will be " + str((slope*2020)+intercept))print("The predicted population in Singapore in 2100 will be " + str((slope*2100)+intercept)) From the figure, we see that the linear fit did not seem to fit the Population of Singapore that well though we have a correlation coefficient close to 1. The prediction of the population was also well off as the current population of Singapore in 2020 is around 5.6 million, which is way above the 3.4 million predicted. Notice that the population before 1850s were negative, which is definitely impossible. Since Singapore is founded in 1965, let’s filter to only use data from 1965 onwards. from scipy.stats import linregress# set up regression lineslope, intercept, r_value, p_value, std_err = linregress(population.Year[population.Year>=1965],population.Singapore[population.Year>=1965])line = [slope*xi + intercept for xi in population.Year[population.Year>=1965]]plt.plot(population.Year[population.Year>=1965],line,'r-', linewidth=3,label='Linear Regression Line')plt.scatter(population.Year[population.Year>=1965], population.Singapore[population.Year>=1965],label='Singapore')plt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Population')plt.title('Population Growth of Singapore from 1965 onwards')plt.show()# Calculate correlation coefficient to see how well is the linear fitprint("The correlation coefficient is " + str(r_value))## Use the linear fit to predict the resident population in Singapore in 2020 and 2100.# Using equation y=mx + c, i.e. population=slope*year + interceptprint("The predicted population in Singapore in 2020 will be " + str((slope*2020)+intercept))print("The predicted population in Singapore in 2100 will be " + str((slope*2100)+intercept)) This linear regression line fits so much better as shown in the graph as well as the correlation coefficient. Furthermore, the predicted 2020 population is exactly what it is in Singapore currently, and let’s hope the 2100 population is not true since we know the land area in Singapore is considerably small. Moving onto the second dataset, let’s try to plot the gender ratio (females to males) in schools for Singapore, China and the United States over time. We can also look at the maximum and minimum gender ratio percentage in Singapore. # reading in datagender_equality = pd.read_csv('./GenderEquality.csv')# plot the graphsplt.plot(gender_equality.Year,gender_equality.Singapore,label="Singapore")plt.plot(gender_equality.Year,gender_equality.China,label="China")plt.plot(gender_equality.Year,gender_equality["United States"],label="United States")# set up legends, labels and titleplt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Gender Ratio of Female to Male in school')plt.title('Gender Ratio of Female to Male in school over time')plt.show()# What are the maximum and minimum values for gender ratio in Singapore over the time period?print("The maximum value is: " + str(max(gender_equality.Singapore)) + " and the minimum is " + str(min(gender_equality.Singapore))) The gender ratios were generally increasing over time as seen in the output above. Gender Ratio for China and Singapore were increasing linearly over time. For United States, there was certain periods in which the gender ratio were stagnant before increasing again. The minimum gender ratio for Singapore was 79.5 while the maximum was 98.9, and this was expected since education in Singapore in the past was considerably more important for males than females. Let’s plot the linear regression line on the gender ratio for Singapore. # plot the regression lineslope, intercept, r_value, p_value, std_err = linregress(gender_equality.Year,gender_equality["Singapore"])line = [slope*xi + intercept for xi in gender_equality.Year]plt.plot(gender_equality.Year,line,'r-', linewidth=3,label='Linear Regression Line')plt.plot(gender_equality.Year, gender_equality["Singapore"],label='Singapore')plt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Gender Ratio of Female to Male in school')plt.title('Gender Ratio of Female to Male in school for Singapore over time')plt.show()print("The correlation coefficient is " + str(r_value)) The correlation coefficient suggested that it is a good fit and gender ratio will potentially reach 100% in the future. This could be possible as education is no longer a privilege in Singapore as both males and females have equal opportunities in receiving formal education. Let’s finally move to Income data and plot the income of Singapore, United States and China over time. # read in dataincome = pd.read_csv('./Income.csv')# plot the graphsplt.plot(income.Year,income.Australia,label="Singapore")plt.plot(income.Year,income.China,label="China")plt.plot(income.Year,income["United States"],label="United States")# set up legends, labels, titleplt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Income per person')plt.title('Income per person over time')plt.show() Surprisingly, the income per person in Singapore is comparable to the United States, with both above those in China. Now, let’s try to build a motion chart to visualise relationships over time for all three factors of Population, Gender Ratio and Income. In order to build a motion chart in Python, we will need motionchart library. Before that, we will need to merge all three datasets into a single one to plot our motion chart easily. Merging can be done using common pandas commands. # Convert columns into rows for each data set based on country and population/gender ratio/incomepopulation=pd.melt(population,id_vars=['Year'],var_name='Country',value_name='Population')gender_equality=pd.melt(gender_equality,id_vars=['Year'],var_name='Country',value_name='Gender Ratio')# Merge the 3 datasets into one on common year and countryincome=pd.melt(income,id_vars=['Year'],var_name='Country',value_name='Income')overall=pd.merge(population,gender_equality,how="inner",on=["Year","Country"])overall=pd.merge(overall,income,how="inner",on=["Year","Country"]) To visualise relationship over time, we will need to set the Year attribute as the key in our motion chart. Our x-axis will be the Gender Ratio, y-axis the Income, size of the bubble for Population and lastly, colour of bubble for the Country. from motionchart.motionchart import MotionChart# setting up the style%%html<style>.output_wrapper, .output { height:auto !important; max-height:1000px; }.output_scroll { box-shadow:none !important; webkit-box-shadow:none !important;}</style># plotting the motion chartmChart = MotionChart(df = overall)mChart = MotionChart(df = overall, key='Year', x='Gender Ratio', y='Income', xscale='linear' , yscale='linear',size='Population', color='Country', category='Country')mChart.to_notebook() If we explore this motion chart, we know Afghanistan and Yemen had the lowest gender ratio in education of 23.7 and 30.1 respectively. Lesotho in South Africa has the highest gender ration throughout (note the little pink dot at the bottom right). There is generally not a clear relationship between income and gender ratio in education. During the whole period of time, as gender ratio is generally increasing for all countries, income did not follow likewise by increasing nor did it decrease. There was a mix of being stagnant, increasing and decreasing which did not exhibit any clear relationship with gender ratio. Let’s focus on building a motion chart for just Singapore. mChart = MotionChart(df = overall.loc[overall.Country.isin(['Singapore'])])mChart = MotionChart(df = overall.loc[overall.Country.isin(['Singapore'])], key='Year', x='Gender Ratio', y='Income', xscale='linear', yscale='linear',size='Population', color='Country', category='Country')mChart.to_notebook() Interestingly for Singapore, other than the Population increasing over time, Gender Ratio in Education as well as Income seems to increasing constantly over time as well. Income was at 11400 in 1970 and it increased tremendously to 80900 in 2015. In this article, we made use of Python matplotlib, linear regression as well as the fanciful motion charts to conduct exploratory data analysis on three datasets, mainly Population, Gender Ratio in Education & Income. Through these graphical methods, we can discover some insights on our data and potentially, allow us to make better predictions. Hope you guys enjoy this graphical approach to Exploratory Data Analysis in Python, and have fun playing with your fanciful motion charts!
[ { "code": null, "e": 618, "s": 172, "text": "Exploratory Data Analysis (EDA) is one of the most important aspect in every data science or data analysis problem. It provides us greater understanding on our data and can possibly unravel hidden insights that aren’t that obvious to us. The first article I’ve wrote on Medium is also on performing EDA in R, you can check it out here. This post will focus more on graphical EDA in Python using matplotlib, regression line and even motion chart!" }, { "code": null, "e": 768, "s": 618, "text": "The dataset we are using for this article can be obtained from Gapminder, and drilling down into Population, Gender Equality in Education and Income." }, { "code": null, "e": 915, "s": 768, "text": "The Population data contains yearly data regarding the estimated resident population, grouped by countries around the world between 1800 and 2018." }, { "code": null, "e": 1153, "s": 915, "text": "The Gender Equality in Education data contains yearly data between 1970 and 2015 on the ratio between female to male in schools, among 25 to 34 years old which includes primary, secondary and tertiary education across different countries" }, { "code": null, "e": 1366, "s": 1153, "text": "The Income data contains yearly data of income per person adjusted for differences in purchasing power (in international dollars) across different countries around the world, for the period between 1800 and 2018." }, { "code": null, "e": 1573, "s": 1366, "text": "Let’s first plot the population data over time, and focus mainly on the three countries Singapore, United States and China. We will use matplotlib library to plot 3 different line charts on the same figure." }, { "code": null, "e": 2065, "s": 1573, "text": "import pandas as pdimport matplotlib.pylab as plt%matplotlib inline# read in datapopulation = pd.read_csv('./population.csv')# plot for the 3 countriesplt.plot(population.Year,population.Singapore,label=\"Singapore\")plt.plot(population.Year,population.China,label=\"China\")plt.plot(population.Year,population[\"United States\"],label=\"United States\")# add legends, labels and titleplt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Population')plt.title('Population Growth over time')plt.show()" }, { "code": null, "e": 2318, "s": 2065, "text": "As seen in the figure, the population values for the 3 countries Singapore, China and United States are increasing over time, though Singapore is not that visible since the axis is in billions, while the population in Singapore is only in the millions." }, { "code": null, "e": 2509, "s": 2318, "text": "Now, let’s try to fit a linear regression line using linregressto the Singapore population data and plot the linear fit. We can even try predicting the Singapore population in 2020 and 2100." }, { "code": null, "e": 3512, "s": 2509, "text": "from scipy.stats import linregress# set up regression lineslope, intercept, r_value, p_value, std_err = linregress(population.Year,population.Singapore)line = [slope*xi + intercept for xi in population.Year]# plot the regression line and the linear fitplt.plot(population.Year,line,'r-', linewidth=3,label='Linear Regression Line')plt.scatter(population.Year, population.Singapore,label='Population of Singapore')plt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Population')plt.title('Population Growth of Singapore over time')plt.show()# Calculate correlation coefficient to see how well is the linear fitprint(\"The correlation coefficient is \" + str(r_value))## Use the linear fit to predict the resident population in Singapore in 2020 and 2100.# Using equation y=mx + c, i.e. population=slope*year + interceptprint(\"The predicted population in Singapore in 2020 will be \" + str((slope*2020)+intercept))print(\"The predicted population in Singapore in 2100 will be \" + str((slope*2100)+intercept))" }, { "code": null, "e": 3834, "s": 3512, "text": "From the figure, we see that the linear fit did not seem to fit the Population of Singapore that well though we have a correlation coefficient close to 1. The prediction of the population was also well off as the current population of Singapore in 2020 is around 5.6 million, which is way above the 3.4 million predicted." }, { "code": null, "e": 4006, "s": 3834, "text": "Notice that the population before 1850s were negative, which is definitely impossible. Since Singapore is founded in 1965, let’s filter to only use data from 1965 onwards." }, { "code": null, "e": 5096, "s": 4006, "text": "from scipy.stats import linregress# set up regression lineslope, intercept, r_value, p_value, std_err = linregress(population.Year[population.Year>=1965],population.Singapore[population.Year>=1965])line = [slope*xi + intercept for xi in population.Year[population.Year>=1965]]plt.plot(population.Year[population.Year>=1965],line,'r-', linewidth=3,label='Linear Regression Line')plt.scatter(population.Year[population.Year>=1965], population.Singapore[population.Year>=1965],label='Singapore')plt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Population')plt.title('Population Growth of Singapore from 1965 onwards')plt.show()# Calculate correlation coefficient to see how well is the linear fitprint(\"The correlation coefficient is \" + str(r_value))## Use the linear fit to predict the resident population in Singapore in 2020 and 2100.# Using equation y=mx + c, i.e. population=slope*year + interceptprint(\"The predicted population in Singapore in 2020 will be \" + str((slope*2020)+intercept))print(\"The predicted population in Singapore in 2100 will be \" + str((slope*2100)+intercept))" }, { "code": null, "e": 5406, "s": 5096, "text": "This linear regression line fits so much better as shown in the graph as well as the correlation coefficient. Furthermore, the predicted 2020 population is exactly what it is in Singapore currently, and let’s hope the 2100 population is not true since we know the land area in Singapore is considerably small." }, { "code": null, "e": 5639, "s": 5406, "text": "Moving onto the second dataset, let’s try to plot the gender ratio (females to males) in schools for Singapore, China and the United States over time. We can also look at the maximum and minimum gender ratio percentage in Singapore." }, { "code": null, "e": 6384, "s": 5639, "text": "# reading in datagender_equality = pd.read_csv('./GenderEquality.csv')# plot the graphsplt.plot(gender_equality.Year,gender_equality.Singapore,label=\"Singapore\")plt.plot(gender_equality.Year,gender_equality.China,label=\"China\")plt.plot(gender_equality.Year,gender_equality[\"United States\"],label=\"United States\")# set up legends, labels and titleplt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Gender Ratio of Female to Male in school')plt.title('Gender Ratio of Female to Male in school over time')plt.show()# What are the maximum and minimum values for gender ratio in Singapore over the time period?print(\"The maximum value is: \" + str(max(gender_equality.Singapore)) + \" and the minimum is \" + str(min(gender_equality.Singapore)))" }, { "code": null, "e": 6845, "s": 6384, "text": "The gender ratios were generally increasing over time as seen in the output above. Gender Ratio for China and Singapore were increasing linearly over time. For United States, there was certain periods in which the gender ratio were stagnant before increasing again. The minimum gender ratio for Singapore was 79.5 while the maximum was 98.9, and this was expected since education in Singapore in the past was considerably more important for males than females." }, { "code": null, "e": 6918, "s": 6845, "text": "Let’s plot the linear regression line on the gender ratio for Singapore." }, { "code": null, "e": 7510, "s": 6918, "text": "# plot the regression lineslope, intercept, r_value, p_value, std_err = linregress(gender_equality.Year,gender_equality[\"Singapore\"])line = [slope*xi + intercept for xi in gender_equality.Year]plt.plot(gender_equality.Year,line,'r-', linewidth=3,label='Linear Regression Line')plt.plot(gender_equality.Year, gender_equality[\"Singapore\"],label='Singapore')plt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Gender Ratio of Female to Male in school')plt.title('Gender Ratio of Female to Male in school for Singapore over time')plt.show()print(\"The correlation coefficient is \" + str(r_value))" }, { "code": null, "e": 7786, "s": 7510, "text": "The correlation coefficient suggested that it is a good fit and gender ratio will potentially reach 100% in the future. This could be possible as education is no longer a privilege in Singapore as both males and females have equal opportunities in receiving formal education." }, { "code": null, "e": 7889, "s": 7786, "text": "Let’s finally move to Income data and plot the income of Singapore, United States and China over time." }, { "code": null, "e": 8280, "s": 7889, "text": "# read in dataincome = pd.read_csv('./Income.csv')# plot the graphsplt.plot(income.Year,income.Australia,label=\"Singapore\")plt.plot(income.Year,income.China,label=\"China\")plt.plot(income.Year,income[\"United States\"],label=\"United States\")# set up legends, labels, titleplt.legend(loc='best')plt.xlabel('Year')plt.ylabel('Income per person')plt.title('Income per person over time')plt.show()" }, { "code": null, "e": 8397, "s": 8280, "text": "Surprisingly, the income per person in Singapore is comparable to the United States, with both above those in China." }, { "code": null, "e": 8613, "s": 8397, "text": "Now, let’s try to build a motion chart to visualise relationships over time for all three factors of Population, Gender Ratio and Income. In order to build a motion chart in Python, we will need motionchart library." }, { "code": null, "e": 8768, "s": 8613, "text": "Before that, we will need to merge all three datasets into a single one to plot our motion chart easily. Merging can be done using common pandas commands." }, { "code": null, "e": 9338, "s": 8768, "text": "# Convert columns into rows for each data set based on country and population/gender ratio/incomepopulation=pd.melt(population,id_vars=['Year'],var_name='Country',value_name='Population')gender_equality=pd.melt(gender_equality,id_vars=['Year'],var_name='Country',value_name='Gender Ratio')# Merge the 3 datasets into one on common year and countryincome=pd.melt(income,id_vars=['Year'],var_name='Country',value_name='Income')overall=pd.merge(population,gender_equality,how=\"inner\",on=[\"Year\",\"Country\"])overall=pd.merge(overall,income,how=\"inner\",on=[\"Year\",\"Country\"])" }, { "code": null, "e": 9582, "s": 9338, "text": "To visualise relationship over time, we will need to set the Year attribute as the key in our motion chart. Our x-axis will be the Gender Ratio, y-axis the Income, size of the bubble for Population and lastly, colour of bubble for the Country." }, { "code": null, "e": 10103, "s": 9582, "text": "from motionchart.motionchart import MotionChart# setting up the style%%html<style>.output_wrapper, .output { height:auto !important; max-height:1000px; }.output_scroll { box-shadow:none !important; webkit-box-shadow:none !important;}</style># plotting the motion chartmChart = MotionChart(df = overall)mChart = MotionChart(df = overall, key='Year', x='Gender Ratio', y='Income', xscale='linear' , yscale='linear',size='Population', color='Country', category='Country')mChart.to_notebook()" }, { "code": null, "e": 10351, "s": 10103, "text": "If we explore this motion chart, we know Afghanistan and Yemen had the lowest gender ratio in education of 23.7 and 30.1 respectively. Lesotho in South Africa has the highest gender ration throughout (note the little pink dot at the bottom right)." }, { "code": null, "e": 10724, "s": 10351, "text": "There is generally not a clear relationship between income and gender ratio in education. During the whole period of time, as gender ratio is generally increasing for all countries, income did not follow likewise by increasing nor did it decrease. There was a mix of being stagnant, increasing and decreasing which did not exhibit any clear relationship with gender ratio." }, { "code": null, "e": 10783, "s": 10724, "text": "Let’s focus on building a motion chart for just Singapore." }, { "code": null, "e": 11085, "s": 10783, "text": "mChart = MotionChart(df = overall.loc[overall.Country.isin(['Singapore'])])mChart = MotionChart(df = overall.loc[overall.Country.isin(['Singapore'])], key='Year', x='Gender Ratio', y='Income', xscale='linear', yscale='linear',size='Population', color='Country', category='Country')mChart.to_notebook()" }, { "code": null, "e": 11332, "s": 11085, "text": "Interestingly for Singapore, other than the Population increasing over time, Gender Ratio in Education as well as Income seems to increasing constantly over time as well. Income was at 11400 in 1970 and it increased tremendously to 80900 in 2015." } ]
Knowing the complexity in competitive programming - GeeksforGeeks
24 May, 2018 Prerequisite: Time Complexity Analysis Generally, while doing competitive programming problems on various sites, the most difficult task faced is writing the code under desired complexity otherwise the program will get a TLE ( Time Limit Exceeded ). A naive solution is almost never accepted. So how to know, what complexity is acceptable? The answer to this question is directly related to the number of operations that are allowed to perform within a second. Most of the sites these days allow 108 operations per second, only a few sites still allow 107 operations. After figuring out the number of operations that can be performed, search for the right complexity by looking at the constraints given in the problem. Example:Given an array A[] and a number x, check for a pair in A[] with the sum as x.where N is: 1) 1 <= N <= 103 2) 1 <= N <= 105 3) 1 <= N <= 108 For Case 1A naive solution that is using two for-loops works as it gives us a complexity of O(N2), which even in the worst case will perform 106 operations which are well under 108. Ofcourse O(N) and O(NlogN) is also acceptable in this case. For Case 2We have to think of a better solution than O(N2), as in worst case, it will perform 1010 operations as N is 105. So complexity acceptable for this case is either O(NlogN) which is approximately 106 (105 * ~10) operations well under 108 or O(N). For Case 3Even O(NlogN) gives us TLE as it performs ~109 operations which are over 108. So the only solution which is acceptable is O(N) which in worst case will perform 10^8 operations. The code for the given problem can be found on : https://www.geeksforgeeks.org/write-a-c-program-that-given-a-set-a-of-n-numbers-and-another-number-x-determines-whether-or-not-there-exist-two-elements-in-s-whose-sum-is-exactly-x/ Analysis Competitive Programming GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Proof that Dominant Set of a Graph is NP-Complete 3-coloring is NP Complete Difference between Deterministic and Non-deterministic Algorithms Set partition is NP complete Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Competitive Programming - A Complete Guide Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 24653, "s": 24625, "text": "\n24 May, 2018" }, { "code": null, "e": 24692, "s": 24653, "text": "Prerequisite: Time Complexity Analysis" }, { "code": null, "e": 24993, "s": 24692, "text": "Generally, while doing competitive programming problems on various sites, the most difficult task faced is writing the code under desired complexity otherwise the program will get a TLE ( Time Limit Exceeded ). A naive solution is almost never accepted. So how to know, what complexity is acceptable?" }, { "code": null, "e": 25372, "s": 24993, "text": "The answer to this question is directly related to the number of operations that are allowed to perform within a second. Most of the sites these days allow 108 operations per second, only a few sites still allow 107 operations. After figuring out the number of operations that can be performed, search for the right complexity by looking at the constraints given in the problem." }, { "code": null, "e": 25469, "s": 25372, "text": "Example:Given an array A[] and a number x, check for a pair in A[] with the sum as x.where N is:" }, { "code": null, "e": 25521, "s": 25469, "text": "1) 1 <= N <= 103\n2) 1 <= N <= 105\n3) 1 <= N <= 108\n" }, { "code": null, "e": 25763, "s": 25521, "text": "For Case 1A naive solution that is using two for-loops works as it gives us a complexity of O(N2), which even in the worst case will perform 106 operations which are well under 108. Ofcourse O(N) and O(NlogN) is also acceptable in this case." }, { "code": null, "e": 26018, "s": 25763, "text": "For Case 2We have to think of a better solution than O(N2), as in worst case, it will perform 1010 operations as N is 105. So complexity acceptable for this case is either O(NlogN) which is approximately 106 (105 * ~10) operations well under 108 or O(N)." }, { "code": null, "e": 26205, "s": 26018, "text": "For Case 3Even O(NlogN) gives us TLE as it performs ~109 operations which are over 108. So the only solution which is acceptable is O(N) which in worst case will perform 10^8 operations." }, { "code": null, "e": 26435, "s": 26205, "text": "The code for the given problem can be found on : https://www.geeksforgeeks.org/write-a-c-program-that-given-a-set-a-of-n-numbers-and-another-number-x-determines-whether-or-not-there-exist-two-elements-in-s-whose-sum-is-exactly-x/" }, { "code": null, "e": 26444, "s": 26435, "text": "Analysis" }, { "code": null, "e": 26468, "s": 26444, "text": "Competitive Programming" }, { "code": null, "e": 26474, "s": 26468, "text": "GBlog" }, { "code": null, "e": 26572, "s": 26474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26581, "s": 26572, "text": "Comments" }, { "code": null, "e": 26594, "s": 26581, "text": "Old Comments" }, { "code": null, "e": 26661, "s": 26594, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 26711, "s": 26661, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 26737, "s": 26711, "text": "3-coloring is NP Complete" }, { "code": null, "e": 26803, "s": 26737, "text": "Difference between Deterministic and Non-deterministic Algorithms" }, { "code": null, "e": 26832, "s": 26803, "text": "Set partition is NP complete" }, { "code": null, "e": 26875, "s": 26832, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 26916, "s": 26875, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26959, "s": 26916, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 26986, "s": 26959, "text": "Modulo 10^9+7 (1000000007)" } ]
Tryit Editor v3.7
Tryit: HTML table border
[]
How to add CSS
When a browser reads a style sheet, it will format the HTML document according to the information in the style sheet. There are three ways of inserting a style sheet: External CSS Internal CSS Inline CSS With an external style sheet, you can change the look of an entire website by changing just one file! Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section. External styles are defined within the <link> element, inside the <head> section of an HTML page: An external style sheet can be written in any text editor, and must be saved with a .css extension. The external .css file should not contain any HTML tags. Here is how the "mystyle.css" file looks: Note: Do not add a space between the property value and the unit: Incorrect (space): margin-left: 20 px; Correct (nospace): margin-left: 20px; An internal style sheet may be used if one single HTML page has a unique style. The internal style is defined inside the <style> element, inside the head section. Internal styles are defined within the <style> element, inside the <head> section of an HTML page: An inline style may be used to apply a unique style for a single element. To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property. Inline styles are defined within the "style" attribute of the relevant element: Tip: An inline style loses many of the advantages of a style sheet (by mixing content with presentation). Use this method sparingly. If some properties have been defined for the same selector (element) in different style sheets, the value from the last read style sheet will be used. Assume that an external style sheet has the following style for the <h1> element: Then, assume that an internal style sheet also has the following style for the <h1> element: If the internal style is defined after the link to the external style sheet, the <h1> elements will be "orange": However, if the internal style is defined before the link to the external style sheet, the <h1> elements will be "navy": What style will be used when there is more than one style specified for an HTML element? All the styles in a page will "cascade" into a new "virtual" style sheet by the following rules, where number one has the highest priority: Inline style (inside an HTML element) External and internal style sheets (in the head section) Browser default Inline style (inside an HTML element) External and internal style sheets (in the head section) Browser default So, an inline style has the highest priority, and will override external and internal styles and browser defaults. Try it Yourself » Ever heard about W3Schools Spaces? Here you can create your own website, or save code snippets for later use, for free. * no credit card required Add an external style sheet with the URL: "mystyle.css". <head> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph</p> <p>This is a paragraph</p> </body> Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 119, "s": 0, "text": "When a browser reads a style sheet, it will format the HTML document according to \nthe information in the style sheet." }, { "code": null, "e": 168, "s": 119, "text": "There are three ways of inserting a style sheet:" }, { "code": null, "e": 181, "s": 168, "text": "External CSS" }, { "code": null, "e": 194, "s": 181, "text": "Internal CSS" }, { "code": null, "e": 205, "s": 194, "text": "Inline CSS" }, { "code": null, "e": 308, "s": 205, "text": "With an\nexternal style sheet, you can change the look of an entire website by changing \njust one file!" }, { "code": null, "e": 434, "s": 308, "text": "Each HTML page must include a reference to the external style sheet file inside \nthe <link> element, inside the head section." }, { "code": null, "e": 532, "s": 434, "text": "External styles are defined within the <link> element, inside the <head> section of an HTML page:" }, { "code": null, "e": 632, "s": 532, "text": "An external style sheet can be written in any text editor, and must be saved with a .css extension." }, { "code": null, "e": 689, "s": 632, "text": "The external .css file should not contain any HTML tags." }, { "code": null, "e": 731, "s": 689, "text": "Here is how the \"mystyle.css\" file looks:" }, { "code": null, "e": 878, "s": 731, "text": "Note: Do not add a space between the property value and the unit:\n Incorrect (space): margin-left: 20 px;\n Correct (nospace): margin-left: 20px;" }, { "code": null, "e": 958, "s": 878, "text": "An internal style sheet may be used if one single HTML page has a unique style." }, { "code": null, "e": 1042, "s": 958, "text": "The internal style is defined inside the <style> element, inside the head \nsection." }, { "code": null, "e": 1141, "s": 1042, "text": "Internal styles are defined within the <style> element, inside the <head> section of an HTML page:" }, { "code": null, "e": 1215, "s": 1141, "text": "An inline style may be used to apply a unique style for a single element." }, { "code": null, "e": 1336, "s": 1215, "text": "To use inline styles, add the style attribute to the relevant element. The\nstyle attribute can contain any CSS property." }, { "code": null, "e": 1419, "s": 1336, "text": "Inline styles are defined within the \"style\" attribute of the relevant \n element:" }, { "code": null, "e": 1552, "s": 1419, "text": "Tip: An inline style loses many of the advantages of a style sheet (by mixing\ncontent with presentation). Use this method sparingly." }, { "code": null, "e": 1704, "s": 1552, "text": "If some properties have been defined for the same selector (element) in different style sheets,\nthe value from the last read style sheet will be used. " }, { "code": null, "e": 1787, "s": 1704, "text": " Assume that an external style sheet has the following style for the <h1> element:" }, { "code": null, "e": 1880, "s": 1787, "text": "Then, assume that an internal style sheet also has the following style for the <h1> element:" }, { "code": null, "e": 1994, "s": 1880, "text": "If the internal style is defined after the link to the external style sheet, the <h1> elements will be \n\"orange\":" }, { "code": null, "e": 2117, "s": 1994, "text": "However, if the internal style is defined before the link to the external style sheet, the <h1> elements will be \n\"navy\": " }, { "code": null, "e": 2206, "s": 2117, "text": "What style will be used when there is more than one style specified for an HTML element?" }, { "code": null, "e": 2346, "s": 2206, "text": "All the styles in a page will \"cascade\" into a new \"virtual\" style\nsheet by the following rules, where number one has the highest priority:" }, { "code": null, "e": 2459, "s": 2346, "text": "\nInline style (inside an HTML element)\nExternal and internal style sheets (in the head section)\nBrowser default\n" }, { "code": null, "e": 2497, "s": 2459, "text": "Inline style (inside an HTML element)" }, { "code": null, "e": 2554, "s": 2497, "text": "External and internal style sheets (in the head section)" }, { "code": null, "e": 2570, "s": 2554, "text": "Browser default" }, { "code": null, "e": 2686, "s": 2570, "text": "So, an inline style has the highest priority, and will override external and \ninternal styles and browser defaults." }, { "code": null, "e": 2704, "s": 2686, "text": "Try it Yourself »" }, { "code": null, "e": 2824, "s": 2704, "text": "Ever heard about W3Schools Spaces? Here you can create your own website, or save code snippets for later use, for free." }, { "code": null, "e": 2850, "s": 2824, "text": "* no credit card required" }, { "code": null, "e": 2907, "s": 2850, "text": "Add an external style sheet with the URL: \"mystyle.css\"." }, { "code": null, "e": 3027, "s": 2907, "text": "<head>\n\n</head>\n\n<body>\n <h1>This is a heading</h1>\n <p>This is a paragraph</p>\n <p>This is a paragraph</p>\n</body>\n" }, { "code": null, "e": 3046, "s": 3027, "text": "Start the Exercise" }, { "code": null, "e": 3079, "s": 3046, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3121, "s": 3079, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3228, "s": 3121, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 3247, "s": 3228, "text": "help@w3schools.com" } ]
How to list all triggers in a MySQL database?
To list all triggers in a MySQL database, you can use the SHOW command. The query is as follows − mysql> show triggers; The following is the output − +----------------+--------+----------------------+--------------------------------------------------------------------+--------+------------------------+--------------------------------------------+---------+----------------------+----------------------+--------------------+ | Trigger | Event | Table | Statement | Timing | Created | sql_mode | Definer | character_set_client | collation_connection | Database Collation | +----------------+--------+----------------------+--------------------------------------------------------------------+--------+------------------------+--------------------------------------------+---------+----------------------+----------------------+--------------------+ | binsertTrigger | INSERT | functiontriggersdemo | SET new.Id = uuid() | BEFORE | 2018-10-16 13:36:09.86 | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | root@% | cp850 | cp850_general_ci | utf8mb4_unicode_ci | | Table1Trigger | INSERT | table1 | begin insert into Table2(id, name) values (new.id, new.name); end | AFTER | 2018-10-23 10:51:31.76 | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | root@% | cp850 | cp850_general_ci | utf8mb4_unicode_ci | | insertBef | INSERT | tblfunctiontrigger | SET new.id = uuid() | BEFORE | 2018-10-16 13:44:10.93 | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | root@% | cp850 | cp850_general_ci | utf8mb4_unicode_ci | +----------------+--------+----------------------+--------------------------------------------------------------------+--------+------------------------+--------------------------------------------+---------+----------------------+----------------------+--------------------+ 3 rows in set (0.13 sec) You can access information_schema table with the help of the following query. Note − You need to have MySQL version 5.0.10 and above. I am currently using MySQL version 8.0.12 − mysql> select trigger_schema, trigger_name, action_statement −> from information_schema.triggers; The following is the output − +----------------+----------------------------+-------------------------------------------------------------------------------------------------------------------+ | TRIGGER_SCHEMA | TRIGGER_NAME | ACTION_STATEMENT | +----------------+----------------------------+-------------------------------------------------------------------------------------------------------------------+ | sys | sys_config_insert_set_user | BEGIN IF @sys.ignore_sys_config_triggers != true AND NEW.set_by IS NULL THEN SET NEW.set_by = USER(); END IF; END | | sys | sys_config_update_set_user | BEGIN IF @sys.ignore_sys_config_triggers != true AND NEW.set_by IS NULL THEN SET NEW.set_by = USER(); END IF; END | | business | binsertTrigger | SET new.Id = uuid() | | business | insertBef | SET new.id = uuid() | | business | Table1Trigger | begin insert into Table2(id, name) values (new.id, new.name);end | +----------------+----------------------------+-------------------------------------------------------------------------------------------------------------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1160, "s": 1062, "text": "To list all triggers in a MySQL database, you can use the SHOW command. The query is as follows −" }, { "code": null, "e": 1182, "s": 1160, "text": "mysql> show triggers;" }, { "code": null, "e": 1212, "s": 1182, "text": "The following is the output −" }, { "code": null, "e": 2991, "s": 1212, "text": "+----------------+--------+----------------------+--------------------------------------------------------------------+--------+------------------------+--------------------------------------------+---------+----------------------+----------------------+--------------------+\n| Trigger | Event | Table | Statement | Timing | Created | sql_mode | Definer | character_set_client | collation_connection | Database Collation |\n+----------------+--------+----------------------+--------------------------------------------------------------------+--------+------------------------+--------------------------------------------+---------+----------------------+----------------------+--------------------+\n| binsertTrigger | INSERT | functiontriggersdemo | SET new.Id = uuid() | BEFORE | 2018-10-16 13:36:09.86 | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | root@% | cp850 | cp850_general_ci | utf8mb4_unicode_ci |\n| Table1Trigger | INSERT | table1 | begin\ninsert into Table2(id, name) values (new.id, new.name);\nend | AFTER | 2018-10-23 10:51:31.76 | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | root@% | cp850 | cp850_general_ci | utf8mb4_unicode_ci |\n| insertBef | INSERT | tblfunctiontrigger | SET new.id = uuid() | BEFORE | 2018-10-16 13:44:10.93 | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | root@% | cp850 | cp850_general_ci | utf8mb4_unicode_ci |\n+----------------+--------+----------------------+--------------------------------------------------------------------+--------+------------------------+--------------------------------------------+---------+----------------------+----------------------+--------------------+\n3 rows in set (0.13 sec)" }, { "code": null, "e": 3069, "s": 2991, "text": "You can access information_schema table with the help of the following query." }, { "code": null, "e": 3169, "s": 3069, "text": "Note − You need to have MySQL version 5.0.10 and above. I am currently using MySQL version 8.0.12 −" }, { "code": null, "e": 3267, "s": 3169, "text": "mysql> select trigger_schema, trigger_name, action_statement\n−> from information_schema.triggers;" }, { "code": null, "e": 3297, "s": 3267, "text": "The following is the output −" }, { "code": null, "e": 4852, "s": 3297, "text": "+----------------+----------------------------+-------------------------------------------------------------------------------------------------------------------+\n| TRIGGER_SCHEMA | TRIGGER_NAME | ACTION_STATEMENT |\n+----------------+----------------------------+-------------------------------------------------------------------------------------------------------------------+\n| sys | sys_config_insert_set_user | BEGIN IF @sys.ignore_sys_config_triggers != true AND NEW.set_by IS NULL THEN SET NEW.set_by = USER(); END IF; END |\n| sys | sys_config_update_set_user | BEGIN IF @sys.ignore_sys_config_triggers != true AND NEW.set_by IS NULL THEN SET NEW.set_by = USER(); END IF; END |\n| business | binsertTrigger | SET new.Id = uuid() |\n| business | insertBef | SET new.id = uuid() |\n| business | Table1Trigger | begin\ninsert into Table2(id, name) values (new.id, new.name);end |\n+----------------+----------------------------+-------------------------------------------------------------------------------------------------------------------+\n5 rows in set (0.00 sec)" } ]
Setting Up Jupyter Notebooks for Data Visualization in Python | by Alan Jones | Towards Data Science
We are going to see how you set up the Jupyter Notebooks environment with Anaconda, see how to create a notebook and then plot your first graph. Although the language used to create the plots is Python, you don’t really have to know much about programming, as only a very limited set of the language is needed. You will need to learn the particular syntax of the plotting commands in Pandas and/or Seaborn but not much else. In the example above most of the code is boilerplate stuff, it’s the final line that does the work. You can use Pandas or Seaborn by writing a Python program in a programmer’s editor and running that program. But I think that the easiest way to produce nice charts, in an interactive environment, is with a Jupyter Notebook. So, first of all we are going to set up Jupyter Notebook environment. This guide is not aimed at seasoned programmers, so I’m going to assume that you do not have Python installed on your computer and will, instead, urge you to install Anaconda on your machine. Anaconda is single package that contains an implementation of Python along with a whole set of data science libraries. Downloading and installation is straightforward and once installed you will have a vast range of data science and AI tools available to you from a single graphical interface. These tools include Python, Pandas and Jupyter, as well as all the libraries that you need to support them. Anaconda is quite big — several gigabytes — but since most computers come with hundreds of gigabytes of storage that probably is not a big deal for most people. For those who are short of space (like when I installed it on a Windows tablet) there is a smaller alternative, Miniconda, but that requires a little more work — I’ll cover that separately but, for now we’ll consider the full version. Anaconda is available for Windows, MacOS and Linux, and comes in 32 or 64 bit versions. It also comes in versions that include Python 2.7 Python 3.x — I recommend that you choose the latest Python 3 version that is right for your machine. First, go to the Anaconda downloads page and, about halfway down you will see links to your operating system, Windows, MacOS or Linux. Click on the right one for you, to download the installer. When you have the installer downloaded you can find detailed instructions on how to install it on the appropriate installation page. I’ve listed them here, for convenience. Install Anaconda on Windows Install Anaconda on MacOS Install Anaconda on Linux However, installation is straightforward. For Windows and Mac users, just download the appropriate version from the web site and install as you would any other program; admin rights are not needed. For Linux users you do not use apt-get to install, as you might expect. Download the installer, open a terminal window, navigate to where your download is and run the command: bash ./whatever-your-file-is-called.sh During the install, it’s probably best simply to accept default options when you are given a choice. Once it has got going, the install can be left to its own devices — it may take a while depending on the speed of your internet connection and your PC. Towards the end of the installation, you will be asked if you want to install Microsoft’s Visual Studio Code. This is quite a good programmer’s editor but if you decide against installing it at this stage, you can always install it at a later date. Once installed on a Windows machine, or a Mac, you should find various new items in your start menu. One of them will be the Anaconda Navigator (as shown above). You can also find entries for Jupyter Notebooks and the Anaconda prompt. On Linux, you may not have these entries added to your menu. If this is the case, then simply open a terminal window and type the command: anaconda-navigator This way you will get the Anaconda GUI from which you can start a Jupyter Notebook. And that’s about it. With Anaconda installed you are ready to start using Jupyter to produce great data visualisations. The next article will be about actually using a notebook and producing a first visualisation using Pandas. When it is ready I’ll put a link, here. I’m going to start with the Anaconda Navigator GUI as launching a notebook from here is the same whether you are using Windows, MacOS or Linux. Here’s the Navigator screen: As you can see, the panel on the top left of the main window is for Jupyter Notebooks and to get going simply click on the Launch button. (Your layout may not be the same as mine but the Jupyter Notebook panel will be there somewhere, if it is installed.) But just before you do, you should know that Jupyter runs in your browser. Launching Jupyter will create a new tab in your default browser with a page that looks something like this: Of course, since this the home folder on my Windows tablet, your screen won’t look exactly the same. But it will probably contain a number of folders that you don’t want littered up with notebooks. So, the first thing that you will probably want to do is create a new directory for your work. So, click on the New drop down and select Folder. You will now have a new folder called Untitled Folder. Scroll down to find it and click the check box next to it so that it is ticked and then select Rename from the top of the screen and give it a new name. Now here’s a trick. You are probably going to want to use this directory every time you open Jupyter. And if like me you have a whole load of folders to scroll down through, you might want to choose a name that would position it near the top. I called my folder “_Notebooks”. The underscore brings it up to the second item on the list so easily seen and clicked on. Now double click on your new folder and you will see something like this: Now we are ready to create our first notebook. Click New again but this time select Python3. This will open a new tab in your browser which is your new notebook — it will look like this: The import bit to notice is the field with the coloured bar on the left. This is a cell. In a cell you can write text or code. The default is code and we are going to write the following code in our cell (I suggest that you cut and paste it from the text, below): import numpy as np, pandas as pd, matplotlib.pyplot as plt This line of code imports the necessary libraries that will allow us to do basic visualisation of data. We are importing three libraries, numpy, which provides numerical support for large multi-dimensional arrays, pandas, which provides more data structures and data analysis tools, and matplotlib,which provides a 2D plotting library that is used by pandas to produce charts in a variety of formats. Now, click on the + icon to create another cell and write the following into it (again, I suggest that you cut and paste this text): data = pd.Series([0,1,2,3,4,5,6,7,8,9])data.plot() You should end up with something like this: Now, if you are a programmer, you will know what a variable is, and will recognise data as being one. If you are not a programmer, then you only need to understand that a variable is a basically something that can hold a value. So, for example, we could have a variable called x and give it the value 5; we can then use the name x in various operations and it would represent the value 5. You can think of it as a short cut to using the value. In the case of the variable I’ve called data, its value is rather more complex than a single number; it’s actually a series of numbers (and we use the pandas library to create a data structure that contains that series). Using pandas we can create all sort of data structures which are, essentially various forms of data tables, in this case, our series of numbers is like a single row of numbers from a table. So, the first line of our second cell gives, or assigns, the value 0,1,2,3,4,5,6,7,8,9 to the variable data. Now we can invoke the magic of the pandas library. The second line of this cell produces a plot, a graph, based on the series of numbers in data. Let’s try it. First select the first cell and click on the icon that looks like a ‘play’ button. This will execute the code in that cell. Nothing much will happen, although you should notice that the asterisk has changed to a number. (an asterisk denotes a cell which has not yet been executed). However, executing this cell has imported the libraries that we need. Now select the second cell and click the play icon. This time something much more exiting happens. You will see this image displayed in the cell. It’s is, of course, a simple line plot of the data which, as we would expect, results in a straight line graph. We’ve seen how to install Anaconda and Jupyter Notebooks, and how to create out first data visualization. There is, of course, much more to discover: how to import a data set and how to create different types of visualization, not just line graphs, but scatter diagrams, bar charts and pie charts, for example. You can see a article on plotting various graphs with Python and Pandas, here: towardsdatascience.com and other articles here:
[ { "code": null, "e": 316, "s": 171, "text": "We are going to see how you set up the Jupyter Notebooks environment with Anaconda, see how to create a notebook and then plot your first graph." }, { "code": null, "e": 696, "s": 316, "text": "Although the language used to create the plots is Python, you don’t really have to know much about programming, as only a very limited set of the language is needed. You will need to learn the particular syntax of the plotting commands in Pandas and/or Seaborn but not much else. In the example above most of the code is boilerplate stuff, it’s the final line that does the work." }, { "code": null, "e": 921, "s": 696, "text": "You can use Pandas or Seaborn by writing a Python program in a programmer’s editor and running that program. But I think that the easiest way to produce nice charts, in an interactive environment, is with a Jupyter Notebook." }, { "code": null, "e": 991, "s": 921, "text": "So, first of all we are going to set up Jupyter Notebook environment." }, { "code": null, "e": 1183, "s": 991, "text": "This guide is not aimed at seasoned programmers, so I’m going to assume that you do not have Python installed on your computer and will, instead, urge you to install Anaconda on your machine." }, { "code": null, "e": 1302, "s": 1183, "text": "Anaconda is single package that contains an implementation of Python along with a whole set of data science libraries." }, { "code": null, "e": 1585, "s": 1302, "text": "Downloading and installation is straightforward and once installed you will have a vast range of data science and AI tools available to you from a single graphical interface. These tools include Python, Pandas and Jupyter, as well as all the libraries that you need to support them." }, { "code": null, "e": 1981, "s": 1585, "text": "Anaconda is quite big — several gigabytes — but since most computers come with hundreds of gigabytes of storage that probably is not a big deal for most people. For those who are short of space (like when I installed it on a Windows tablet) there is a smaller alternative, Miniconda, but that requires a little more work — I’ll cover that separately but, for now we’ll consider the full version." }, { "code": null, "e": 2220, "s": 1981, "text": "Anaconda is available for Windows, MacOS and Linux, and comes in 32 or 64 bit versions. It also comes in versions that include Python 2.7 Python 3.x — I recommend that you choose the latest Python 3 version that is right for your machine." }, { "code": null, "e": 2414, "s": 2220, "text": "First, go to the Anaconda downloads page and, about halfway down you will see links to your operating system, Windows, MacOS or Linux. Click on the right one for you, to download the installer." }, { "code": null, "e": 2587, "s": 2414, "text": "When you have the installer downloaded you can find detailed instructions on how to install it on the appropriate installation page. I’ve listed them here, for convenience." }, { "code": null, "e": 2615, "s": 2587, "text": "Install Anaconda on Windows" }, { "code": null, "e": 2641, "s": 2615, "text": "Install Anaconda on MacOS" }, { "code": null, "e": 2667, "s": 2641, "text": "Install Anaconda on Linux" }, { "code": null, "e": 2865, "s": 2667, "text": "However, installation is straightforward. For Windows and Mac users, just download the appropriate version from the web site and install as you would any other program; admin rights are not needed." }, { "code": null, "e": 3041, "s": 2865, "text": "For Linux users you do not use apt-get to install, as you might expect. Download the installer, open a terminal window, navigate to where your download is and run the command:" }, { "code": null, "e": 3080, "s": 3041, "text": "bash ./whatever-your-file-is-called.sh" }, { "code": null, "e": 3333, "s": 3080, "text": "During the install, it’s probably best simply to accept default options when you are given a choice. Once it has got going, the install can be left to its own devices — it may take a while depending on the speed of your internet connection and your PC." }, { "code": null, "e": 3582, "s": 3333, "text": "Towards the end of the installation, you will be asked if you want to install Microsoft’s Visual Studio Code. This is quite a good programmer’s editor but if you decide against installing it at this stage, you can always install it at a later date." }, { "code": null, "e": 3817, "s": 3582, "text": "Once installed on a Windows machine, or a Mac, you should find various new items in your start menu. One of them will be the Anaconda Navigator (as shown above). You can also find entries for Jupyter Notebooks and the Anaconda prompt." }, { "code": null, "e": 3956, "s": 3817, "text": "On Linux, you may not have these entries added to your menu. If this is the case, then simply open a terminal window and type the command:" }, { "code": null, "e": 3975, "s": 3956, "text": "anaconda-navigator" }, { "code": null, "e": 4059, "s": 3975, "text": "This way you will get the Anaconda GUI from which you can start a Jupyter Notebook." }, { "code": null, "e": 4179, "s": 4059, "text": "And that’s about it. With Anaconda installed you are ready to start using Jupyter to produce great data visualisations." }, { "code": null, "e": 4326, "s": 4179, "text": "The next article will be about actually using a notebook and producing a first visualisation using Pandas. When it is ready I’ll put a link, here." }, { "code": null, "e": 4470, "s": 4326, "text": "I’m going to start with the Anaconda Navigator GUI as launching a notebook from here is the same whether you are using Windows, MacOS or Linux." }, { "code": null, "e": 4499, "s": 4470, "text": "Here’s the Navigator screen:" }, { "code": null, "e": 4755, "s": 4499, "text": "As you can see, the panel on the top left of the main window is for Jupyter Notebooks and to get going simply click on the Launch button. (Your layout may not be the same as mine but the Jupyter Notebook panel will be there somewhere, if it is installed.)" }, { "code": null, "e": 4938, "s": 4755, "text": "But just before you do, you should know that Jupyter runs in your browser. Launching Jupyter will create a new tab in your default browser with a page that looks something like this:" }, { "code": null, "e": 5231, "s": 4938, "text": "Of course, since this the home folder on my Windows tablet, your screen won’t look exactly the same. But it will probably contain a number of folders that you don’t want littered up with notebooks. So, the first thing that you will probably want to do is create a new directory for your work." }, { "code": null, "e": 5281, "s": 5231, "text": "So, click on the New drop down and select Folder." }, { "code": null, "e": 5489, "s": 5281, "text": "You will now have a new folder called Untitled Folder. Scroll down to find it and click the check box next to it so that it is ticked and then select Rename from the top of the screen and give it a new name." }, { "code": null, "e": 5855, "s": 5489, "text": "Now here’s a trick. You are probably going to want to use this directory every time you open Jupyter. And if like me you have a whole load of folders to scroll down through, you might want to choose a name that would position it near the top. I called my folder “_Notebooks”. The underscore brings it up to the second item on the list so easily seen and clicked on." }, { "code": null, "e": 5929, "s": 5855, "text": "Now double click on your new folder and you will see something like this:" }, { "code": null, "e": 6116, "s": 5929, "text": "Now we are ready to create our first notebook. Click New again but this time select Python3. This will open a new tab in your browser which is your new notebook — it will look like this:" }, { "code": null, "e": 6380, "s": 6116, "text": "The import bit to notice is the field with the coloured bar on the left. This is a cell. In a cell you can write text or code. The default is code and we are going to write the following code in our cell (I suggest that you cut and paste it from the text, below):" }, { "code": null, "e": 6440, "s": 6380, "text": "import numpy as np, pandas as pd, matplotlib.pyplot as plt " }, { "code": null, "e": 6841, "s": 6440, "text": "This line of code imports the necessary libraries that will allow us to do basic visualisation of data. We are importing three libraries, numpy, which provides numerical support for large multi-dimensional arrays, pandas, which provides more data structures and data analysis tools, and matplotlib,which provides a 2D plotting library that is used by pandas to produce charts in a variety of formats." }, { "code": null, "e": 6974, "s": 6841, "text": "Now, click on the + icon to create another cell and write the following into it (again, I suggest that you cut and paste this text):" }, { "code": null, "e": 7026, "s": 6974, "text": "data = pd.Series([0,1,2,3,4,5,6,7,8,9])data.plot() " }, { "code": null, "e": 7070, "s": 7026, "text": "You should end up with something like this:" }, { "code": null, "e": 7514, "s": 7070, "text": "Now, if you are a programmer, you will know what a variable is, and will recognise data as being one. If you are not a programmer, then you only need to understand that a variable is a basically something that can hold a value. So, for example, we could have a variable called x and give it the value 5; we can then use the name x in various operations and it would represent the value 5. You can think of it as a short cut to using the value." }, { "code": null, "e": 7925, "s": 7514, "text": "In the case of the variable I’ve called data, its value is rather more complex than a single number; it’s actually a series of numbers (and we use the pandas library to create a data structure that contains that series). Using pandas we can create all sort of data structures which are, essentially various forms of data tables, in this case, our series of numbers is like a single row of numbers from a table." }, { "code": null, "e": 8034, "s": 7925, "text": "So, the first line of our second cell gives, or assigns, the value 0,1,2,3,4,5,6,7,8,9 to the variable data." }, { "code": null, "e": 8085, "s": 8034, "text": "Now we can invoke the magic of the pandas library." }, { "code": null, "e": 8180, "s": 8085, "text": "The second line of this cell produces a plot, a graph, based on the series of numbers in data." }, { "code": null, "e": 8194, "s": 8180, "text": "Let’s try it." }, { "code": null, "e": 8546, "s": 8194, "text": "First select the first cell and click on the icon that looks like a ‘play’ button. This will execute the code in that cell. Nothing much will happen, although you should notice that the asterisk has changed to a number. (an asterisk denotes a cell which has not yet been executed). However, executing this cell has imported the libraries that we need." }, { "code": null, "e": 8645, "s": 8546, "text": "Now select the second cell and click the play icon. This time something much more exiting happens." }, { "code": null, "e": 8692, "s": 8645, "text": "You will see this image displayed in the cell." }, { "code": null, "e": 8804, "s": 8692, "text": "It’s is, of course, a simple line plot of the data which, as we would expect, results in a straight line graph." }, { "code": null, "e": 9115, "s": 8804, "text": "We’ve seen how to install Anaconda and Jupyter Notebooks, and how to create out first data visualization. There is, of course, much more to discover: how to import a data set and how to create different types of visualization, not just line graphs, but scatter diagrams, bar charts and pie charts, for example." }, { "code": null, "e": 9194, "s": 9115, "text": "You can see a article on plotting various graphs with Python and Pandas, here:" }, { "code": null, "e": 9217, "s": 9194, "text": "towardsdatascience.com" } ]
Get Size of the Pandas DataFrame - GeeksforGeeks
28 Nov, 2021 In this article, we will discuss how to get the size of the Pandas Dataframe using Python. This will return the size of dataframe i.e. rows*columns Syntax: dataframe.size where, dataframe is the input dataframe Example: Python code to create a student dataframe and display size Python3 # import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 3 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87]}) # display dataframeprint(data) # get the sizedata.size Output: This function will return the number of rows and columns in the dataframe Syntax: dataframe.shape where, dataframe is the input dataframe Example: Python program to get the shape of the dataframe Python3 # import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 3 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87]}) # display dataframeprint(data) # get the shapedata.shape Output: This will return the number of dimensions present in the dataframe. Syntax: data.ndim where, dataframe is the input dataframe Example: Python program to get the dimension of the dataframe Python3 # import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 3 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87]}) # display dataframeprint(data) # get the dimensionsdata.ndim Output: pandas-dataframe-program Picked 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n28 Nov, 2021" }, { "code": null, "e": 25646, "s": 25555, "text": "In this article, we will discuss how to get the size of the Pandas Dataframe using Python." }, { "code": null, "e": 25704, "s": 25646, "text": "This will return the size of dataframe i.e. rows*columns" }, { "code": null, "e": 25712, "s": 25704, "text": "Syntax:" }, { "code": null, "e": 25727, "s": 25712, "text": "dataframe.size" }, { "code": null, "e": 25767, "s": 25727, "text": "where, dataframe is the input dataframe" }, { "code": null, "e": 25835, "s": 25767, "text": "Example: Python code to create a student dataframe and display size" }, { "code": null, "e": 25843, "s": 25835, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 3 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87]}) # display dataframeprint(data) # get the sizedata.size", "e": 26169, "s": 25843, "text": null }, { "code": null, "e": 26177, "s": 26169, "text": "Output:" }, { "code": null, "e": 26251, "s": 26177, "text": "This function will return the number of rows and columns in the dataframe" }, { "code": null, "e": 26259, "s": 26251, "text": "Syntax:" }, { "code": null, "e": 26275, "s": 26259, "text": "dataframe.shape" }, { "code": null, "e": 26315, "s": 26275, "text": "where, dataframe is the input dataframe" }, { "code": null, "e": 26373, "s": 26315, "text": "Example: Python program to get the shape of the dataframe" }, { "code": null, "e": 26381, "s": 26373, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 3 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87]}) # display dataframeprint(data) # get the shapedata.shape", "e": 26709, "s": 26381, "text": null }, { "code": null, "e": 26717, "s": 26709, "text": "Output:" }, { "code": null, "e": 26785, "s": 26717, "text": "This will return the number of dimensions present in the dataframe." }, { "code": null, "e": 26793, "s": 26785, "text": "Syntax:" }, { "code": null, "e": 26803, "s": 26793, "text": "data.ndim" }, { "code": null, "e": 26843, "s": 26803, "text": "where, dataframe is the input dataframe" }, { "code": null, "e": 26905, "s": 26843, "text": "Example: Python program to get the dimension of the dataframe" }, { "code": null, "e": 26913, "s": 26905, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create a dataframe# with 5 rows and 3 columnsdata = pd.DataFrame({ 'name': ['sravan', 'ojsawi', 'bobby', 'rohith', 'gnanesh'], 'subjects': ['java', 'php', 'html/css', 'python', 'R'], 'marks': [98, 90, 78, 91, 87]}) # display dataframeprint(data) # get the dimensionsdata.ndim", "e": 27245, "s": 26913, "text": null }, { "code": null, "e": 27253, "s": 27245, "text": "Output:" }, { "code": null, "e": 27278, "s": 27253, "text": "pandas-dataframe-program" }, { "code": null, "e": 27285, "s": 27278, "text": "Picked" }, { "code": null, "e": 27309, "s": 27285, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27323, "s": 27309, "text": "Python-pandas" }, { "code": null, "e": 27330, "s": 27323, "text": "Python" }, { "code": null, "e": 27428, "s": 27330, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27460, "s": 27428, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27502, "s": 27460, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27544, "s": 27502, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27600, "s": 27544, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27627, "s": 27600, "text": "Python Classes and Objects" }, { "code": null, "e": 27658, "s": 27627, "text": "Python | os.path.join() method" }, { "code": null, "e": 27697, "s": 27658, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27726, "s": 27697, "text": "Create a directory in Python" }, { "code": null, "e": 27748, "s": 27726, "text": "Defaultdict in Python" } ]
C# Linq Distinct() Method
To get the distinct elements, use the Distinct() method. The following is our list with duplicate elements. List<int> points = new List<int> { 5, 10, 5, 20, 30, 30, 40, 50, 60, 70 }; Now to get the distinct elements − points.AsQueryable().Distinct(); Let us see the entire example − Live Demo using System; using System.Linq; using System.Collections.Generic; class Demo { static void Main() { List<int> points = new List<int> { 5, 10, 5, 20, 30, 30, 40, 50, 60, 70 }; // distict elements from the list IEnumerable<int> res = points.AsQueryable().Distinct(); foreach (int a in res) { Console.WriteLine(a); } } } 5 10 20 30 40 50 60 70
[ { "code": null, "e": 1119, "s": 1062, "text": "To get the distinct elements, use the Distinct() method." }, { "code": null, "e": 1170, "s": 1119, "text": "The following is our list with duplicate elements." }, { "code": null, "e": 1245, "s": 1170, "text": "List<int> points = new List<int> { 5, 10, 5, 20, 30, 30, 40, 50, 60, 70 };" }, { "code": null, "e": 1280, "s": 1245, "text": "Now to get the distinct elements −" }, { "code": null, "e": 1313, "s": 1280, "text": "points.AsQueryable().Distinct();" }, { "code": null, "e": 1345, "s": 1313, "text": "Let us see the entire example −" }, { "code": null, "e": 1356, "s": 1345, "text": " Live Demo" }, { "code": null, "e": 1720, "s": 1356, "text": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\nclass Demo {\n static void Main() {\n List<int> points = new List<int> { 5, 10, 5, 20, 30, 30, 40, 50, 60, 70 };\n // distict elements from the list\n IEnumerable<int> res = points.AsQueryable().Distinct();\n foreach (int a in res) {\n Console.WriteLine(a);\n }\n }\n}" }, { "code": null, "e": 1743, "s": 1720, "text": "5\n10\n20\n30\n40\n50\n60\n70" } ]
Java ceil() method with Examples
08 Apr, 2018 The java.lang.Math.ceil() returns the double value that is greater than or equal to the argument and is equal to the nearest mathematical integer.Note: If the argument is Integer, then the result is Integer. If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. If the argument value is less than zero but greater than -1.0, then the result is negative zero. Syntax : public static double ceil(double a)a : the argument whose ceil value is to be determinedReturns : This method returns the double value that is greater than or equalto the argument and is equal to the nearest mathematical integer. Example :To show working of java.lang.Math.ceil() method. // Java program to demonstrate working// of java.lang.Math.ceil() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 4.3; double b = 1.0 / 0; double c = 0.0; double d = -0.0; double e = -0.12; System.out.println(Math.ceil(a)); // Input Infinity, Output Infinity System.out.println(Math.ceil(b)); // Input Positive Zero, Output Positive Zero System.out.println(Math.ceil(c)); // Input Negative Zero, Output Negative Zero System.out.println(Math.ceil(d)); // Input less than zero but greater than -1.0 // Output Negative zero System.out.println(Math.ceil(e)); }} Output: 5.0 Infinity 0.0 -0.0 -0.0 Java-Library java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Stack Class in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Apr, 2018" }, { "code": null, "e": 204, "s": 52, "text": "The java.lang.Math.ceil() returns the double value that is greater than or equal to the argument and is equal to the nearest mathematical integer.Note:" }, { "code": null, "e": 260, "s": 204, "text": "If the argument is Integer, then the result is Integer." }, { "code": null, "e": 378, "s": 260, "text": "If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument." }, { "code": null, "e": 475, "s": 378, "text": "If the argument value is less than zero but greater than -1.0, then the result is negative zero." }, { "code": null, "e": 484, "s": 475, "text": "Syntax :" }, { "code": null, "e": 714, "s": 484, "text": "public static double ceil(double a)a : the argument whose ceil value is to be determinedReturns : This method returns the double value that is greater than or equalto the argument and is equal to the nearest mathematical integer." }, { "code": null, "e": 772, "s": 714, "text": "Example :To show working of java.lang.Math.ceil() method." }, { "code": "// Java program to demonstrate working// of java.lang.Math.ceil() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 4.3; double b = 1.0 / 0; double c = 0.0; double d = -0.0; double e = -0.12; System.out.println(Math.ceil(a)); // Input Infinity, Output Infinity System.out.println(Math.ceil(b)); // Input Positive Zero, Output Positive Zero System.out.println(Math.ceil(c)); // Input Negative Zero, Output Negative Zero System.out.println(Math.ceil(d)); // Input less than zero but greater than -1.0 // Output Negative zero System.out.println(Math.ceil(e)); }}", "e": 1521, "s": 772, "text": null }, { "code": null, "e": 1529, "s": 1521, "text": "Output:" }, { "code": null, "e": 1557, "s": 1529, "text": "5.0\nInfinity\n0.0\n-0.0\n-0.0\n" }, { "code": null, "e": 1570, "s": 1557, "text": "Java-Library" }, { "code": null, "e": 1580, "s": 1570, "text": "java-math" }, { "code": null, "e": 1585, "s": 1580, "text": "Java" }, { "code": null, "e": 1590, "s": 1585, "text": "Java" }, { "code": null, "e": 1688, "s": 1590, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1739, "s": 1688, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 1770, "s": 1739, "text": "How to iterate any Map in Java" }, { "code": null, "e": 1789, "s": 1770, "text": "Interfaces in Java" }, { "code": null, "e": 1819, "s": 1789, "text": "HashMap in Java with Examples" }, { "code": null, "e": 1837, "s": 1819, "text": "ArrayList in Java" }, { "code": null, "e": 1852, "s": 1837, "text": "Stream In Java" }, { "code": null, "e": 1872, "s": 1852, "text": "Collections in Java" }, { "code": null, "e": 1896, "s": 1872, "text": "Singleton Class in Java" }, { "code": null, "e": 1928, "s": 1896, "text": "Multidimensional Arrays in Java" } ]
C - Basic Datatypes
C - Programming HOME C - Basic Introduction C - Program Structure C - Reserved Keywords C - Basic Datatypes C - Variable Types C - Storage Classes C - Using Constants C - Operator Types C - Control Statements C - Input and Output C - Pointing to Data C - Using Functions C - Play with Strings C - Structured Datatypes C - Working with Files C - Bits Manipulation C - Pre-Processors C - Useful Concepts C - Built-in Functions C - Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location. The value of a variable can be changed any time. C has the following basic built-in datatypes. int int float float double double char char Please note that there is not a boolean data type. C does not have the traditional view about logical comparison, but thats another story. int is used to define integer numbers. { int Count; Count = 5; } float is used to define floating point numbers. { float Miles; Miles = 5.6; } double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes. { double Atoms; Atoms = 2500000; } char defines characters. { char Letter; Letter = 'x'; } The data types explained above have the following modifiers. short long signed unsigned The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules: short int <= int <= long int float <= double <= long double What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is: Type Bytes Range --------------------------------------------------------------------- short int 2 -32,768 -> +32,767 (32kb) unsigned short int 2 0 -> +65,535 (64Kb) unsigned int 4 0 -> +4,294,967,295 ( 4Gb) int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb) long int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb) signed char 1 -128 -> +127 unsigned char 1 0 -> +255 float 4 double 8 long double 12 These figures only apply to todays generation of PCs. Mainframes and midrange machines could use different figures, but would still comply with the rule above. You can find out how much storage is allocated to a data type by using the sizeof operator discussed in Operator Types Session. Here is an example to check size of memory taken by various datatypes. int main() { printf("sizeof(char) == %d\n", sizeof(char)); printf("sizeof(short) == %d\n", sizeof(short)); printf("sizeof(int) == %d\n", sizeof(int)); printf("sizeof(long) == %d\n", sizeof(long)); printf("sizeof(float) == %d\n", sizeof(float)); printf("sizeof(double) == %d\n", sizeof(double)); printf("sizeof(long double) == %d\n", sizeof(long double)); printf("sizeof(long long) == %d\n", sizeof(long long)); return 0; } A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whether: The value of a variable can be changed. The value of a variable must always be read from memory rather than from a register Standard C language recognizes the following two qualifiers: const volatile The const qualifier is used to tell C that the variable value can not change after initialisation. Now pi cannot be changed at a later time within the program. Another way to define constants is with the #define preprocessor which has the advantage that it does not use any storage The volatile qualifier declares a data type that can have its value changed in ways outside the control or detection of the compiler (such as a variable updated by the system clock or by another program). This prevents the compiler from optimizing code referring to the object by storing the object's value in a register and re-reading it from there, rather than from memory, where it may have changed. You will use this qualifier once you will become expert in "C". So for now just proceed. We have seen all baisc data types. In C language it is possible to make arrays whose elements are basic types. Thus we can make an array of 10 integers with the declaration. int x[10]; The square brackets mean subscripting; parentheses are used only for function references. Array indexes begin at zero, so the elements of x are: Thus Array are special type of variables which can be used to store multiple values of same data type. Those values are stored and accessed using subscript or index. Arrays occupy consecutive memory slots in the computer's memory. x[0], x[1], x[2], ..., x[9] If an array has n elements, the largest subscript is n-1. Multiple-dimension arrays are provided. The declaration and use look like: int name[10] [20]; n = name[i+j] [1] + name[k] [2]; Subscripts can be arbitrary integer expressions. Multi-dimension arrays are stored by row so the rightmost subscript varies fastest. In above example name has 10 rows and 20 columns. Same way, arrays can be defined for any data type. Text is usually kept as an array of characters. By convention in C, the last character in a character array should be a `\0' because most programs that manipulate character arrays expect it. For example, printf uses the `\0' to detect the end of a character array when printing it out with a `%s'. Here is a program which reads a line, stores it in a buffer, and prints its length (excluding the newline at the end). main( ) { int n, c; char line[100]; n = 0; while( (c=getchar( )) != '\n' ) { if( n < 100 ) line[n] = c; n++; } printf("length = %d\n", n); } As with other declarations, array declarations can include an optional initialization Scalar variables are initialized with a single value Arrays are initialized with a list of values The list is enclosed in curly braces int array [8] = {2, 4, 6, 8, 10, 12, 14, 16}; The number of initializers cannot be more than the number of elements in the array but it can be less in which case, the remaining elements are initialized to 0.if you like, the array size can be inferred from the number of initializers by leaving the square brackets empty so these are identical declarations: int array1 [8] = {2, 4, 6, 8, 10, 12, 14, 16}; int array2 [] = {2, 4, 6, 8, 10, 12, 14, 16}; An array of characters ie string can be initialized as follows: char string[10] = "Hello";
[ { "code": null, "e": 1609, "s": 1588, "text": "C - Programming HOME" }, { "code": null, "e": 1632, "s": 1609, "text": "C - Basic Introduction" }, { "code": null, "e": 1654, "s": 1632, "text": "C - Program Structure" }, { "code": null, "e": 1676, "s": 1654, "text": "C - Reserved Keywords" }, { "code": null, "e": 1696, "s": 1676, "text": "C - Basic Datatypes" }, { "code": null, "e": 1715, "s": 1696, "text": "C - Variable Types" }, { "code": null, "e": 1735, "s": 1715, "text": "C - Storage Classes" }, { "code": null, "e": 1755, "s": 1735, "text": "C - Using Constants" }, { "code": null, "e": 1774, "s": 1755, "text": "C - Operator Types" }, { "code": null, "e": 1797, "s": 1774, "text": "C - Control Statements" }, { "code": null, "e": 1818, "s": 1797, "text": "C - Input and Output" }, { "code": null, "e": 1839, "s": 1818, "text": "C - Pointing to Data" }, { "code": null, "e": 1859, "s": 1839, "text": "C - Using Functions" }, { "code": null, "e": 1881, "s": 1859, "text": "C - Play with Strings" }, { "code": null, "e": 1906, "s": 1881, "text": "C - Structured Datatypes" }, { "code": null, "e": 1929, "s": 1906, "text": "C - Working with Files" }, { "code": null, "e": 1951, "s": 1929, "text": "C - Bits Manipulation" }, { "code": null, "e": 1970, "s": 1951, "text": "C - Pre-Processors" }, { "code": null, "e": 1990, "s": 1970, "text": "C - Useful Concepts" }, { "code": null, "e": 2013, "s": 1990, "text": "C - Built-in Functions" }, { "code": null, "e": 2034, "s": 2013, "text": "C - Useful Resources" }, { "code": null, "e": 2052, "s": 2034, "text": "Computer Glossary" }, { "code": null, "e": 2063, "s": 2052, "text": "Who is Who" }, { "code": null, "e": 2098, "s": 2063, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2311, "s": 2098, "text": "C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location." }, { "code": null, "e": 2360, "s": 2311, "text": "The value of a variable can be changed any time." }, { "code": null, "e": 2406, "s": 2360, "text": "C has the following basic built-in datatypes." }, { "code": null, "e": 2410, "s": 2406, "text": "int" }, { "code": null, "e": 2414, "s": 2410, "text": "int" }, { "code": null, "e": 2420, "s": 2414, "text": "float" }, { "code": null, "e": 2426, "s": 2420, "text": "float" }, { "code": null, "e": 2433, "s": 2426, "text": "double" }, { "code": null, "e": 2440, "s": 2433, "text": "double" }, { "code": null, "e": 2445, "s": 2440, "text": "char" }, { "code": null, "e": 2450, "s": 2445, "text": "char" }, { "code": null, "e": 2589, "s": 2450, "text": "Please note that there is not a boolean data type. C does not have the traditional view about logical comparison, but thats another story." }, { "code": null, "e": 2629, "s": 2589, "text": "int is used to define integer numbers. " }, { "code": null, "e": 2680, "s": 2629, "text": " {\n int Count;\n Count = 5;\n }\n" }, { "code": null, "e": 2728, "s": 2680, "text": "float is used to define floating point numbers." }, { "code": null, "e": 2784, "s": 2728, "text": "\n {\n float Miles;\n Miles = 5.6;\n }\n" }, { "code": null, "e": 2920, "s": 2784, "text": "double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes." }, { "code": null, "e": 2981, "s": 2920, "text": "\n {\n double Atoms;\n Atoms = 2500000;\n }\n" }, { "code": null, "e": 3006, "s": 2981, "text": "char defines characters." }, { "code": null, "e": 3062, "s": 3006, "text": " {\n char Letter;\n Letter = 'x';\n }\n" }, { "code": null, "e": 3124, "s": 3062, "text": "The data types explained above have the following modifiers. " }, { "code": null, "e": 3130, "s": 3124, "text": "short" }, { "code": null, "e": 3135, "s": 3130, "text": "long" }, { "code": null, "e": 3142, "s": 3135, "text": "signed" }, { "code": null, "e": 3151, "s": 3142, "text": "unsigned" }, { "code": null, "e": 3306, "s": 3151, "text": "The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules:" }, { "code": null, "e": 3392, "s": 3306, "text": "\n short int <= int <= long int\n float <= double <= long double\n\n" }, { "code": null, "e": 3602, "s": 3392, "text": "\nWhat this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is: " }, { "code": null, "e": 3719, "s": 3602, "text": " Type Bytes Range\n---------------------------------------------------------------------\n" }, { "code": null, "e": 4244, "s": 3719, "text": " short int 2 -32,768 -> +32,767 (32kb)\n unsigned short int 2 0 -> +65,535 (64Kb)\n unsigned int 4 0 -> +4,294,967,295 ( 4Gb)\n int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb)\n long int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb)\n signed char 1 -128 -> +127\n unsigned char 1 0 -> +255\n float 4 \n double 8 \n long double 12 \n" }, { "code": null, "e": 4405, "s": 4244, "text": "\nThese figures only apply to todays generation of PCs. Mainframes and midrange machines could use different figures, but would still comply with the rule above." }, { "code": null, "e": 4533, "s": 4405, "text": "You can find out how much storage is allocated to a data type by using the sizeof operator discussed in Operator Types Session." }, { "code": null, "e": 4604, "s": 4533, "text": "Here is an example to check size of memory taken by various datatypes." }, { "code": null, "e": 5047, "s": 4604, "text": "int\nmain()\n{\n printf(\"sizeof(char) == %d\\n\", sizeof(char));\n printf(\"sizeof(short) == %d\\n\", sizeof(short));\n printf(\"sizeof(int) == %d\\n\", sizeof(int));\n printf(\"sizeof(long) == %d\\n\", sizeof(long));\n printf(\"sizeof(float) == %d\\n\", sizeof(float));\n printf(\"sizeof(double) == %d\\n\", sizeof(double));\n printf(\"sizeof(long double) == %d\\n\", sizeof(long double));\n printf(\"sizeof(long long) == %d\\n\", sizeof(long long));\n\n return 0;\n}\n" }, { "code": null, "e": 5164, "s": 5047, "text": "A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whether:" }, { "code": null, "e": 5204, "s": 5164, "text": "The value of a variable can be changed." }, { "code": null, "e": 5288, "s": 5204, "text": "The value of a variable must always be read from memory rather than from a register" }, { "code": null, "e": 5349, "s": 5288, "text": "Standard C language recognizes the following two qualifiers:" }, { "code": null, "e": 5355, "s": 5349, "text": "const" }, { "code": null, "e": 5364, "s": 5355, "text": "volatile" }, { "code": null, "e": 5463, "s": 5364, "text": "The const qualifier is used to tell C that the variable value can not change after initialisation." }, { "code": null, "e": 5524, "s": 5463, "text": "Now pi cannot be changed at a later time within the program." }, { "code": null, "e": 5647, "s": 5524, "text": "Another way to define constants is with the #define preprocessor which has the advantage that it does not use any storage " }, { "code": null, "e": 6139, "s": 5647, "text": "The volatile qualifier declares a data type that can have its value changed in ways outside the control or detection of the compiler (such as a variable updated by the system clock or by another program). This prevents the compiler from optimizing code referring to the object by storing the object's value in a register and re-reading it from there, rather than from memory, where it may have changed. You will use this qualifier once you will become expert in \"C\". So for now just proceed." }, { "code": null, "e": 6314, "s": 6139, "text": "We have seen all baisc data types. In C language it is possible to make arrays whose elements are basic types. Thus we can make an array of 10 integers with the declaration." }, { "code": null, "e": 6326, "s": 6314, "text": "int x[10];\n" }, { "code": null, "e": 6472, "s": 6326, "text": "The square brackets mean subscripting; parentheses are used only for function references. Array indexes begin at zero, so the elements of x are:" }, { "code": null, "e": 6638, "s": 6472, "text": "Thus Array are special type of variables which can be used to store multiple values of same data type. Those values are stored and accessed using subscript or index." }, { "code": null, "e": 6703, "s": 6638, "text": "Arrays occupy consecutive memory slots in the computer's memory." }, { "code": null, "e": 6732, "s": 6703, "text": "x[0], x[1], x[2], ..., x[9]\n" }, { "code": null, "e": 6790, "s": 6732, "text": "If an array has n elements, the largest subscript is n-1." }, { "code": null, "e": 6866, "s": 6790, "text": "Multiple-dimension arrays are provided. The declaration and use look like:" }, { "code": null, "e": 6931, "s": 6866, "text": " int name[10] [20];\n n = name[i+j] [1] + name[k] [2];\n" }, { "code": null, "e": 7116, "s": 6931, "text": "Subscripts can be arbitrary integer expressions. Multi-dimension arrays are stored by row so the rightmost subscript varies fastest. In above example name has 10 rows and 20 columns." }, { "code": null, "e": 7465, "s": 7116, "text": "Same way, arrays can be defined for any data type. Text is usually kept as an array of characters. By convention in C, the last character in a character array should be a `\\0' because most programs that manipulate character arrays expect it. For example, printf uses the `\\0' to detect the end of a character array when printing it out with a `%s'." }, { "code": null, "e": 7584, "s": 7465, "text": "Here is a program which reads a line, stores it in a buffer, and prints its length (excluding the newline at the end)." }, { "code": null, "e": 7907, "s": 7584, "text": " main( ) {\n int n, c;\n char line[100];\n n = 0;\n while( (c=getchar( )) != '\\n' ) {\n if( n < 100 )\n line[n] = c;\n n++;\n }\n printf(\"length = %d\\n\", n);\n }\n" }, { "code": null, "e": 7993, "s": 7907, "text": "As with other declarations, array declarations can include an optional initialization" }, { "code": null, "e": 8046, "s": 7993, "text": "Scalar variables are initialized with a single value" }, { "code": null, "e": 8091, "s": 8046, "text": "Arrays are initialized with a list of values" }, { "code": null, "e": 8128, "s": 8091, "text": "The list is enclosed in curly braces" }, { "code": null, "e": 8175, "s": 8128, "text": "int array [8] = {2, 4, 6, 8, 10, 12, 14, 16};\n" }, { "code": null, "e": 8486, "s": 8175, "text": "The number of initializers cannot be more than the number of elements in the array but it can be less in which case, the remaining elements are initialized to 0.if you like, the array size can be inferred from the number of initializers by leaving the square brackets empty so these are identical declarations:" }, { "code": null, "e": 8580, "s": 8486, "text": "int array1 [8] = {2, 4, 6, 8, 10, 12, 14, 16};\nint array2 [] = {2, 4, 6, 8, 10, 12, 14, 16};\n" }, { "code": null, "e": 8644, "s": 8580, "text": "An array of characters ie string can be initialized as follows:" } ]
ReactJS UI Ant Design DatePicker Component
01 Jun, 2021 Ant Design Library has this component pre-built, and it is very easy to integrate as well. DatePicker Component is used to select a date from a popup panel when the user clicks on the input box. We can use the following approach in ReactJS to use the Ant Design DatePicker Component. Common API: allowClear: It is used to indicate whether allow clearing text or not. autoFocus: It is used to get the focus when component mounted if this is set to true. bordered: It is used to indicate whether it has border style or not. className: It is used to pass the className of picker. dateRender: It is used as the custom rendering function for date cells. disabled: It is used to determine whether the DatePicker is disabled or not. disabledDate: It is used to specify the date that cannot be selected. dropdownClassName: It is used to customize the className of the popup calendar. getPopupContainer: It is used to set the container of the floating layer. inputReadOnly: It is used to set the read-only attribute of the input tag. locale: It is used for the localization configuration. mode: It is used to denote the picker panel mode. open: It is used to denote the open state of the picker. panelRender: It is used to customize panel render. picker: It is used to set picker type date. placeholder: It is used to denote the placeholder of date input. popupStyle: It is used to customize the style of the popup calendar. size: It is used to determine the size of the input box. style: It is used to customize the style of the input box. suffixIcon: It is used for the custom suffix icon. onOpenChange: It is a callback function that can be triggered when the popup calendar is popped up or closed. onPanelChange: It is a callback function that is triggered when picker panel mode is changed. DatePicker Props: defaultPickerValue: It is used to set the default picker date. defaultValue: If start time or end time is null or undefined, it is used to set the default date. disabledTime: It is used to specify the time that cannot be selected. format: It is used to set the date format. renderExtraFooter: It is used to render extra footer in the panel. showNow: It is used to indicate whether to show the ‘Now’ button on the panel when showTime is set. showTime: It is used to provide an additional time selection object. showTime.defaultValue: It is used to set the default time of the selected date. showToday: It is used to indicate whether to show the Today button. value: It is used to set a date. onChange: It is a callback function that is triggered when the selected time is changing. onOk: It is a callback function that is triggered when clicking the ok button. onPanelChange: It is a callback function that is triggered for panel changing. DatePicker[picker=year] Props: defaultPickerValue: It is used to set the default picker date. defaultValue: It is used to set the default date. format: It is used to set the date format. renderExtraFooter: It is used to render extra footer in the panel. value: It is used to set a date. onChange: It is a callback function that is triggered when the selected time is changing. DatePicker[picker=quarter] Props: defaultPickerValue: It is used to set the default picker date. defaultValue: It is used to set the default date. format: It is used to set the date format. renderExtraFooter: It is used to render extra footer in the panel. value: It is used to set a date. onChange: It is a callback function that is triggered when the selected time is changing. DatePicker[picker=month] Props: defaultPickerValue: It is used to set the default picker date. defaultValue: It is used to set the default date. format: It is used to set the date format. monthCellRender: It is used for the custom month cell content render method. renderExtraFooter: It is used to render extra footer in the panel. value: It is used to set a date. onChange: It is a callback function that is triggered when the selected time is changing. DatePicker[picker=week] Props: defaultPickerValue: It is used to set the default picker date. defaultValue: It is used to set the default date. format: It is used to set the date format. renderExtraFooter: It is used to render extra footer in the panel. value: It is used to set a date. onChange: It is a callback function that is triggered when the selected time is changing. Methods: blur(): This method is used to remove the focus. focus(): This method is used to get the focus. RangePicker Props: allowEmpty: It is used to allow start or end input leave empty. dateRender: It is used to customize the date cell. defaultPickerValue: It is used to set the default picker date. defaultValue: It is used to set the default date. disabled: It is used to indicate whether to disable start or end or not. disabledTime: It is used to specify the time that cannot be selected. format: It is used to set the date format. ranges: It is used for the preset ranges for quick selection. renderExtraFooter: It is used to render extra footer in the panel. separator: It is used to set separator between inputs. showTime: It is used to provide an additional time selection. showTime.defaultValue: It is used to set the default time of the selected date. value: It is used to set a date. onCalendarChange: It is a callback function that is triggered when the start time or the end time of the range is changing. onChange: It is a callback function that is triggered when the selected time is changing. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd Step 3: After creating the ReactJS application, Install the required module using the following command: npm install antd Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'import "antd/dist/antd.css";import { DatePicker } from 'antd'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design DatePicker Component</h4> <> <DatePicker onChange={(date) => console.log(date)} />, </> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://ant.design/components/date-picker/ ReactJS-Ant Design ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS Functional Components ReactJS setState() Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2021" }, { "code": null, "e": 312, "s": 28, "text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. DatePicker Component is used to select a date from a popup panel when the user clicks on the input box. We can use the following approach in ReactJS to use the Ant Design DatePicker Component." }, { "code": null, "e": 324, "s": 312, "text": "Common API:" }, { "code": null, "e": 395, "s": 324, "text": "allowClear: It is used to indicate whether allow clearing text or not." }, { "code": null, "e": 481, "s": 395, "text": "autoFocus: It is used to get the focus when component mounted if this is set to true." }, { "code": null, "e": 550, "s": 481, "text": "bordered: It is used to indicate whether it has border style or not." }, { "code": null, "e": 605, "s": 550, "text": "className: It is used to pass the className of picker." }, { "code": null, "e": 677, "s": 605, "text": "dateRender: It is used as the custom rendering function for date cells." }, { "code": null, "e": 754, "s": 677, "text": "disabled: It is used to determine whether the DatePicker is disabled or not." }, { "code": null, "e": 824, "s": 754, "text": "disabledDate: It is used to specify the date that cannot be selected." }, { "code": null, "e": 904, "s": 824, "text": "dropdownClassName: It is used to customize the className of the popup calendar." }, { "code": null, "e": 978, "s": 904, "text": "getPopupContainer: It is used to set the container of the floating layer." }, { "code": null, "e": 1053, "s": 978, "text": "inputReadOnly: It is used to set the read-only attribute of the input tag." }, { "code": null, "e": 1108, "s": 1053, "text": "locale: It is used for the localization configuration." }, { "code": null, "e": 1158, "s": 1108, "text": "mode: It is used to denote the picker panel mode." }, { "code": null, "e": 1215, "s": 1158, "text": "open: It is used to denote the open state of the picker." }, { "code": null, "e": 1266, "s": 1215, "text": "panelRender: It is used to customize panel render." }, { "code": null, "e": 1310, "s": 1266, "text": "picker: It is used to set picker type date." }, { "code": null, "e": 1375, "s": 1310, "text": "placeholder: It is used to denote the placeholder of date input." }, { "code": null, "e": 1444, "s": 1375, "text": "popupStyle: It is used to customize the style of the popup calendar." }, { "code": null, "e": 1501, "s": 1444, "text": "size: It is used to determine the size of the input box." }, { "code": null, "e": 1560, "s": 1501, "text": "style: It is used to customize the style of the input box." }, { "code": null, "e": 1611, "s": 1560, "text": "suffixIcon: It is used for the custom suffix icon." }, { "code": null, "e": 1721, "s": 1611, "text": "onOpenChange: It is a callback function that can be triggered when the popup calendar is popped up or closed." }, { "code": null, "e": 1815, "s": 1721, "text": "onPanelChange: It is a callback function that is triggered when picker panel mode is changed." }, { "code": null, "e": 1833, "s": 1815, "text": "DatePicker Props:" }, { "code": null, "e": 1896, "s": 1833, "text": "defaultPickerValue: It is used to set the default picker date." }, { "code": null, "e": 1994, "s": 1896, "text": "defaultValue: If start time or end time is null or undefined, it is used to set the default date." }, { "code": null, "e": 2064, "s": 1994, "text": "disabledTime: It is used to specify the time that cannot be selected." }, { "code": null, "e": 2107, "s": 2064, "text": "format: It is used to set the date format." }, { "code": null, "e": 2174, "s": 2107, "text": "renderExtraFooter: It is used to render extra footer in the panel." }, { "code": null, "e": 2274, "s": 2174, "text": "showNow: It is used to indicate whether to show the ‘Now’ button on the panel when showTime is set." }, { "code": null, "e": 2343, "s": 2274, "text": "showTime: It is used to provide an additional time selection object." }, { "code": null, "e": 2423, "s": 2343, "text": "showTime.defaultValue: It is used to set the default time of the selected date." }, { "code": null, "e": 2491, "s": 2423, "text": "showToday: It is used to indicate whether to show the Today button." }, { "code": null, "e": 2524, "s": 2491, "text": "value: It is used to set a date." }, { "code": null, "e": 2614, "s": 2524, "text": "onChange: It is a callback function that is triggered when the selected time is changing." }, { "code": null, "e": 2693, "s": 2614, "text": "onOk: It is a callback function that is triggered when clicking the ok button." }, { "code": null, "e": 2772, "s": 2693, "text": "onPanelChange: It is a callback function that is triggered for panel changing." }, { "code": null, "e": 2803, "s": 2772, "text": "DatePicker[picker=year] Props:" }, { "code": null, "e": 2866, "s": 2803, "text": "defaultPickerValue: It is used to set the default picker date." }, { "code": null, "e": 2916, "s": 2866, "text": "defaultValue: It is used to set the default date." }, { "code": null, "e": 2959, "s": 2916, "text": "format: It is used to set the date format." }, { "code": null, "e": 3026, "s": 2959, "text": "renderExtraFooter: It is used to render extra footer in the panel." }, { "code": null, "e": 3059, "s": 3026, "text": "value: It is used to set a date." }, { "code": null, "e": 3149, "s": 3059, "text": "onChange: It is a callback function that is triggered when the selected time is changing." }, { "code": null, "e": 3183, "s": 3149, "text": "DatePicker[picker=quarter] Props:" }, { "code": null, "e": 3246, "s": 3183, "text": "defaultPickerValue: It is used to set the default picker date." }, { "code": null, "e": 3296, "s": 3246, "text": "defaultValue: It is used to set the default date." }, { "code": null, "e": 3339, "s": 3296, "text": "format: It is used to set the date format." }, { "code": null, "e": 3406, "s": 3339, "text": "renderExtraFooter: It is used to render extra footer in the panel." }, { "code": null, "e": 3439, "s": 3406, "text": "value: It is used to set a date." }, { "code": null, "e": 3529, "s": 3439, "text": "onChange: It is a callback function that is triggered when the selected time is changing." }, { "code": null, "e": 3561, "s": 3529, "text": "DatePicker[picker=month] Props:" }, { "code": null, "e": 3624, "s": 3561, "text": "defaultPickerValue: It is used to set the default picker date." }, { "code": null, "e": 3674, "s": 3624, "text": "defaultValue: It is used to set the default date." }, { "code": null, "e": 3717, "s": 3674, "text": "format: It is used to set the date format." }, { "code": null, "e": 3794, "s": 3717, "text": "monthCellRender: It is used for the custom month cell content render method." }, { "code": null, "e": 3861, "s": 3794, "text": "renderExtraFooter: It is used to render extra footer in the panel." }, { "code": null, "e": 3894, "s": 3861, "text": "value: It is used to set a date." }, { "code": null, "e": 3984, "s": 3894, "text": "onChange: It is a callback function that is triggered when the selected time is changing." }, { "code": null, "e": 4015, "s": 3984, "text": "DatePicker[picker=week] Props:" }, { "code": null, "e": 4078, "s": 4015, "text": "defaultPickerValue: It is used to set the default picker date." }, { "code": null, "e": 4128, "s": 4078, "text": "defaultValue: It is used to set the default date." }, { "code": null, "e": 4171, "s": 4128, "text": "format: It is used to set the date format." }, { "code": null, "e": 4238, "s": 4171, "text": "renderExtraFooter: It is used to render extra footer in the panel." }, { "code": null, "e": 4271, "s": 4238, "text": "value: It is used to set a date." }, { "code": null, "e": 4361, "s": 4271, "text": "onChange: It is a callback function that is triggered when the selected time is changing." }, { "code": null, "e": 4370, "s": 4361, "text": "Methods:" }, { "code": null, "e": 4419, "s": 4370, "text": "blur(): This method is used to remove the focus." }, { "code": null, "e": 4466, "s": 4419, "text": "focus(): This method is used to get the focus." }, { "code": null, "e": 4485, "s": 4466, "text": "RangePicker Props:" }, { "code": null, "e": 4549, "s": 4485, "text": "allowEmpty: It is used to allow start or end input leave empty." }, { "code": null, "e": 4600, "s": 4549, "text": "dateRender: It is used to customize the date cell." }, { "code": null, "e": 4663, "s": 4600, "text": "defaultPickerValue: It is used to set the default picker date." }, { "code": null, "e": 4713, "s": 4663, "text": "defaultValue: It is used to set the default date." }, { "code": null, "e": 4786, "s": 4713, "text": "disabled: It is used to indicate whether to disable start or end or not." }, { "code": null, "e": 4856, "s": 4786, "text": "disabledTime: It is used to specify the time that cannot be selected." }, { "code": null, "e": 4899, "s": 4856, "text": "format: It is used to set the date format." }, { "code": null, "e": 4961, "s": 4899, "text": "ranges: It is used for the preset ranges for quick selection." }, { "code": null, "e": 5028, "s": 4961, "text": "renderExtraFooter: It is used to render extra footer in the panel." }, { "code": null, "e": 5083, "s": 5028, "text": "separator: It is used to set separator between inputs." }, { "code": null, "e": 5145, "s": 5083, "text": "showTime: It is used to provide an additional time selection." }, { "code": null, "e": 5225, "s": 5145, "text": "showTime.defaultValue: It is used to set the default time of the selected date." }, { "code": null, "e": 5258, "s": 5225, "text": "value: It is used to set a date." }, { "code": null, "e": 5382, "s": 5258, "text": "onCalendarChange: It is a callback function that is triggered when the start time or the end time of the range is changing." }, { "code": null, "e": 5472, "s": 5382, "text": "onChange: It is a callback function that is triggered when the selected time is changing." }, { "code": null, "e": 5522, "s": 5472, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 5617, "s": 5522, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 5681, "s": 5617, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 5713, "s": 5681, "text": "npx create-react-app foldername" }, { "code": null, "e": 5826, "s": 5713, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 5926, "s": 5826, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 5940, "s": 5926, "text": "cd foldername" }, { "code": null, "e": 6061, "s": 5940, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd" }, { "code": null, "e": 6166, "s": 6061, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 6183, "s": 6166, "text": "npm install antd" }, { "code": null, "e": 6235, "s": 6183, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 6253, "s": 6235, "text": "Project Structure" }, { "code": null, "e": 6383, "s": 6253, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 6390, "s": 6383, "text": "App.js" }, { "code": "import React from 'react'import \"antd/dist/antd.css\";import { DatePicker } from 'antd'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design DatePicker Component</h4> <> <DatePicker onChange={(date) => console.log(date)} />, </> </div> );}", "e": 6742, "s": 6390, "text": null }, { "code": null, "e": 6855, "s": 6742, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 6865, "s": 6855, "text": "npm start" }, { "code": null, "e": 6964, "s": 6865, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 7018, "s": 6964, "text": "Reference: https://ant.design/components/date-picker/" }, { "code": null, "e": 7037, "s": 7018, "text": "ReactJS-Ant Design" }, { "code": null, "e": 7045, "s": 7037, "text": "ReactJS" }, { "code": null, "e": 7062, "s": 7045, "text": "Web Technologies" }, { "code": null, "e": 7160, "s": 7062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7203, "s": 7160, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 7248, "s": 7203, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 7286, "s": 7248, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 7316, "s": 7286, "text": "ReactJS Functional Components" }, { "code": null, "e": 7335, "s": 7316, "text": "ReactJS setState()" }, { "code": null, "e": 7397, "s": 7335, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7430, "s": 7397, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7491, "s": 7430, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7541, "s": 7491, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Output of Java Programs | Set 12
11 Nov, 2021 1) What is the output of the following program? public class Test implements Runnable{ public void run() { System.out.printf("%d",3); } public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Test()); thread.start(); System.out.printf("%d",1); thread.join(); System.out.printf("%d",2); } } a) 123b) 213c) 132d) 321 Ans: (c) Explanation: The parent thread waits for the newly created thread to complete using join. join() method allows one thread to wait until another thread completes its execution. So, parent thread prints 1 and wait for the child thread to complete. The child thread prints 3 on console and finally the parent thread prints 2. 2) What is the output of the following program? public class Test{ private static int value = 20; public int s = 15; public static int temp = 10; public static class Nested { private void display() { System.out.println(temp + s + value); } } public static void main(String args[]) { Test.Nested inner = new Test.Nested(); inner.display(); } } a) Compilation errorb) 1020c) 101520d) None of the above Ans: (a) Explanation: A non-static variable can not be accessed in static nested inner class. “Nested” cannot access non-static variables[variable s in this case]. Therefore the error: 10: error: non-static variable s cannot be referenced from a static context System.out.println(temp + s + value); ^ 3) What is the output of the following program? import java.io.*;public class Test{ public void display() throws IOException { System.out.println("Test"); } } class Derived extends Test{ public void display() throws IOException { System.out.println("Derived"); } public static void main(String[] args) throws IOException { Derived object = new Derived(); object.display(); }} a) Testb) Derivedc) Compilation errord) Runtime error Ans: (b) Explanation: If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. 4) What is the output of the following program? public class Test extends Thread{ public void run() { System.out.printf("Test "); } public static void main(String[] args) { Test test = new Test(); test.run(); test.start(); }} a) Compilation errorb) Runtime errorc) Testd) Test Test Ans: (d) Explanation: test.run() executes the run method. test.start() creates a new thread and executes the overridden run method of the Thread class. The Thread.start() method always starts a new thread, and the entry point for this thread is the run() method. If you are calling run() directly it will execute in the same thread BUT it is always recommendable logically calling Thread.start() to start a new thread of execution followed by the run() method. 5) What is the output of the following program? public class Test extends Thread{ public static void main(String[] args) { String a = "GeeksforGeeks"; String b = new String(a); int value = 0; value = (a==b) ? 1:2; if(value == 1) { System.out.println("GeeksforGeeks"); } else if(value == 2) { System.out.println("Geeks for Geeks"); } else { System.out.println("GFG"); } }} a) GeeksforGeeksb) Geeks for Geeksc) GFGd) None of the above Ans: (b) Explanation: == operator checks if two variable refer to the same object. Here a and brefers to two different objects. ?: is another form of if else statement that could be read as, condition : if true then do this : else do this. 6) What is the output of the following program? public class Test{ try { public Test() { System.out.println("GeeksforGeeks"); throw new Exception(); } } catch(Exception e) { System.out.println("GFG"); } public static void main(String[] args) { Test test = new Test(); }} a) GeeksforGeeksb) GFGc) Compilation errord) None of the above Ans: (c) Explanation: Constructors cannot be enclosed in try/catch block. 7) For the given code select the correct answer. public interface Test{ public int calculate(); protected interface NestedInterface { public void nested(); }} a) Compile time error due to NestedInterfaceb) Compile time error due to access modifier of NestedInterfacec) No Compile time errord) NestedInterface cannot hold any function declaration. Ans: (b) Explanation: Access modifier of NestedInterface can only be public. Therefore the error: 4: error: illegal combination of modifiers: public and protected protected interface NestedInterface ^ 1 error 8) Which of the following are true about constructor declaration?a) Constructors can be declared final.b) Constructors can be surrounded by try/catch blocks.c) Constructor cannot throw exception.d) Constructors can hold synchronized code(so that each thread can access constructor sequentially). Ans: (d) Explanation: Constructors allows a sequential access of data between threads. This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. chhabradhanvi Java-Output Java Program Output Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Collections in Java Stream In Java Singleton Class in Java Arrow operator -> in C/C++ with Examples Output of Java Program | Set 1 Output of C Programs | Set 1 delete keyword in C++ Output of C++ programs | Set 50
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Nov, 2021" }, { "code": null, "e": 102, "s": 54, "text": "1) What is the output of the following program?" }, { "code": "public class Test implements Runnable{ public void run() { System.out.printf(\"%d\",3); } public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Test()); thread.start(); System.out.printf(\"%d\",1); thread.join(); System.out.printf(\"%d\",2); } }", "e": 449, "s": 102, "text": null }, { "code": null, "e": 474, "s": 449, "text": "a) 123b) 213c) 132d) 321" }, { "code": null, "e": 483, "s": 474, "text": "Ans: (c)" }, { "code": null, "e": 806, "s": 483, "text": "Explanation: The parent thread waits for the newly created thread to complete using join. join() method allows one thread to wait until another thread completes its execution. So, parent thread prints 1 and wait for the child thread to complete. The child thread prints 3 on console and finally the parent thread prints 2." }, { "code": null, "e": 854, "s": 806, "text": "2) What is the output of the following program?" }, { "code": "public class Test{ private static int value = 20; public int s = 15; public static int temp = 10; public static class Nested { private void display() { System.out.println(temp + s + value); } } public static void main(String args[]) { Test.Nested inner = new Test.Nested(); inner.display(); } }", "e": 1231, "s": 854, "text": null }, { "code": null, "e": 1288, "s": 1231, "text": "a) Compilation errorb) 1020c) 101520d) None of the above" }, { "code": null, "e": 1297, "s": 1288, "text": "Ans: (a)" }, { "code": null, "e": 1473, "s": 1297, "text": "Explanation: A non-static variable can not be accessed in static nested inner class. “Nested” cannot access non-static variables[variable s in this case]. Therefore the error:" }, { "code": null, "e": 1639, "s": 1473, "text": "10: error: non-static variable s cannot be referenced from a static context\n System.out.println(temp + s + value);\n ^" }, { "code": null, "e": 1687, "s": 1639, "text": "3) What is the output of the following program?" }, { "code": "import java.io.*;public class Test{ public void display() throws IOException { System.out.println(\"Test\"); } } class Derived extends Test{ public void display() throws IOException { System.out.println(\"Derived\"); } public static void main(String[] args) throws IOException { Derived object = new Derived(); object.display(); }}", "e": 2072, "s": 1687, "text": null }, { "code": null, "e": 2126, "s": 2072, "text": "a) Testb) Derivedc) Compilation errord) Runtime error" }, { "code": null, "e": 2135, "s": 2126, "text": "Ans: (b)" }, { "code": null, "e": 2313, "s": 2135, "text": "Explanation: If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception." }, { "code": null, "e": 2361, "s": 2313, "text": "4) What is the output of the following program?" }, { "code": "public class Test extends Thread{ public void run() { System.out.printf(\"Test \"); } public static void main(String[] args) { Test test = new Test(); test.run(); test.start(); }}", "e": 2585, "s": 2361, "text": null }, { "code": null, "e": 2641, "s": 2585, "text": "a) Compilation errorb) Runtime errorc) Testd) Test Test" }, { "code": null, "e": 2650, "s": 2641, "text": "Ans: (d)" }, { "code": null, "e": 3102, "s": 2650, "text": "Explanation: test.run() executes the run method. test.start() creates a new thread and executes the overridden run method of the Thread class. The Thread.start() method always starts a new thread, and the entry point for this thread is the run() method. If you are calling run() directly it will execute in the same thread BUT it is always recommendable logically calling Thread.start() to start a new thread of execution followed by the run() method." }, { "code": null, "e": 3150, "s": 3102, "text": "5) What is the output of the following program?" }, { "code": "public class Test extends Thread{ public static void main(String[] args) { String a = \"GeeksforGeeks\"; String b = new String(a); int value = 0; value = (a==b) ? 1:2; if(value == 1) { System.out.println(\"GeeksforGeeks\"); } else if(value == 2) { System.out.println(\"Geeks for Geeks\"); } else { System.out.println(\"GFG\"); } }}", "e": 3617, "s": 3150, "text": null }, { "code": null, "e": 3678, "s": 3617, "text": "a) GeeksforGeeksb) Geeks for Geeksc) GFGd) None of the above" }, { "code": null, "e": 3688, "s": 3678, "text": "Ans: (b) " }, { "code": null, "e": 3919, "s": 3688, "text": "Explanation: == operator checks if two variable refer to the same object. Here a and brefers to two different objects. ?: is another form of if else statement that could be read as, condition : if true then do this : else do this." }, { "code": null, "e": 3967, "s": 3919, "text": "6) What is the output of the following program?" }, { "code": "public class Test{ try { public Test() { System.out.println(\"GeeksforGeeks\"); throw new Exception(); } } catch(Exception e) { System.out.println(\"GFG\"); } public static void main(String[] args) { Test test = new Test(); }}", "e": 4274, "s": 3967, "text": null }, { "code": null, "e": 4337, "s": 4274, "text": "a) GeeksforGeeksb) GFGc) Compilation errord) None of the above" }, { "code": null, "e": 4346, "s": 4337, "text": "Ans: (c)" }, { "code": null, "e": 4411, "s": 4346, "text": "Explanation: Constructors cannot be enclosed in try/catch block." }, { "code": null, "e": 4460, "s": 4411, "text": "7) For the given code select the correct answer." }, { "code": "public interface Test{ public int calculate(); protected interface NestedInterface { public void nested(); }}", "e": 4589, "s": 4460, "text": null }, { "code": null, "e": 4777, "s": 4589, "text": "a) Compile time error due to NestedInterfaceb) Compile time error due to access modifier of NestedInterfacec) No Compile time errord) NestedInterface cannot hold any function declaration." }, { "code": null, "e": 4786, "s": 4777, "text": "Ans: (b)" }, { "code": null, "e": 4875, "s": 4786, "text": "Explanation: Access modifier of NestedInterface can only be public. Therefore the error:" }, { "code": null, "e": 5004, "s": 4875, "text": "4: error: illegal combination of modifiers: public and protected\n protected interface NestedInterface\n ^\n1 error" }, { "code": null, "e": 5300, "s": 5004, "text": "8) Which of the following are true about constructor declaration?a) Constructors can be declared final.b) Constructors can be surrounded by try/catch blocks.c) Constructor cannot throw exception.d) Constructors can hold synchronized code(so that each thread can access constructor sequentially)." }, { "code": null, "e": 5309, "s": 5300, "text": "Ans: (d)" }, { "code": null, "e": 5387, "s": 5309, "text": "Explanation: Constructors allows a sequential access of data between threads." }, { "code": null, "e": 5683, "s": 5387, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5808, "s": 5683, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5822, "s": 5808, "text": "chhabradhanvi" }, { "code": null, "e": 5834, "s": 5822, "text": "Java-Output" }, { "code": null, "e": 5839, "s": 5834, "text": "Java" }, { "code": null, "e": 5854, "s": 5839, "text": "Program Output" }, { "code": null, "e": 5859, "s": 5854, "text": "Java" }, { "code": null, "e": 5957, "s": 5859, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5976, "s": 5957, "text": "Interfaces in Java" }, { "code": null, "e": 5994, "s": 5976, "text": "ArrayList in Java" }, { "code": null, "e": 6014, "s": 5994, "text": "Collections in Java" }, { "code": null, "e": 6029, "s": 6014, "text": "Stream In Java" }, { "code": null, "e": 6053, "s": 6029, "text": "Singleton Class in Java" }, { "code": null, "e": 6094, "s": 6053, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 6125, "s": 6094, "text": "Output of Java Program | Set 1" }, { "code": null, "e": 6154, "s": 6125, "text": "Output of C Programs | Set 1" }, { "code": null, "e": 6176, "s": 6154, "text": "delete keyword in C++" } ]
Getter and Setter Methods in Dart
31 Oct, 2021 Getter and setter methods are the class methods used to manipulate the data of the class fields. Getter is used to read or get the data of the class field whereas setter is used to set the data of the class field to some variable. It is used to retrieve a particular class field and save it in a variable. All classes have a default getter method but it can be overridden explicitly. The getter method can be defined using the get keyword as: return_type get field_name{ ... } It must be noted we have to define a return type but there is no need to define parameters in the above method. It is used to set the data inside a variable received from the getter method. All classes have a default setter method but it can be overridden explicitly. The setter method can be defined using the set keyword as: set field_name{ ... } Example: Using the Getter and Setter method in the dart program. Dart // Creating Class named Gfgclass Gfg { // Creating a Field/Property String geekName; // Creating the getter method // to get input from Field/Property String get getName { return geekName; } // Creating the setter method // to set the input in Field/Property set setName(String name) { geekName = name; }} void main() { // Creating Instance of class Gfg geek = Gfg(); // Calling the set_name method(setter method we created) // To set the value in Property "geekName" geek.setName = "GeeksForGeeks"; // Calling the get_name method(getter method we created) // To get the value from Property "geekName" print("Welcome to ${geek.getName}");} Output: Welcome to GeeksForGeeks prateeksrivastav7374 Dart-OOPs Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget ListView Class in Flutter Flutter - Stack Widget Dart Tutorial How to Append or Concatenate Strings in Dart? Flutter - Search Bar Operators in Dart Flutter - FutureBuilder Widget
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2021" }, { "code": null, "e": 259, "s": 28, "text": "Getter and setter methods are the class methods used to manipulate the data of the class fields. Getter is used to read or get the data of the class field whereas setter is used to set the data of the class field to some variable." }, { "code": null, "e": 471, "s": 259, "text": "It is used to retrieve a particular class field and save it in a variable. All classes have a default getter method but it can be overridden explicitly. The getter method can be defined using the get keyword as:" }, { "code": null, "e": 509, "s": 471, "text": "return_type get field_name{\n ...\n}" }, { "code": null, "e": 621, "s": 509, "text": "It must be noted we have to define a return type but there is no need to define parameters in the above method." }, { "code": null, "e": 836, "s": 621, "text": "It is used to set the data inside a variable received from the getter method. All classes have a default setter method but it can be overridden explicitly. The setter method can be defined using the set keyword as:" }, { "code": null, "e": 862, "s": 836, "text": "set field_name{\n ...\n}" }, { "code": null, "e": 927, "s": 862, "text": "Example: Using the Getter and Setter method in the dart program." }, { "code": null, "e": 932, "s": 927, "text": "Dart" }, { "code": "// Creating Class named Gfgclass Gfg { // Creating a Field/Property String geekName; // Creating the getter method // to get input from Field/Property String get getName { return geekName; } // Creating the setter method // to set the input in Field/Property set setName(String name) { geekName = name; }} void main() { // Creating Instance of class Gfg geek = Gfg(); // Calling the set_name method(setter method we created) // To set the value in Property \"geekName\" geek.setName = \"GeeksForGeeks\"; // Calling the get_name method(getter method we created) // To get the value from Property \"geekName\" print(\"Welcome to ${geek.getName}\");}", "e": 1600, "s": 932, "text": null }, { "code": null, "e": 1608, "s": 1600, "text": "Output:" }, { "code": null, "e": 1633, "s": 1608, "text": "Welcome to GeeksForGeeks" }, { "code": null, "e": 1654, "s": 1633, "text": "prateeksrivastav7374" }, { "code": null, "e": 1664, "s": 1654, "text": "Dart-OOPs" }, { "code": null, "e": 1669, "s": 1664, "text": "Dart" }, { "code": null, "e": 1767, "s": 1669, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1799, "s": 1767, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 1838, "s": 1799, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 1864, "s": 1838, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 1890, "s": 1864, "text": "ListView Class in Flutter" }, { "code": null, "e": 1913, "s": 1890, "text": "Flutter - Stack Widget" }, { "code": null, "e": 1927, "s": 1913, "text": "Dart Tutorial" }, { "code": null, "e": 1973, "s": 1927, "text": "How to Append or Concatenate Strings in Dart?" }, { "code": null, "e": 1994, "s": 1973, "text": "Flutter - Search Bar" }, { "code": null, "e": 2012, "s": 1994, "text": "Operators in Dart" } ]
Python MySQL - Create Table
The CREATE TABLE statement is used to create tables in MYSQL database. Here, you need to specify the name of the table and, definition (name and datatype) of each column. Following is the syntax to create a table in MySQL − CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype, ..... columnN datatype, ); Following query creates a table named EMPLOYEE in MySQL with five columns namely, FIRST_NAME, LAST_NAME, AGE, SEX and, INCOME. mysql> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT); Query OK, 0 rows affected (0.42 sec) The DESC statement gives you the description of the specified table. Using this you can verify if the table has been created or not as shown below − mysql> Desc Employee; +------------+----------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+----------+------+-----+---------+-------+ | FIRST_NAME | char(20) | NO | | NULL | | | LAST_NAME | char(20) | YES | | NULL | | | AGE | int(11) | YES | | NULL | | | SEX | char(1) | YES | | NULL | | | INCOME | float | YES | | NULL | | +------------+----------+------+-----+---------+-------+ 5 rows in set (0.07 sec) The method named execute() (invoked on the cursor object) accepts two variables− A String value representing the query to be executed. A String value representing the query to be executed. An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders). An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders). It returns an integer value representing the number of rows effected by the query. Once a database connection is established, you can create tables by passing the CREATE TABLE query to the execute() method. In short, to create a table using python − Import mysql.connector package. Import mysql.connector package. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Create a cursor object by invoking the cursor() method on the connection object created above. Create a cursor object by invoking the cursor() method on the connection object created above. Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method. Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method. Following example creates a table named Employee in the database mydb. import mysql.connector #establishing the connection conn = mysql.connector.connect( user='root', password='password', host='127.0.0.1', database='mydb' ) #Creating a cursor object using the cursor() method cursor = conn.cursor() #Dropping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") #Creating table as per requirement sql ='''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) #Closing the connection
[ { "code": null, "e": 2524, "s": 2353, "text": "The CREATE TABLE statement is used to create tables in MYSQL database. Here, you need to specify the name of the table and, definition (name and datatype) of each column." }, { "code": null, "e": 2577, "s": 2524, "text": "Following is the syntax to create a table in MySQL −" }, { "code": null, "e": 2699, "s": 2577, "text": "CREATE TABLE table_name(\n column1 datatype,\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype,\n);\n" }, { "code": null, "e": 2826, "s": 2699, "text": "Following query creates a table named EMPLOYEE in MySQL with five columns namely, FIRST_NAME, LAST_NAME, AGE, SEX and, INCOME." }, { "code": null, "e": 2995, "s": 2826, "text": "mysql> CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT);\nQuery OK, 0 rows affected (0.42 sec)" }, { "code": null, "e": 3144, "s": 2995, "text": "The DESC statement gives you the description of the specified table. Using this you can verify if the table has been created or not as shown below −" }, { "code": null, "e": 3707, "s": 3144, "text": "mysql> Desc Employee;\n+------------+----------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+------------+----------+------+-----+---------+-------+\n| FIRST_NAME | char(20) | NO | | NULL | |\n| LAST_NAME | char(20) | YES | | NULL | |\n| AGE | int(11) | YES | | NULL | |\n| SEX | char(1) | YES | | NULL | | \n| INCOME | float | YES | | NULL | |\n+------------+----------+------+-----+---------+-------+\n5 rows in set (0.07 sec)\n" }, { "code": null, "e": 3788, "s": 3707, "text": "The method named execute() (invoked on the cursor object) accepts two variables−" }, { "code": null, "e": 3842, "s": 3788, "text": "A String value representing the query to be executed." }, { "code": null, "e": 3896, "s": 3842, "text": "A String value representing the query to be executed." }, { "code": null, "e": 4041, "s": 3896, "text": "An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders)." }, { "code": null, "e": 4186, "s": 4041, "text": "An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the query (values of the place holders)." }, { "code": null, "e": 4269, "s": 4186, "text": "It returns an integer value representing the number of rows effected by the query." }, { "code": null, "e": 4393, "s": 4269, "text": "Once a database connection is established, you can create tables by passing the CREATE TABLE query to the execute() method." }, { "code": null, "e": 4436, "s": 4393, "text": "In short, to create a table using python −" }, { "code": null, "e": 4468, "s": 4436, "text": "Import mysql.connector package." }, { "code": null, "e": 4500, "s": 4468, "text": "Import mysql.connector package." }, { "code": null, "e": 4688, "s": 4500, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 4876, "s": 4688, "text": "Create a connection object using the mysql.connector.connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it." }, { "code": null, "e": 4971, "s": 4876, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 5066, "s": 4971, "text": "Create a cursor object by invoking the cursor() method on the connection object created above." }, { "code": null, "e": 5161, "s": 5066, "text": "Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 5256, "s": 5161, "text": "Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method." }, { "code": null, "e": 5327, "s": 5256, "text": "Following example creates a table named Employee in the database mydb." } ]
Difference between SortedList and SortedDictionary in C#
01 May, 2019 In C#, SortedList is a collection of key/value pairs which are sorted according to keys. By default, this collection sort the key/value pairs in ascending order. It is of both generic and non-generic type of collection. The generic SortedList is defined in System.Collections.Generic namespace whereas non-generic SortedList is defined under System.Collections namespace. Example: // C# program to illustrate how// to create a sortedlistusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Creating a sortedlist // Using SortedList class SortedList my_Slist = new SortedList(); // Adding key/value pairs in // SortedList using Add() method my_Slist.Add(1.02, "Dog"); my_Slist.Add(1.07, "Cat"); my_Slist.Add(1.04, "Rat"); my_Slist.Add(1.01, "Bird"); foreach(DictionaryEntry pair in my_Slist) { Console.WriteLine("{0} and {1}", pair.Key, pair.Value); } Console.WriteLine(); }} 1.01 and Bird 1.02 and Dog 1.04 and Rat 1.07 and Cat In C#, SortedDictionary is a generic collection which is used to store the key/value pairs in the sorted form and the sorting is done on the key. SortedDictionary is defined under System.Collection.Generic namespace. It is dynamic in nature means the size of the sorted dictionary is growing according to the need. Example: // C# program to illustrate how// to create a sorted dictionaryusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating sorted dictionary // Using SortedDictionary class SortedDictionary<int, string> My_sdict = new SortedDictionary<int, string>(); // Adding key/value pair in Sorted // Dictionary Using Add() method My_sdict.Add(004, "Roscosmos"); My_sdict.Add(003, "ESA"); My_sdict.Add(001, "NASA"); My_sdict.Add(005, "ISRO"); My_sdict.Add(002, "CNSA"); Console.WriteLine("Top 5 space agencies 2018:"); // Accessing the key/value pair of the // SortedDictionary Using foreach loop foreach(KeyValuePair<int, string> pair in My_sdict) { Console.WriteLine("Rank: {0} and Name: {1}", pair.Key, pair.Value); } }} Top 5 space agencies 2018: Rank: 1 and Name: NASA Rank: 2 and Name: CNSA Rank: 3 and Name: ESA Rank: 4 and Name: Roscosmos Rank: 5 and Name: ISRO Below are the some differences between SortedList and SortedDictionary: CSharp SortedDictionary Class CSharp-Collections-SortedList C# Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Data Types Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 28, "s": 0, "text": "\n01 May, 2019" }, { "code": null, "e": 400, "s": 28, "text": "In C#, SortedList is a collection of key/value pairs which are sorted according to keys. By default, this collection sort the key/value pairs in ascending order. It is of both generic and non-generic type of collection. The generic SortedList is defined in System.Collections.Generic namespace whereas non-generic SortedList is defined under System.Collections namespace." }, { "code": null, "e": 409, "s": 400, "text": "Example:" }, { "code": "// C# program to illustrate how// to create a sortedlistusing System;using System.Collections; class GFG { // Main Method static public void Main() { // Creating a sortedlist // Using SortedList class SortedList my_Slist = new SortedList(); // Adding key/value pairs in // SortedList using Add() method my_Slist.Add(1.02, \"Dog\"); my_Slist.Add(1.07, \"Cat\"); my_Slist.Add(1.04, \"Rat\"); my_Slist.Add(1.01, \"Bird\"); foreach(DictionaryEntry pair in my_Slist) { Console.WriteLine(\"{0} and {1}\", pair.Key, pair.Value); } Console.WriteLine(); }}", "e": 1091, "s": 409, "text": null }, { "code": null, "e": 1145, "s": 1091, "text": "1.01 and Bird\n1.02 and Dog\n1.04 and Rat\n1.07 and Cat\n" }, { "code": null, "e": 1460, "s": 1145, "text": "In C#, SortedDictionary is a generic collection which is used to store the key/value pairs in the sorted form and the sorting is done on the key. SortedDictionary is defined under System.Collection.Generic namespace. It is dynamic in nature means the size of the sorted dictionary is growing according to the need." }, { "code": null, "e": 1469, "s": 1460, "text": "Example:" }, { "code": "// C# program to illustrate how// to create a sorted dictionaryusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating sorted dictionary // Using SortedDictionary class SortedDictionary<int, string> My_sdict = new SortedDictionary<int, string>(); // Adding key/value pair in Sorted // Dictionary Using Add() method My_sdict.Add(004, \"Roscosmos\"); My_sdict.Add(003, \"ESA\"); My_sdict.Add(001, \"NASA\"); My_sdict.Add(005, \"ISRO\"); My_sdict.Add(002, \"CNSA\"); Console.WriteLine(\"Top 5 space agencies 2018:\"); // Accessing the key/value pair of the // SortedDictionary Using foreach loop foreach(KeyValuePair<int, string> pair in My_sdict) { Console.WriteLine(\"Rank: {0} and Name: {1}\", pair.Key, pair.Value); } }}", "e": 2424, "s": 1469, "text": null }, { "code": null, "e": 2571, "s": 2424, "text": "Top 5 space agencies 2018:\nRank: 1 and Name: NASA\nRank: 2 and Name: CNSA\nRank: 3 and Name: ESA\nRank: 4 and Name: Roscosmos\nRank: 5 and Name: ISRO\n" }, { "code": null, "e": 2643, "s": 2571, "text": "Below are the some differences between SortedList and SortedDictionary:" }, { "code": null, "e": 2673, "s": 2643, "text": "CSharp SortedDictionary Class" }, { "code": null, "e": 2703, "s": 2673, "text": "CSharp-Collections-SortedList" }, { "code": null, "e": 2706, "s": 2703, "text": "C#" }, { "code": null, "e": 2725, "s": 2706, "text": "Difference Between" }, { "code": null, "e": 2823, "s": 2725, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2854, "s": 2823, "text": "Introduction to .NET Framework" }, { "code": null, "e": 2869, "s": 2854, "text": "C# | Delegates" }, { "code": null, "e": 2912, "s": 2869, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2961, "s": 2912, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 2977, "s": 2961, "text": "C# | Data Types" }, { "code": null, "e": 3017, "s": 2977, "text": "Class method vs Static method in Python" }, { "code": null, "e": 3048, "s": 3017, "text": "Difference between BFS and DFS" }, { "code": null, "e": 3109, "s": 3048, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3177, "s": 3109, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
Python-Quizzes | Python Dictionary Quiz | Question 25
17 Sep, 2020 Question 25:Find the output of the following program: counter = {} def addToCounter(country): if country in counter: counter[country] += 1 else: counter[country] = 1 addToCounter('China') addToCounter('Japan') addToCounter('china') print (len(counter)) (A) 0(B) 1(C) 2(D) 3Answer: (D)Explanation: The task of “len” function is to return the number of keys in a dictionary. Here 3 keys are added to the dictionary “country” using the “addToCounter” function. The keys to a dictionary are case sensitive.Quiz of this Question Python-Quizzes Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Why do people prefer Selenium with Python? Python-Quizzes | Python List Quiz | Question 3 Python-Quizzes | Output Type | Question 10 Python-Quizzes | Miscellaneous | Question 10 Python-Quizzes | Output Type | Question 12 Python-Quizzes | Data Type | Question 3 Python | Animated Banner showing 'GeeksForGeeks' Python | Word Stretch Python-Quizzes | Python List Quiz | Question 1 Python-Quizzes | Python List Quiz | Question 2
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Sep, 2020" }, { "code": null, "e": 107, "s": 53, "text": "Question 25:Find the output of the following program:" }, { "code": "counter = {} def addToCounter(country): if country in counter: counter[country] += 1 else: counter[country] = 1 addToCounter('China') addToCounter('Japan') addToCounter('china') print (len(counter))", "e": 334, "s": 107, "text": null }, { "code": null, "e": 605, "s": 334, "text": "(A) 0(B) 1(C) 2(D) 3Answer: (D)Explanation: The task of “len” function is to return the number of keys in a dictionary. Here 3 keys are added to the dictionary “country” using the “addToCounter” function. The keys to a dictionary are case sensitive.Quiz of this Question" }, { "code": null, "e": 620, "s": 605, "text": "Python-Quizzes" }, { "code": null, "e": 718, "s": 620, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 761, "s": 718, "text": "Why do people prefer Selenium with Python?" }, { "code": null, "e": 808, "s": 761, "text": "Python-Quizzes | Python List Quiz | Question 3" }, { "code": null, "e": 851, "s": 808, "text": "Python-Quizzes | Output Type | Question 10" }, { "code": null, "e": 896, "s": 851, "text": "Python-Quizzes | Miscellaneous | Question 10" }, { "code": null, "e": 939, "s": 896, "text": "Python-Quizzes | Output Type | Question 12" }, { "code": null, "e": 979, "s": 939, "text": "Python-Quizzes | Data Type | Question 3" }, { "code": null, "e": 1028, "s": 979, "text": "Python | Animated Banner showing 'GeeksForGeeks'" }, { "code": null, "e": 1050, "s": 1028, "text": "Python | Word Stretch" }, { "code": null, "e": 1097, "s": 1050, "text": "Python-Quizzes | Python List Quiz | Question 1" } ]
How to Set Precision For Double Values in Java?
04 Jul, 2022 Significant digits are referred to all digits inclusive of left and right to decimal place keeping a note adding 0 to left of any number is not countable as significant digits whereas precise digits referred to digits that are only lying on the right side or in short after the decimal place in mathematics. In Java, there are numbers more than 16 numbers only to the precision but can go more. Here we are given a double value, the task is to set its precision value to specific decimal places. It is illustrated below illustrations as follows: Illustrations: Input : val = 1 Output : 1.0000 Upto 4 decimal places Input : 12.5 Output : 12.500000 Upto 6 decimal places Using format() Method of String classUsing round() method of Math class Using format() Method of String class Using round() method of Math class We can use format() method of String class to format the decimal number to some specific format. Syntax: String.format("%.Df", decimalValue); // Where D is the number required number of Decimal places Example-1: Java // Java Program to Illustrate format() Method// of String class // Importing required classesimport java.io.*;import java.lang.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing // double value double a = 0.9; // Setting the precision // to 20 places System.out.println( String.format("%.20f", a)); double b = 1; // Setting the precision // to 5 places System.out.println( String.format("%.5f", b)); }} 0.90000000000000000000 1.00000 From the above output, it is clear that precision of 20 digits is been carried out for the first entry whereas precision to 5 digits is carried out on input double value. Example-2: Java // Demonstrating the precision modifier import java.util.*; class GFG { public static void main (String[] args) { Formatter fm=new Formatter(); // Format 4 decimal places fm.format("%.4f", 123.1234567); System.out.println(fm); fm.close(); //Format 2 decimal places in a 16 charcater field fm=new Formatter(); fm.format("%16.2e",123.1234567); System.out.println("GFG!"); fm.close(); //Display atmost 15 characters in a string fm=new Formatter(); fm.format("%.15s", "Learning with Gfg is easy quick"); System.out.println(fm); fm.close(); }} 123.1235 GFG! Learning with G Example: Java // Java Program to Illustrate Precision Setting In Double// Using round() Method of Math Class // Importing required classesimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing double variable double num = 3.141414141414; // Rounding off above double number // to 7 precision double ans = Math.round(num * 10000000) / 10000000.0; // Printing the above precised value // of double value System.out.println(ans); }} 3.1414141 The above double number is precise to 7 digits which can easily be seen from the output generated. snape_here solankimayank singhankitasingh066 Java-Data Types Java-Double Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2022" }, { "code": null, "e": 598, "s": 52, "text": "Significant digits are referred to all digits inclusive of left and right to decimal place keeping a note adding 0 to left of any number is not countable as significant digits whereas precise digits referred to digits that are only lying on the right side or in short after the decimal place in mathematics. In Java, there are numbers more than 16 numbers only to the precision but can go more. Here we are given a double value, the task is to set its precision value to specific decimal places. It is illustrated below illustrations as follows:" }, { "code": null, "e": 614, "s": 598, "text": "Illustrations: " }, { "code": null, "e": 670, "s": 614, "text": "Input : val = 1 \nOutput : 1.0000\nUpto 4 decimal places" }, { "code": null, "e": 725, "s": 670, "text": "Input : 12.5\nOutput : 12.500000\nUpto 6 decimal places" }, { "code": null, "e": 797, "s": 725, "text": "Using format() Method of String classUsing round() method of Math class" }, { "code": null, "e": 835, "s": 797, "text": "Using format() Method of String class" }, { "code": null, "e": 870, "s": 835, "text": "Using round() method of Math class" }, { "code": null, "e": 967, "s": 870, "text": "We can use format() method of String class to format the decimal number to some specific format." }, { "code": null, "e": 975, "s": 967, "text": "Syntax:" }, { "code": null, "e": 1071, "s": 975, "text": "String.format(\"%.Df\", decimalValue);\n// Where D is the number required number of Decimal places" }, { "code": null, "e": 1082, "s": 1071, "text": "Example-1:" }, { "code": null, "e": 1087, "s": 1082, "text": "Java" }, { "code": "// Java Program to Illustrate format() Method// of String class // Importing required classesimport java.io.*;import java.lang.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing // double value double a = 0.9; // Setting the precision // to 20 places System.out.println( String.format(\"%.20f\", a)); double b = 1; // Setting the precision // to 5 places System.out.println( String.format(\"%.5f\", b)); }}", "e": 1607, "s": 1087, "text": null }, { "code": null, "e": 1638, "s": 1607, "text": "0.90000000000000000000\n1.00000" }, { "code": null, "e": 1810, "s": 1638, "text": "From the above output, it is clear that precision of 20 digits is been carried out for the first entry whereas precision to 5 digits is carried out on input double value. " }, { "code": null, "e": 1821, "s": 1810, "text": "Example-2:" }, { "code": null, "e": 1826, "s": 1821, "text": "Java" }, { "code": "// Demonstrating the precision modifier import java.util.*; class GFG { public static void main (String[] args) { Formatter fm=new Formatter(); // Format 4 decimal places fm.format(\"%.4f\", 123.1234567); System.out.println(fm); fm.close(); //Format 2 decimal places in a 16 charcater field fm=new Formatter(); fm.format(\"%16.2e\",123.1234567); System.out.println(\"GFG!\"); fm.close(); //Display atmost 15 characters in a string fm=new Formatter(); fm.format(\"%.15s\", \"Learning with Gfg is easy quick\"); System.out.println(fm); fm.close(); }}", "e": 2467, "s": 1826, "text": null }, { "code": null, "e": 2497, "s": 2467, "text": "123.1235\nGFG!\nLearning with G" }, { "code": null, "e": 2506, "s": 2497, "text": "Example:" }, { "code": null, "e": 2511, "s": 2506, "text": "Java" }, { "code": "// Java Program to Illustrate Precision Setting In Double// Using round() Method of Math Class // Importing required classesimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing double variable double num = 3.141414141414; // Rounding off above double number // to 7 precision double ans = Math.round(num * 10000000) / 10000000.0; // Printing the above precised value // of double value System.out.println(ans); }}", "e": 3087, "s": 2511, "text": null }, { "code": null, "e": 3097, "s": 3087, "text": "3.1414141" }, { "code": null, "e": 3197, "s": 3097, "text": "The above double number is precise to 7 digits which can easily be seen from the output generated. " }, { "code": null, "e": 3208, "s": 3197, "text": "snape_here" }, { "code": null, "e": 3222, "s": 3208, "text": "solankimayank" }, { "code": null, "e": 3242, "s": 3222, "text": "singhankitasingh066" }, { "code": null, "e": 3258, "s": 3242, "text": "Java-Data Types" }, { "code": null, "e": 3270, "s": 3258, "text": "Java-Double" }, { "code": null, "e": 3283, "s": 3270, "text": "Java-Strings" }, { "code": null, "e": 3288, "s": 3283, "text": "Java" }, { "code": null, "e": 3301, "s": 3288, "text": "Java-Strings" }, { "code": null, "e": 3306, "s": 3301, "text": "Java" }, { "code": null, "e": 3404, "s": 3306, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3455, "s": 3404, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3486, "s": 3455, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3505, "s": 3486, "text": "Interfaces in Java" }, { "code": null, "e": 3535, "s": 3505, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3550, "s": 3535, "text": "Stream In Java" }, { "code": null, "e": 3568, "s": 3550, "text": "ArrayList in Java" }, { "code": null, "e": 3588, "s": 3568, "text": "Collections in Java" }, { "code": null, "e": 3612, "s": 3588, "text": "Singleton Class in Java" }, { "code": null, "e": 3644, "s": 3612, "text": "Multidimensional Arrays in Java" } ]
Numpy | Indexing - GeeksforGeeks
15 Nov, 2018 NumPy or Numeric Python is a package for computation on homogenous n-dimensional arrays. In numpy dimensions are called as axes. Why do we need NumPy ? A question arises that why do we need NumPy when python lists are already there. The answer to it is we cannot perform operations on all the elements of two list directly. For example, we cannot multiply two lists directly we will have to do it element-wise. This is where the role of NumPy comes into play. Example #1: Output : TypeError: can't multiply sequence by non-int of type 'list' Where as this can easily be done with NumPy arrays. Example #2: Output : array([10, 18, 24, 28, 30, 30]) Numpy package of python has a great power of indexing in different ways. Indexing using index arrays Indexing can be done in numpy by using an array as an index. In case of slice, a view or shallow copy of the array is returned but in index array a copy of the original array is returned. Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples. The last element is indexed by -1 second last by -2 and so on. Example #1: Output : A sequential array with a negative step: [10 8 6 4 2] Elements at these indices are: [4 8 6] Example #2: Output : Elements are: [2 4 7] There are two types of indexing : Basic Slicing and indexing : Consider the syntax x[obj] where x is the array and obj is the index. Slice object is the index in case of basic slicing. Basic slicing occurs when obj is : a slice object that is of the form start : stop : step an integer or a tuple of slice objects and integers All arrays generated by basic slicing are always view of the original array. Code #1: Output : Array is: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] a[-8:17:1] = [12 13 14 15 16] a[10:] = [10 11 12 13 14 15 16 17 18 19] Code #2: Output : Array is: [[0 1 2 3 4 5] [6 7 8 9 10 11] [12 13 14 15 16 17] [18 19 20 21 22 23] [24 25 26 27 28 29] [30 31 32 33 34 35]] a[0, 3:5] = [3 4] a[4:, 4:] = [[28 29], [34 35]] a[:, 2] = [2 8 14 20 26 32] a[2:;2, ::2] = [[12 14 16], [24 26 28]] The figure below makes the concept more clear: Ellipsis can also be used along with basic slicing. Ellipsis (...) is the number of : objects needed to make a selection tuple of the same length as the dimensions of the array. Output : [[ 2 5] [ 8 11]] Advanced indexing : Advanced indexing is triggered when obj is – an ndarray of type integer or Boolean or a tuple with at least one sequence object is a non tuple sequence object Advanced indexing returns a copy of data rather than a view of it. Advanced indexing is of two types integer and Boolean. Purely integer indexing : When integers are used for indexing. Each element of first dimension is paired with the element of the second dimension. So the index of the elements in this case are (0,0),(1,0),(2,1) and the corresponding elements are selected. Output : [1 3 6] Combining advanced and basic indexing: When there is at least one slice (:), ellipsis (...) or newaxis in the index (or the array has more dimensions than there are advanced indexes), then the behavior can be more complicated. It is like concatenating the indexing result for each advanced index element In the simplest case, there is only a single advanced index. A single advanced index can, for example, replace a slice and the result array will be the same, however, it is a copy and may have a different memory layout. A slice is preferable when it is possible. Output : [4, 5] [4, 5] The easiest way to understand the situation may be to think in terms of the result shape. There are two parts to the indexing operation, the subspace defined by the basic indexing (excluding integers) and the subspace from the advanced indexing part. Two cases of index combination need to be distinguished: The advanced indexes are separated by a slice, Ellipsis or newaxis. For example x[arr1, :, arr2].The advanced indexes are all next to each other. For example x[..., arr1, arr2, :] but not x[arr1, :, 1] since 1 is an advanced index in this regard.In the first case, the dimensions resulting from the advanced indexing operation come first in the result array, and the subspace dimensions after that. In the second case, the dimensions from the advanced indexing operations are inserted into the result array at the same spot as they were in the initial array (the latter logic is what makes simple advanced indexing behave just like slicing). Boolean Array Indexing:This indexing has some boolean expression as the index. Those elements are returned which satisfy that Boolean expression. It is used for filtering the desired element values.Code #1 Output : [80 100] Code #2 Output : [1600 6400]) Code #3 Output : array([[ 5, 5], [16, 4]]) Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Learn C++ Programming Step by Step - A 20 Day Curriculum! Must Do Coding Questions for Product Based Companies 50 Common Ports You Should Know GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? How to Find Length of String in Bash Script? Samsung R&D Internship Interview Experience (On-Campus) Generate UUID in Golang How to install PHP in windows 10 ? Types of Distributed System
[ { "code": null, "e": 43445, "s": 43417, "text": "\n15 Nov, 2018" }, { "code": null, "e": 43574, "s": 43445, "text": "NumPy or Numeric Python is a package for computation on homogenous n-dimensional arrays. In numpy dimensions are called as axes." }, { "code": null, "e": 43597, "s": 43574, "text": "Why do we need NumPy ?" }, { "code": null, "e": 43905, "s": 43597, "text": "A question arises that why do we need NumPy when python lists are already there. The answer to it is we cannot perform operations on all the elements of two list directly. For example, we cannot multiply two lists directly we will have to do it element-wise. This is where the role of NumPy comes into play." }, { "code": null, "e": 43917, "s": 43905, "text": "Example #1:" }, { "code": null, "e": 43926, "s": 43917, "text": "Output :" }, { "code": null, "e": 43988, "s": 43926, "text": "TypeError: can't multiply sequence by non-int of type 'list'\n" }, { "code": null, "e": 44040, "s": 43988, "text": "Where as this can easily be done with NumPy arrays." }, { "code": null, "e": 44052, "s": 44040, "text": "Example #2:" }, { "code": null, "e": 44061, "s": 44052, "text": "Output :" }, { "code": null, "e": 44093, "s": 44061, "text": "array([10, 18, 24, 28, 30, 30])" }, { "code": null, "e": 44166, "s": 44093, "text": "Numpy package of python has a great power of indexing in different ways." }, { "code": null, "e": 44194, "s": 44166, "text": "Indexing using index arrays" }, { "code": null, "e": 44543, "s": 44194, "text": "Indexing can be done in numpy by using an array as an index. In case of slice, a view or shallow copy of the array is returned but in index array a copy of the original array is returned. Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples. The last element is indexed by -1 second last by -2 and so on." }, { "code": null, "e": 44555, "s": 44543, "text": "Example #1:" }, { "code": null, "e": 44564, "s": 44555, "text": "Output :" }, { "code": null, "e": 44663, "s": 44564, "text": "A sequential array with a negative step:\n[10 8 6 4 2]\n\nElements at these indices are:\n[4 8 6]\n" }, { "code": null, "e": 44676, "s": 44663, "text": " Example #2:" }, { "code": null, "e": 44685, "s": 44676, "text": "Output :" }, { "code": null, "e": 44708, "s": 44685, "text": "Elements are:\n[2 4 7]\n" }, { "code": null, "e": 44744, "s": 44710, "text": "There are two types of indexing :" }, { "code": null, "e": 44930, "s": 44744, "text": "Basic Slicing and indexing : Consider the syntax x[obj] where x is the array and obj is the index. Slice object is the index in case of basic slicing. Basic slicing occurs when obj is :" }, { "code": null, "e": 44985, "s": 44930, "text": "a slice object that is of the form start : stop : step" }, { "code": null, "e": 44996, "s": 44985, "text": "an integer" }, { "code": null, "e": 45037, "s": 44996, "text": "or a tuple of slice objects and integers" }, { "code": null, "e": 45114, "s": 45037, "text": "All arrays generated by basic slicing are always view of the original array." }, { "code": null, "e": 45123, "s": 45114, "text": "Code #1:" }, { "code": null, "e": 45132, "s": 45123, "text": "Output :" }, { "code": null, "e": 45281, "s": 45132, "text": "Array is:\n[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]\n\na[-8:17:1] = [12 13 14 15 16]\n\na[10:] = [10 11 12 13 14 15 16 17 18 19] \n" }, { "code": null, "e": 45291, "s": 45281, "text": " Code #2:" }, { "code": null, "e": 45300, "s": 45291, "text": "Output :" }, { "code": null, "e": 45593, "s": 45300, "text": "Array is:\n [[0 1 2 3 4 5] \n [6 7 8 9 10 11]\n [12 13 14 15 16 17]\n [18 19 20 21 22 23]\n [24 25 26 27 28 29]\n [30 31 32 33 34 35]]\n\na[0, 3:5] = [3 4]\n\na[4:, 4:] = [[28 29],\n [34 35]]\n\na[:, 2] = [2 8 14 20 26 32]\n\na[2:;2, ::2] = [[12 14 16],\n [24 26 28]]\n" }, { "code": null, "e": 45640, "s": 45593, "text": "The figure below makes the concept more clear:" }, { "code": null, "e": 45818, "s": 45640, "text": "Ellipsis can also be used along with basic slicing. Ellipsis (...) is the number of : objects needed to make a selection tuple of the same length as the dimensions of the array." }, { "code": null, "e": 45827, "s": 45818, "text": "Output :" }, { "code": null, "e": 45847, "s": 45827, "text": "[[ 2 5]\n [ 8 11]]\n" }, { "code": null, "e": 45913, "s": 45847, "text": " Advanced indexing : Advanced indexing is triggered when obj is –" }, { "code": null, "e": 45951, "s": 45913, "text": "an ndarray of type integer or Boolean" }, { "code": null, "e": 45996, "s": 45951, "text": "or a tuple with at least one sequence object" }, { "code": null, "e": 46027, "s": 45996, "text": "is a non tuple sequence object" }, { "code": null, "e": 46149, "s": 46027, "text": "Advanced indexing returns a copy of data rather than a view of it. Advanced indexing is of two types integer and Boolean." }, { "code": null, "e": 46405, "s": 46149, "text": "Purely integer indexing : When integers are used for indexing. Each element of first dimension is paired with the element of the second dimension. So the index of the elements in this case are (0,0),(1,0),(2,1) and the corresponding elements are selected." }, { "code": null, "e": 46414, "s": 46405, "text": "Output :" }, { "code": null, "e": 46423, "s": 46414, "text": "[1 3 6]\n" }, { "code": null, "e": 46727, "s": 46423, "text": "Combining advanced and basic indexing: When there is at least one slice (:), ellipsis (...) or newaxis in the index (or the array has more dimensions than there are advanced indexes), then the behavior can be more complicated. It is like concatenating the indexing result for each advanced index element" }, { "code": null, "e": 46990, "s": 46727, "text": "In the simplest case, there is only a single advanced index. A single advanced index can, for example, replace a slice and the result array will be the same, however, it is a copy and may have a different memory layout. A slice is preferable when it is possible." }, { "code": null, "e": 46999, "s": 46990, "text": "Output :" }, { "code": null, "e": 47014, "s": 46999, "text": "[4, 5]\n[4, 5]\n" }, { "code": null, "e": 47322, "s": 47014, "text": "The easiest way to understand the situation may be to think in terms of the result shape. There are two parts to the indexing operation, the subspace defined by the basic indexing (excluding integers) and the subspace from the advanced indexing part. Two cases of index combination need to be distinguished:" }, { "code": null, "e": 48170, "s": 47322, "text": "The advanced indexes are separated by a slice, Ellipsis or newaxis. For example x[arr1, :, arr2].The advanced indexes are all next to each other. For example x[..., arr1, arr2, :] but not x[arr1, :, 1] since 1 is an advanced index in this regard.In the first case, the dimensions resulting from the advanced indexing operation come first in the result array, and the subspace dimensions after that. In the second case, the dimensions from the advanced indexing operations are inserted into the result array at the same spot as they were in the initial array (the latter logic is what makes simple advanced indexing behave just like slicing). Boolean Array Indexing:This indexing has some boolean expression as the index. Those elements are returned which satisfy that Boolean expression. It is used for filtering the desired element values.Code #1" }, { "code": null, "e": 48179, "s": 48170, "text": "Output :" }, { "code": null, "e": 48189, "s": 48179, "text": "[80 100]\n" }, { "code": null, "e": 48197, "s": 48189, "text": "Code #2" }, { "code": null, "e": 48206, "s": 48197, "text": "Output :" }, { "code": null, "e": 48220, "s": 48206, "text": "[1600 6400])\n" }, { "code": null, "e": 48228, "s": 48220, "text": "Code #3" }, { "code": null, "e": 48237, "s": 48228, "text": "Output :" }, { "code": null, "e": 48264, "s": 48237, "text": "array([[ 5, 5], [16, 4]])\n" }, { "code": null, "e": 48362, "s": 48264, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 48436, "s": 48362, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 48494, "s": 48436, "text": "Learn C++ Programming Step by Step - A 20 Day Curriculum!" }, { "code": null, "e": 48547, "s": 48494, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 48579, "s": 48547, "text": "50 Common Ports You Should Know" }, { "code": null, "e": 48645, "s": 48579, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 48690, "s": 48645, "text": "How to Find Length of String in Bash Script?" }, { "code": null, "e": 48746, "s": 48690, "text": "Samsung R&D Internship Interview Experience (On-Campus)" }, { "code": null, "e": 48770, "s": 48746, "text": "Generate UUID in Golang" }, { "code": null, "e": 48805, "s": 48770, "text": "How to install PHP in windows 10 ?" } ]
ImageField – Django Models
12 Feb, 2020 ImageField is a FileField with uploads restricted to image formats only. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. The default form widget for this field is a ClearableFileInput. In addition to the special attributes that are available for FileField, an ImageField also has height and width attributes.ImageField requires the Pillow library. To install the same run, pip install Pillow Syntax field_name = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options) ImageField has following optional arguments: ImageField.upload_to This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method. If you specify a string value, it may contain strftime() formatting, which will be replaced by the date/time of the file upload (so that uploaded files don’t fill up the given directory). For example: class MyModel(models.Model): # file will be uploaded to MEDIA_ROOT / uploads upload = models.ImageField(upload_to ='uploads/') # or... # file will be saved to MEDIA_ROOT / uploads / 2015 / 01 / 30 upload = models.ImageField(upload_to ='uploads/% Y/% m/% d/') If you are using the default FileSystemStorage, the string value will be appended to your MEDIA_ROOT path to form the location on the local filesystem where uploaded files will be stored. If you are using different storage, check that storage’s documentation to see how it handles upload_to. upload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments are: For example: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT / user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.ImageField(upload_to = user_directory_path) ImageField.height_field Name of a model field which will be auto-populated with the height of the image each time the model instance is saved. ImageField.width_field Name of a model field which will be auto-populated with the width of the image each time the model instance is saved. Illustration of ImageField 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.ImageField() 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.ImageField()), ], ), ] Now run, Python manage.py migrate Thus, an geeks_field ImageField is created when you run migrations on the project. It is a field to store valid image files. ImageField is used for storing valid image files into the database. One can any type of image file in ImageField. Let’s try storing an image in the model created above. To start creating instances of model, create an admin account by using the following command.Python manage.py createsuperuser Python manage.py createsuperuser Enter a username, email and a secure password. Then in your browser enter the following URL.http://localhost:8000/admin/ http://localhost:8000/admin/ Go to add in front of Geeks Models. Choose the file you want to upload and click on 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 ImageField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an ImageField 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 Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Feb, 2020" }, { "code": null, "e": 516, "s": 52, "text": "ImageField is a FileField with uploads restricted to image formats only. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. The default form widget for this field is a ClearableFileInput. In addition to the special attributes that are available for FileField, an ImageField also has height and width attributes.ImageField requires the Pillow library. To install the same run," }, { "code": null, "e": 537, "s": 516, "text": " pip install Pillow " }, { "code": null, "e": 544, "s": 537, "text": "Syntax" }, { "code": null, "e": 655, "s": 544, "text": "field_name = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)" }, { "code": null, "e": 700, "s": 655, "text": "ImageField has following optional arguments:" }, { "code": null, "e": 721, "s": 700, "text": "ImageField.upload_to" }, { "code": null, "e": 1092, "s": 721, "text": "This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method. If you specify a string value, it may contain strftime() formatting, which will be replaced by the date/time of the file upload (so that uploaded files don’t fill up the given directory). For example:" }, { "code": "class MyModel(models.Model): # file will be uploaded to MEDIA_ROOT / uploads upload = models.ImageField(upload_to ='uploads/') # or... # file will be saved to MEDIA_ROOT / uploads / 2015 / 01 / 30 upload = models.ImageField(upload_to ='uploads/% Y/% m/% d/')", "e": 1370, "s": 1092, "text": null }, { "code": null, "e": 1662, "s": 1370, "text": "If you are using the default FileSystemStorage, the string value will be appended to your MEDIA_ROOT path to form the location on the local filesystem where uploaded files will be stored. If you are using different storage, check that storage’s documentation to see how it handles upload_to." }, { "code": null, "e": 1944, "s": 1662, "text": "upload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments are:" }, { "code": null, "e": 1957, "s": 1944, "text": "For example:" }, { "code": "def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT / user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.ImageField(upload_to = user_directory_path)", "e": 2221, "s": 1957, "text": null }, { "code": null, "e": 2245, "s": 2221, "text": "ImageField.height_field" }, { "code": null, "e": 2364, "s": 2245, "text": "Name of a model field which will be auto-populated with the height of the image each time the model instance is saved." }, { "code": null, "e": 2387, "s": 2364, "text": "ImageField.width_field" }, { "code": null, "e": 2505, "s": 2387, "text": "Name of a model field which will be auto-populated with the width of the image each time the model instance is saved." }, { "code": null, "e": 2616, "s": 2505, "text": "Illustration of ImageField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 2703, "s": 2616, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 2754, "s": 2703, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 2787, "s": 2754, "text": "How to Create an App in Django ?" }, { "code": null, "e": 2846, "s": 2787, "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.ImageField()", "e": 2998, "s": 2846, "text": null }, { "code": null, "e": 3034, "s": 2998, "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": 3272, "s": 3034, "text": null }, { "code": null, "e": 3330, "s": 3272, "text": "Now when we run makemigrations command from the terminal," }, { "code": null, "e": 3362, "s": 3330, "text": "Python manage.py makemigrations" }, { "code": null, "e": 3462, "s": 3362, "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.ImageField()), ], ), ]", "e": 4049, "s": 3462, "text": null }, { "code": null, "e": 4058, "s": 4049, "text": "Now run," }, { "code": null, "e": 4083, "s": 4058, "text": "Python manage.py migrate" }, { "code": null, "e": 4208, "s": 4083, "text": "Thus, an geeks_field ImageField is created when you run migrations on the project. It is a field to store valid image files." }, { "code": null, "e": 4377, "s": 4208, "text": "ImageField is used for storing valid image files into the database. One can any type of image file in ImageField. Let’s try storing an image in the model created above." }, { "code": null, "e": 4503, "s": 4377, "text": "To start creating instances of model, create an admin account by using the following command.Python manage.py createsuperuser" }, { "code": null, "e": 4536, "s": 4503, "text": "Python manage.py createsuperuser" }, { "code": null, "e": 4657, "s": 4536, "text": "Enter a username, email and a secure password. Then in your browser enter the following URL.http://localhost:8000/admin/" }, { "code": null, "e": 4686, "s": 4657, "text": "http://localhost:8000/admin/" }, { "code": null, "e": 4722, "s": 4686, "text": "Go to add in front of Geeks Models." }, { "code": null, "e": 4855, "s": 4722, "text": "Choose the file you want to upload and click on save. Now let’s check it in admin server. We have created an instance of GeeksModel." }, { "code": null, "e": 5203, "s": 4855, "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 ImageField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an ImageField can use." }, { "code": null, "e": 5215, "s": 5203, "text": "NaveenArora" }, { "code": null, "e": 5229, "s": 5215, "text": "Django-models" }, { "code": null, "e": 5243, "s": 5229, "text": "Python Django" }, { "code": null, "e": 5250, "s": 5243, "text": "Python" }, { "code": null, "e": 5348, "s": 5250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5366, "s": 5348, "text": "Python Dictionary" }, { "code": null, "e": 5408, "s": 5366, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5430, "s": 5408, "text": "Enumerate() in Python" }, { "code": null, "e": 5465, "s": 5430, "text": "Read a file line by line in Python" }, { "code": null, "e": 5491, "s": 5465, "text": "Python String | replace()" }, { "code": null, "e": 5523, "s": 5491, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5552, "s": 5523, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5579, "s": 5552, "text": "Python Classes and Objects" }, { "code": null, "e": 5609, "s": 5579, "text": "Iterate over a list in Python" } ]
DoubleUnaryOperator Interface in Java
18 Nov, 2019 The DoubleUnaryOperator Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and operates on it. Both its argument and return type are of double data type.It is very similar to using an object of type UnaryOperator<Double>. The lambda expression assigned to an object of DoubleUnaryOperator type is used to define its applyAsDouble() which eventually applies the given operation on its argument. The DoubleUnaryOperator interface consists of the following functions: This method returns a DoubleUnaryOperator which takes in one double value and returns it. The returned DoubleUnaryOperator does not perform any operation on its only value. Syntax: static DoubleUnaryOperator identity() Parameters: This method does not take in any parameter Returns: A DoubleUnaryOperator which takes in one value and returns it. Below is the code to illustrate identity() method: Program import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { DoubleUnaryOperator op = DoubleUnaryOperator.identity(); System.out.println(op.applyAsDouble(12.0)); }} 12.0 This method takes in one double value, performs the given operation and returns a double-valued result. Syntax: double applyAsDouble(double operand) Parameters: This method takes in one double valued parameter Returns:: It returns a double valued result. Below is the code to illustrate applyAsDouble() method: Program import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { DoubleUnaryOperator op = a -> 2 * a; System.out.println(op.applyAsDouble(12.0)); }} 24.0 It returns a composed DoubleUnaryOperator wherein the parameterized operator will be executed after the first one. If either operation throws an error, it is relayed to the caller of the composed operation. Syntax: default DoubleUnaryOperator andThen(DoubleUnaryOperator after) Parameters: This method accepts a parameter after which is the operation to be applied after the current one. Return Value: This method returns a composed DoubleUnaryOperator that applies the current operation first and then the after operation. Exception: This method throws NullPointerException if the after operation is null. Below is the code to illustrate addThen() method: Program 1: import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { DoubleUnaryOperator op = a -> 2 * a; op = op.andThen(a -> 3 * a); System.out.println(op.applyAsDouble(12.0)); }} 72.0 Program 2: To demonstrate when NullPointerException is returned. import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { try { DoubleUnaryOperator op = a -> 2 * a; op = op.andThen(null); System.out.println(op.applyAsDouble(12.0)); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.NullPointerException It returns a composed DoubleUnaryOperator wherein the parameterized operation will be executed first and then the first one. If either operation throws an error, it is relayed to the caller of the composed operation. Syntax: default DoubleUnaryOperator compose(DoubleUnaryOperator before) Parameters: This method accepts a parameter before which is the operation to be applied first and then the current one Return Value: This method returns a composed DoubleUnaryOperator that applies the current operator after the parameterized operator Exception: This method throws NullPointerException if the before operation is null. Below is the code to illustrate compose() method: Program 1: import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { DoubleUnaryOperator op = a -> a / 3; op = op.compose(a -> a * 6); System.out.println(op.applyAsDouble(12.0)); }} 24.0 Program 2: To demonstrate when NullPointerException is returned. import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { try { DoubleUnaryOperator op = a -> a / 3; op = op.compose(null); System.out.println(op.applyAsDouble(12.0)); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.NullPointerException Akanksha_Rai Java - util package Java 8 java-basics Java-Functional Programming java-interfaces Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Nov, 2019" }, { "code": null, "e": 391, "s": 28, "text": "The DoubleUnaryOperator Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and operates on it. Both its argument and return type are of double data type.It is very similar to using an object of type UnaryOperator<Double>." }, { "code": null, "e": 563, "s": 391, "text": "The lambda expression assigned to an object of DoubleUnaryOperator type is used to define its applyAsDouble() which eventually applies the given operation on its argument." }, { "code": null, "e": 634, "s": 563, "text": "The DoubleUnaryOperator interface consists of the following functions:" }, { "code": null, "e": 807, "s": 634, "text": "This method returns a DoubleUnaryOperator which takes in one double value and returns it. The returned DoubleUnaryOperator does not perform any operation on its only value." }, { "code": null, "e": 815, "s": 807, "text": "Syntax:" }, { "code": null, "e": 854, "s": 815, "text": "static DoubleUnaryOperator identity()" }, { "code": null, "e": 909, "s": 854, "text": "Parameters: This method does not take in any parameter" }, { "code": null, "e": 981, "s": 909, "text": "Returns: A DoubleUnaryOperator which takes in one value and returns it." }, { "code": null, "e": 1032, "s": 981, "text": "Below is the code to illustrate identity() method:" }, { "code": null, "e": 1040, "s": 1032, "text": "Program" }, { "code": "import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { DoubleUnaryOperator op = DoubleUnaryOperator.identity(); System.out.println(op.applyAsDouble(12.0)); }}", "e": 1299, "s": 1040, "text": null }, { "code": null, "e": 1305, "s": 1299, "text": "12.0\n" }, { "code": null, "e": 1409, "s": 1305, "text": "This method takes in one double value, performs the given operation and returns a double-valued result." }, { "code": null, "e": 1417, "s": 1409, "text": "Syntax:" }, { "code": null, "e": 1454, "s": 1417, "text": "double applyAsDouble(double operand)" }, { "code": null, "e": 1515, "s": 1454, "text": "Parameters: This method takes in one double valued parameter" }, { "code": null, "e": 1560, "s": 1515, "text": "Returns:: It returns a double valued result." }, { "code": null, "e": 1616, "s": 1560, "text": "Below is the code to illustrate applyAsDouble() method:" }, { "code": null, "e": 1624, "s": 1616, "text": "Program" }, { "code": "import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { DoubleUnaryOperator op = a -> 2 * a; System.out.println(op.applyAsDouble(12.0)); }}", "e": 1841, "s": 1624, "text": null }, { "code": null, "e": 1847, "s": 1841, "text": "24.0\n" }, { "code": null, "e": 2054, "s": 1847, "text": "It returns a composed DoubleUnaryOperator wherein the parameterized operator will be executed after the first one. If either operation throws an error, it is relayed to the caller of the composed operation." }, { "code": null, "e": 2062, "s": 2054, "text": "Syntax:" }, { "code": null, "e": 2125, "s": 2062, "text": "default DoubleUnaryOperator andThen(DoubleUnaryOperator after)" }, { "code": null, "e": 2235, "s": 2125, "text": "Parameters: This method accepts a parameter after which is the operation to be applied after the current one." }, { "code": null, "e": 2371, "s": 2235, "text": "Return Value: This method returns a composed DoubleUnaryOperator that applies the current operation first and then the after operation." }, { "code": null, "e": 2454, "s": 2371, "text": "Exception: This method throws NullPointerException if the after operation is null." }, { "code": null, "e": 2504, "s": 2454, "text": "Below is the code to illustrate addThen() method:" }, { "code": null, "e": 2515, "s": 2504, "text": "Program 1:" }, { "code": "import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { DoubleUnaryOperator op = a -> 2 * a; op = op.andThen(a -> 3 * a); System.out.println(op.applyAsDouble(12.0)); }}", "e": 2772, "s": 2515, "text": null }, { "code": null, "e": 2778, "s": 2772, "text": "72.0\n" }, { "code": null, "e": 2843, "s": 2778, "text": "Program 2: To demonstrate when NullPointerException is returned." }, { "code": "import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { try { DoubleUnaryOperator op = a -> 2 * a; op = op.andThen(null); System.out.println(op.applyAsDouble(12.0)); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 3216, "s": 2843, "text": null }, { "code": null, "e": 3259, "s": 3216, "text": "Exception: java.lang.NullPointerException\n" }, { "code": null, "e": 3476, "s": 3259, "text": "It returns a composed DoubleUnaryOperator wherein the parameterized operation will be executed first and then the first one. If either operation throws an error, it is relayed to the caller of the composed operation." }, { "code": null, "e": 3484, "s": 3476, "text": "Syntax:" }, { "code": null, "e": 3548, "s": 3484, "text": "default DoubleUnaryOperator compose(DoubleUnaryOperator before)" }, { "code": null, "e": 3667, "s": 3548, "text": "Parameters: This method accepts a parameter before which is the operation to be applied first and then the current one" }, { "code": null, "e": 3799, "s": 3667, "text": "Return Value: This method returns a composed DoubleUnaryOperator that applies the current operator after the parameterized operator" }, { "code": null, "e": 3883, "s": 3799, "text": "Exception: This method throws NullPointerException if the before operation is null." }, { "code": null, "e": 3933, "s": 3883, "text": "Below is the code to illustrate compose() method:" }, { "code": null, "e": 3944, "s": 3933, "text": "Program 1:" }, { "code": "import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { DoubleUnaryOperator op = a -> a / 3; op = op.compose(a -> a * 6); System.out.println(op.applyAsDouble(12.0)); }}", "e": 4201, "s": 3944, "text": null }, { "code": null, "e": 4207, "s": 4201, "text": "24.0\n" }, { "code": null, "e": 4272, "s": 4207, "text": "Program 2: To demonstrate when NullPointerException is returned." }, { "code": "import java.util.function.DoubleUnaryOperator; public class GFG { public static void main(String args[]) { try { DoubleUnaryOperator op = a -> a / 3; op = op.compose(null); System.out.println(op.applyAsDouble(12.0)); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 4645, "s": 4272, "text": null }, { "code": null, "e": 4688, "s": 4645, "text": "Exception: java.lang.NullPointerException\n" }, { "code": null, "e": 4701, "s": 4688, "text": "Akanksha_Rai" }, { "code": null, "e": 4721, "s": 4701, "text": "Java - util package" }, { "code": null, "e": 4728, "s": 4721, "text": "Java 8" }, { "code": null, "e": 4740, "s": 4728, "text": "java-basics" }, { "code": null, "e": 4768, "s": 4740, "text": "Java-Functional Programming" }, { "code": null, "e": 4784, "s": 4768, "text": "java-interfaces" }, { "code": null, "e": 4789, "s": 4784, "text": "Java" }, { "code": null, "e": 4794, "s": 4789, "text": "Java" }, { "code": null, "e": 4892, "s": 4794, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4907, "s": 4892, "text": "Stream In Java" }, { "code": null, "e": 4928, "s": 4907, "text": "Introduction to Java" }, { "code": null, "e": 4949, "s": 4928, "text": "Constructors in Java" }, { "code": null, "e": 4968, "s": 4949, "text": "Exceptions in Java" }, { "code": null, "e": 4985, "s": 4968, "text": "Generics in Java" }, { "code": null, "e": 5015, "s": 4985, "text": "Functional Interfaces in Java" }, { "code": null, "e": 5041, "s": 5015, "text": "Java Programming Examples" }, { "code": null, "e": 5057, "s": 5041, "text": "Strings in Java" }, { "code": null, "e": 5094, "s": 5057, "text": "Differences between JDK, JRE and JVM" } ]
Number of solutions for the equation x + y + z <= n
25 May, 2022 Given four numbers x, y, z, n. The task is to find the number of solutions for the equation x + y + z <= n, such that 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z. Examples: Input: x = 1, y = 1, z = 1, n = 1 Output: 4 Input: x = 1, y = 2, z = 3, n = 4 Output: 20 Approach: Let’s iterate explicitly over all possible values of x and y (using nested loop). For one such fixed values of x and y, the problem reduces to how many values of z are there such that z <= n – x – y and 0 <= z <= Z. Below is the required implementation to find the number of solutions: C++ C Java Python 3 C# PHP Javascript // CPP program to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.#include <bits/stdc++.h>using namespace std; // function to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.int NumberOfSolutions(int x, int y, int z, int n){ // to store answer int ans = 0; // for values of x for (int i = 0; i <= x; i++) { // for values of y for (int j = 0; j <= y; j++) { // maximum possible value of z int temp = n - i - j; // if z value greater than equals to 0 // then only it is valid if (temp >= 0) { // find minimum of temp and z temp = min(temp, z); ans += temp + 1; } } } // return required answer return ans;} // Driver codeint main(){ int x = 1, y = 2, z = 3, n = 4; cout << NumberOfSolutions(x, y, z, n); return 0;} // C program to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.#include <stdio.h> int min(int a, int b){ int min = a; if(min > b) min = b; return min;} // function to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.int NumberOfSolutions(int x, int y, int z, int n){ // to store answer int ans = 0; // for values of x for (int i = 0; i <= x; i++) { // for values of y for (int j = 0; j <= y; j++) { // maximum possible value of z int temp = n - i - j; // if z value greater than equals to 0 // then only it is valid if (temp >= 0) { // find minimum of temp and z temp = min(temp, z); ans += temp + 1; } } } // return required answer return ans;} // Driver codeint main(){ int x = 1, y = 2, z = 3, n = 4; printf("%d",NumberOfSolutions(x, y, z, n)); return 0;} // This code is contributed by kothavvsaakash. // Java program to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z. import java.io.*; class GFG { // function to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.static int NumberOfSolutions(int x, int y, int z, int n){ // to store answer int ans = 0; // for values of x for (int i = 0; i <= x; i++) { // for values of y for (int j = 0; j <= y; j++) { // maximum possible value of z int temp = n - i - j; // if z value greater than equals to 0 // then only it is valid if (temp >= 0) { // find minimum of temp and z temp = Math.min(temp, z); ans += temp + 1; } } } // return required answer return ans;} // Driver code public static void main (String[] args) { int x = 1, y = 2, z = 3, n = 4; System.out.println( NumberOfSolutions(x, y, z, n)); }} // this code is contributed by anuj_67.. # Python3 program to find the number # of solutions for the equation# x + y + z <= n, such that# 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z. # function to find the number of solutions# for the equation x + y + z <= n, such that# 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.def NumberOfSolutions(x, y, z, n) : # to store answer ans = 0 # for values of x for i in range(x + 1) : # for values of y for j in range(y + 1) : # maximum possible value of z temp = n - i - j # if z value greater than equals # to 0 then only it is valid if temp >= 0 : # find minimum of temp and z temp = min(temp, z) ans += temp + 1 # return required answer return ans # Driver codeif __name__ == "__main__" : x, y, z, n = 1, 2, 3, 4 # function calling print(NumberOfSolutions(x, y, z, n)) # This code is contributed by ANKITRAI1 // C# program to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.using System; public class GFG{ // function to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.static int NumberOfSolutions(int x, int y, int z, int n){ // to store answer int ans = 0; // for values of x for (int i = 0; i <= x; i++) { // for values of y for (int j = 0; j <= y; j++) { // maximum possible value of z int temp = n - i - j; // if z value greater than equals to 0 // then only it is valid if (temp >= 0) { // find minimum of temp and z temp = Math.Min(temp, z); ans += temp + 1; } } } // return required answer return ans;} // Driver code static public void Main (){ int x = 1, y = 2, z = 3, n = 4; Console.WriteLine( NumberOfSolutions(x, y, z, n)); }} // This code is contributed by anuj_67.. <?php// PHP program to find the number// of solutions for the equation// x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z. // function to find the number of// solutions for the equation// x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.function NumberOfSolutions($x, $y, $z, $n){ // to store answer $ans = 0; // for values of x for ($i = 0; $i <= $x; $i++) { // for values of y for ($j = 0; $j <= $y; $j++) { // maximum possible value of z $temp = $n - $i - $j; // if z value greater than equals // to 0 then only it is valid if ($temp >= 0) { // find minimum of temp and z $temp = min($temp, $z); $ans += $temp + 1; } } } // return required answer return $ans;} // Driver code$x = 1; $y = 2;$z = 3; $n = 4; echo NumberOfSolutions($x, $y, $z, $n); // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // Javascript program to find the number// of solutions for the equation x + y + z <= n,// such that 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z. // Function to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.function NumberOfSolutions(x, y, z, n){ // To store answer var ans = 0; // for values of x for(var i = 0; i <= x; i++) { // for values of y for(var j = 0; j <= y; j++) { // Maximum possible value of z var temp = n - i - j; // If z value greater than equals to 0 // then only it is valid if (temp >= 0) { // Find minimum of temp and z temp = Math.min(temp, z); ans += temp + 1; } } } // Return required answer return ans;} // Driver Codevar x = 1, y = 2, z = 3, n = 4; document.write(NumberOfSolutions(x, y, z, n)); // This code is contributed by Ankita saini </script> 20 vt_m ankthon Akanksha_Rai ankita_saini kothavvsaakash Competitive Programming Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of strings whose prefix match with the given string to a given length k Most important type of Algorithms The Ultimate Beginner's Guide For DSA Find two numbers from their sum and XOR Equal Sum and XOR of three Numbers Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n25 May, 2022" }, { "code": null, "e": 185, "s": 28, "text": "Given four numbers x, y, z, n. The task is to find the number of solutions for the equation x + y + z <= n, such that 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z." }, { "code": null, "e": 196, "s": 185, "text": "Examples: " }, { "code": null, "e": 286, "s": 196, "text": "Input: x = 1, y = 1, z = 1, n = 1\nOutput: 4\n\nInput: x = 1, y = 2, z = 3, n = 4\nOutput: 20" }, { "code": null, "e": 513, "s": 286, "text": "Approach: Let’s iterate explicitly over all possible values of x and y (using nested loop). For one such fixed values of x and y, the problem reduces to how many values of z are there such that z <= n – x – y and 0 <= z <= Z. " }, { "code": null, "e": 584, "s": 513, "text": "Below is the required implementation to find the number of solutions: " }, { "code": null, "e": 588, "s": 584, "text": "C++" }, { "code": null, "e": 590, "s": 588, "text": "C" }, { "code": null, "e": 595, "s": 590, "text": "Java" }, { "code": null, "e": 604, "s": 595, "text": "Python 3" }, { "code": null, "e": 607, "s": 604, "text": "C#" }, { "code": null, "e": 611, "s": 607, "text": "PHP" }, { "code": null, "e": 622, "s": 611, "text": "Javascript" }, { "code": "// CPP program to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.#include <bits/stdc++.h>using namespace std; // function to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.int NumberOfSolutions(int x, int y, int z, int n){ // to store answer int ans = 0; // for values of x for (int i = 0; i <= x; i++) { // for values of y for (int j = 0; j <= y; j++) { // maximum possible value of z int temp = n - i - j; // if z value greater than equals to 0 // then only it is valid if (temp >= 0) { // find minimum of temp and z temp = min(temp, z); ans += temp + 1; } } } // return required answer return ans;} // Driver codeint main(){ int x = 1, y = 2, z = 3, n = 4; cout << NumberOfSolutions(x, y, z, n); return 0;}", "e": 1636, "s": 622, "text": null }, { "code": "// C program to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.#include <stdio.h> int min(int a, int b){ int min = a; if(min > b) min = b; return min;} // function to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.int NumberOfSolutions(int x, int y, int z, int n){ // to store answer int ans = 0; // for values of x for (int i = 0; i <= x; i++) { // for values of y for (int j = 0; j <= y; j++) { // maximum possible value of z int temp = n - i - j; // if z value greater than equals to 0 // then only it is valid if (temp >= 0) { // find minimum of temp and z temp = min(temp, z); ans += temp + 1; } } } // return required answer return ans;} // Driver codeint main(){ int x = 1, y = 2, z = 3, n = 4; printf(\"%d\",NumberOfSolutions(x, y, z, n)); return 0;} // This code is contributed by kothavvsaakash.", "e": 2752, "s": 1636, "text": null }, { "code": "// Java program to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z. import java.io.*; class GFG { // function to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.static int NumberOfSolutions(int x, int y, int z, int n){ // to store answer int ans = 0; // for values of x for (int i = 0; i <= x; i++) { // for values of y for (int j = 0; j <= y; j++) { // maximum possible value of z int temp = n - i - j; // if z value greater than equals to 0 // then only it is valid if (temp >= 0) { // find minimum of temp and z temp = Math.min(temp, z); ans += temp + 1; } } } // return required answer return ans;} // Driver code public static void main (String[] args) { int x = 1, y = 2, z = 3, n = 4; System.out.println( NumberOfSolutions(x, y, z, n)); }} // this code is contributed by anuj_67..", "e": 3856, "s": 2752, "text": null }, { "code": "# Python3 program to find the number # of solutions for the equation# x + y + z <= n, such that# 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z. # function to find the number of solutions# for the equation x + y + z <= n, such that# 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.def NumberOfSolutions(x, y, z, n) : # to store answer ans = 0 # for values of x for i in range(x + 1) : # for values of y for j in range(y + 1) : # maximum possible value of z temp = n - i - j # if z value greater than equals # to 0 then only it is valid if temp >= 0 : # find minimum of temp and z temp = min(temp, z) ans += temp + 1 # return required answer return ans # Driver codeif __name__ == \"__main__\" : x, y, z, n = 1, 2, 3, 4 # function calling print(NumberOfSolutions(x, y, z, n)) # This code is contributed by ANKITRAI1", "e": 4805, "s": 3856, "text": null }, { "code": "// C# program to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.using System; public class GFG{ // function to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.static int NumberOfSolutions(int x, int y, int z, int n){ // to store answer int ans = 0; // for values of x for (int i = 0; i <= x; i++) { // for values of y for (int j = 0; j <= y; j++) { // maximum possible value of z int temp = n - i - j; // if z value greater than equals to 0 // then only it is valid if (temp >= 0) { // find minimum of temp and z temp = Math.Min(temp, z); ans += temp + 1; } } } // return required answer return ans;} // Driver code static public void Main (){ int x = 1, y = 2, z = 3, n = 4; Console.WriteLine( NumberOfSolutions(x, y, z, n)); }} // This code is contributed by anuj_67..", "e": 5911, "s": 4805, "text": null }, { "code": "<?php// PHP program to find the number// of solutions for the equation// x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z. // function to find the number of// solutions for the equation// x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.function NumberOfSolutions($x, $y, $z, $n){ // to store answer $ans = 0; // for values of x for ($i = 0; $i <= $x; $i++) { // for values of y for ($j = 0; $j <= $y; $j++) { // maximum possible value of z $temp = $n - $i - $j; // if z value greater than equals // to 0 then only it is valid if ($temp >= 0) { // find minimum of temp and z $temp = min($temp, $z); $ans += $temp + 1; } } } // return required answer return $ans;} // Driver code$x = 1; $y = 2;$z = 3; $n = 4; echo NumberOfSolutions($x, $y, $z, $n); // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 6933, "s": 5911, "text": null }, { "code": "<script> // Javascript program to find the number// of solutions for the equation x + y + z <= n,// such that 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z. // Function to find the number of solutions for// the equation x + y + z <= n, such that// 0 <= x <= X, 0 <= y <= Y, 0 <= z <= Z.function NumberOfSolutions(x, y, z, n){ // To store answer var ans = 0; // for values of x for(var i = 0; i <= x; i++) { // for values of y for(var j = 0; j <= y; j++) { // Maximum possible value of z var temp = n - i - j; // If z value greater than equals to 0 // then only it is valid if (temp >= 0) { // Find minimum of temp and z temp = Math.min(temp, z); ans += temp + 1; } } } // Return required answer return ans;} // Driver Codevar x = 1, y = 2, z = 3, n = 4; document.write(NumberOfSolutions(x, y, z, n)); // This code is contributed by Ankita saini </script>", "e": 8009, "s": 6933, "text": null }, { "code": null, "e": 8012, "s": 8009, "text": "20" }, { "code": null, "e": 8019, "s": 8014, "text": "vt_m" }, { "code": null, "e": 8027, "s": 8019, "text": "ankthon" }, { "code": null, "e": 8040, "s": 8027, "text": "Akanksha_Rai" }, { "code": null, "e": 8053, "s": 8040, "text": "ankita_saini" }, { "code": null, "e": 8068, "s": 8053, "text": "kothavvsaakash" }, { "code": null, "e": 8092, "s": 8068, "text": "Competitive Programming" }, { "code": null, "e": 8105, "s": 8092, "text": "Mathematical" }, { "code": null, "e": 8118, "s": 8105, "text": "Mathematical" }, { "code": null, "e": 8216, "s": 8118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8294, "s": 8216, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 8328, "s": 8294, "text": "Most important type of Algorithms" }, { "code": null, "e": 8366, "s": 8328, "text": "The Ultimate Beginner's Guide For DSA" }, { "code": null, "e": 8406, "s": 8366, "text": "Find two numbers from their sum and XOR" }, { "code": null, "e": 8441, "s": 8406, "text": "Equal Sum and XOR of three Numbers" }, { "code": null, "e": 8471, "s": 8441, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 8514, "s": 8471, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 8574, "s": 8514, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 8589, "s": 8574, "text": "C++ Data Types" } ]
Searching BETWEEN dates stored as varchar in MySQL?
You can search between dates stored as varchar using STR_TO_DATE(). The syntax is as follows − select *from yourTableName where STR_TO_DATE(LEFT(yourColumnName,LOCATE('',yourColumnName)),'%m/%d/%Y') BETWEEN 'yourDateValue1' AND 'yourDateValue2’; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table SearchDateAsVarchar -> ( -> Id int NOT NULL AUTO_INCREMENT, -> ShippingDate varchar(100), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.99 sec) Insert some records in the table using INSERT command. The query is as follows − mysql> insert into SearchDateAsVarchar(ShippingDate) values('6/28/2011 9:58 AM'); Query OK, 1 row affected (0.19 sec) mysql> insert into SearchDateAsVarchar(ShippingDate) values('6/18/2011 10:50:39 AM'); Query OK, 1 row affected (0.55 sec) mysql> insert into SearchDateAsVarchar(ShippingDate) values('6/22/2011 11:45:40 AM'); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from SearchDateAsVarchar; The following is the output − +----+-----------------------+ | Id | ShippingDate | +----+-----------------------+ | 1 | 6/28/2011 9:58 AM | | 2 | 6/18/2011 10:50:39 AM | | 3 | 6/22/2011 11:45:40 AM | +----+-----------------------+ 3 rows in set (0.00 sec) Here is the query to search between dates stored as varchar − mysql> select *from SearchDateAsVarchar where STR_TO_DATE(LEFT(ShippingDate,LOCATE(' ',ShippingDate)),'%m/%d/%Y') BETWEEN '2011-06-20' AND '2011-06-28'; The following is the output − +----+-----------------------+ | Id | ShippingDate | +----+-----------------------+ | 1 | 6/28/2011 9:58 AM | | 3 | 6/22/2011 11:45:40 AM | +----+-----------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1282, "s": 1187, "text": "You can search between dates stored as varchar using STR_TO_DATE(). The syntax is as follows −" }, { "code": null, "e": 1433, "s": 1282, "text": "select *from yourTableName where STR_TO_DATE(LEFT(yourColumnName,LOCATE('',yourColumnName)),'%m/%d/%Y') BETWEEN 'yourDateValue1' AND 'yourDateValue2’;" }, { "code": null, "e": 1532, "s": 1433, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1719, "s": 1532, "text": "mysql> create table SearchDateAsVarchar\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> ShippingDate varchar(100),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.99 sec)" }, { "code": null, "e": 1800, "s": 1719, "text": "Insert some records in the table using INSERT command. The query is as follows −" }, { "code": null, "e": 2162, "s": 1800, "text": "mysql> insert into SearchDateAsVarchar(ShippingDate) values('6/28/2011 9:58 AM');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into SearchDateAsVarchar(ShippingDate) values('6/18/2011 10:50:39 AM');\nQuery OK, 1 row affected (0.55 sec)\nmysql> insert into SearchDateAsVarchar(ShippingDate) values('6/22/2011 11:45:40 AM');\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 2247, "s": 2162, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2288, "s": 2247, "text": "mysql> select *from SearchDateAsVarchar;" }, { "code": null, "e": 2318, "s": 2288, "text": "The following is the output −" }, { "code": null, "e": 2560, "s": 2318, "text": "+----+-----------------------+\n| Id | ShippingDate |\n+----+-----------------------+\n| 1 | 6/28/2011 9:58 AM |\n| 2 | 6/18/2011 10:50:39 AM |\n| 3 | 6/22/2011 11:45:40 AM |\n+----+-----------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2622, "s": 2560, "text": "Here is the query to search between dates stored as varchar −" }, { "code": null, "e": 2775, "s": 2622, "text": "mysql> select *from SearchDateAsVarchar where\nSTR_TO_DATE(LEFT(ShippingDate,LOCATE(' ',ShippingDate)),'%m/%d/%Y') BETWEEN\n'2011-06-20' AND '2011-06-28';" }, { "code": null, "e": 2805, "s": 2775, "text": "The following is the output −" }, { "code": null, "e": 3016, "s": 2805, "text": "+----+-----------------------+\n| Id | ShippingDate |\n+----+-----------------------+\n| 1 | 6/28/2011 9:58 AM |\n| 3 | 6/22/2011 11:45:40 AM |\n+----+-----------------------+\n2 rows in set (0.00 sec)" } ]
JSF - Expression Language
JSF provides a rich expression language. We can write normal operations using #{operation-expression} notation. Following are some of the advantages of JSF Expression languages. Can reference bean properties where bean can be an object stored in request, session or application scope or is a managed bean. Can reference bean properties where bean can be an object stored in request, session or application scope or is a managed bean. Provides easy access to elements of a collection which can be a list, map or an array. Provides easy access to elements of a collection which can be a list, map or an array. Provides easy access to predefined objects such as a request. Provides easy access to predefined objects such as a request. Arithmetic, logical and relational operations can be done using expression language. Arithmetic, logical and relational operations can be done using expression language. Automatic type conversion. Automatic type conversion. Shows missing values as empty strings instead of NullPointerException. Shows missing values as empty strings instead of NullPointerException. Let us create a test JSF application to test expression language. package com.tutorialspoint.test; import java.io.Serializable; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; private Date createTime = new Date(); private String message = "Hello World!"; public Date getCreateTime() { return(createTime); } public String getMessage() { return(message); } } <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html"> <h:head> <title>JSF Tutorial!</title> </h:head> <h:body> <h2>Expression Language Example</h2> Creation time: <h:outputText value = "#{userData.createTime}"/> <br/><br/> Message: <h:outputText value = "#{userData.message}"/> </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2130, "s": 1952, "text": "JSF provides a rich expression language. We can write normal operations using #{operation-expression} notation. Following are some of the advantages of JSF Expression languages." }, { "code": null, "e": 2258, "s": 2130, "text": "Can reference bean properties where bean can be an object stored in request, session or application scope or is a managed bean." }, { "code": null, "e": 2386, "s": 2258, "text": "Can reference bean properties where bean can be an object stored in request, session or application scope or is a managed bean." }, { "code": null, "e": 2473, "s": 2386, "text": "Provides easy access to elements of a collection which can be a list, map or an array." }, { "code": null, "e": 2560, "s": 2473, "text": "Provides easy access to elements of a collection which can be a list, map or an array." }, { "code": null, "e": 2622, "s": 2560, "text": "Provides easy access to predefined objects such as a request." }, { "code": null, "e": 2684, "s": 2622, "text": "Provides easy access to predefined objects such as a request." }, { "code": null, "e": 2769, "s": 2684, "text": "Arithmetic, logical and relational operations can be done using expression language." }, { "code": null, "e": 2854, "s": 2769, "text": "Arithmetic, logical and relational operations can be done using expression language." }, { "code": null, "e": 2881, "s": 2854, "text": "Automatic type conversion." }, { "code": null, "e": 2908, "s": 2881, "text": "Automatic type conversion." }, { "code": null, "e": 2979, "s": 2908, "text": "Shows missing values as empty strings instead of NullPointerException." }, { "code": null, "e": 3050, "s": 2979, "text": "Shows missing values as empty strings instead of NullPointerException." }, { "code": null, "e": 3116, "s": 3050, "text": "Let us create a test JSF application to test expression language." }, { "code": null, "e": 3657, "s": 3116, "text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n private Date createTime = new Date();\n private String message = \"Hello World!\";\n\n public Date getCreateTime() {\n return(createTime);\n }\n \n public String getMessage() {\n return(message);\n }\n}" }, { "code": null, "e": 4269, "s": 3657, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n \n <h:head>\n <title>JSF Tutorial!</title>\n </h:head>\n \n <h:body>\n <h2>Expression Language Example</h2>\n Creation time: \n <h:outputText value = \"#{userData.createTime}\"/>\n <br/><br/>\n Message: \n <h:outputText value = \"#{userData.message}\"/>\n </h:body>\n</html> " }, { "code": null, "e": 4485, "s": 4269, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 4520, "s": 4485, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4535, "s": 4520, "text": " Chaand Sheikh" }, { "code": null, "e": 4542, "s": 4535, "text": " Print" }, { "code": null, "e": 4553, "s": 4542, "text": " Add Notes" } ]
Setting Up Jupyter on Google Cloud | by Asko Seeba | Towards Data Science
UPDATE: In my next post I gave the equivalent instructions for Setting Up Jupyter on AWS — if you are more into AWS, go and check that article. Google Cloud is a great, powerful and rapidly evolving contemporary cloud environment, which provides plenty of cool services and tools for data scientists and data engineers. As a data scientist, when you run your analysis projects on your local laptop computer, you often face technical resource challenges, be it network speed for downloading large datasets, disk size limitations, CPU power limitations or memory limitations. In a contemporary cloud environment, you basically have easy solutions at hand for any of those obstacles. You have fast network connectivity. You can always start any task with small, lean and mean resources. Whenever you face disk storage problems, you just hire a bigger disk with a couple of clicks. Or you can load the dataset into BigQuery or some other suitable storage service for cost-effective handling. Too little CPU power? No worries, add more CPU to your VM (which you can scale back down immediately when you don’t need it anymore). Out of memory? A couple of clicks later you have more memory, and again, you can take it back down if it isn’t needed any more. Any sort of cluster formation for distributed computing is also usually just some clicks away, when you just know what you do: boot the cluster up for the heavier compute job, persist the results in some storage service outside of the cluster, and shut the cluster down to not let it stand idle (and incur unnecessary cost). As most of the data scientists these days are used to work with Jupyter Notebook or JupyterLab (the newer version of Jupyter Notebook), one of the first questions that any data scientist faces when getting started with Google Cloud, is how to set it up in a way that is reasonably convenient to use and avoid unnecessary cloud costs. One thing that Google Cloud catches your attention with, is their Datalab product, which is basically Google’s facelift to Jupyter Notebook deployed within a dedicated VM with extra persistent disk and couple of extra services (like automated backup and Ungit) added to it. One of the main virtues of using GC Datalab instead of your own deployed Jupyter is that its deployment is all prepared and automated for you — you just type in a specific command line from the Cloud Shell, wait a bit for the provisioning, and there you go, the entire UI environment readily accessible through the GC Cloud Shell Web Preview feature, SDK-s for easy integration with different cloud services already deployed etc. So, it is really easy to get quickly started with GC Datalab. However, that convenience of getting quickly started comes with drawbacks of a bit too constrained and custom designed underlying Linux environment and setup (not a familiar Debian family — no apt* based tools to install additional packages), and few other unexpected unnecessary annoyances, at least to my tastes. So I figured out a way to set up Jupyter Lab (a newer version of Jupyter Notebooks) in a way that achieves the similar (or actually even better) ease of use and cloud integration, and is less costly (by avoiding the mandatory additional persistent disk that comes with Datalab while actually not always necessary). I have preferred using Jupyter Lab over Datalab when working in otherwise Google Cloud environment ever since. If you are experienced with Jupyter Notebook and feel comfortable with Debian-like environments, then you might find the following instructions helpful. For the purpose of being scriptable/automatable, the following instructions rely on Google Cloud Shell command line, i.e. we avoid doing the same things via the Cloud Console UI. 1. Create or select a cloud project where you want to deploy the Jupyter VM. 2. Open the Google Cloud console and activate the Cloud Shell from the Cloud Console. You can do that from the toolbar button at to top right corner of the Cloud Console: 3. At the Cloud Shell command prompt, enter the following commands (adjust the project name, instance vm name, region and machine-type as you wish — rest of the options I’d recommend to leave as they are here, unless you know what you do): PROJECT_NAME=my-project-name #change this to actual project nameVM_NAME=my-jupyterlabZONE=europe-west1-bMACHINE_TYPE=n1-standard-1gcloud compute --project=$PROJECT_NAME \ instances create $VM_NAME \ --zone=$ZONE \ --machine-type=$MACHINE_TYPE \ --maintenance-policy=MIGRATE \ --image-family=debian-10 \ --image-project=debian-cloud \ --scopes=cloud-platformgcloud compute ssh my-jupyterlab --zone europe-west1-b 4. The last command above takes you to the newly created VM’s command prompt. Enter the following commands there: sudo apt updatesudo apt upgrade # Hit 'Y' and Enter key when askedsudo apt install python3-pip # Hit 'Y' and Enter key when askedsudo pip3 install --upgrade jupyterlab google-api-python-clientsudo mkdir -p /opt/my_jupyterlab/binsudo sh -c \ 'echo "#!/bin/bash" > /opt/my_jupyterlab/bin/run_jupyterlab'sudo chmod a+x /opt/my_jupyterlab/bin/run_jupyterlab IMPORTANT!!! On the next command, --ip=127.0.0.1 is necessary for the security reasons, to block any external access attempt, especially as we are turning off the password and security token here to achieve usage convenience that is identical to Datalab. When you get more familiar with Google Cloud later and learn how to configure networking, then for an added security measure, you can turn off the external IP from the VM at all, and create a firewall setup so the VM would still be able to communicate with the outer world (needed for installing the packages and downloading datasets). However, to not over-complicate the current instructions with the firewall features, this is what already achieves the setup where you can access your notebooks through your GC account authentication, without extra password interaction by Jupyter, while not exposing your notebooks to the public world: sudo sh -c 'echo "jupyter lab \\ --ip=127.0.0.1 \\ --NotebookApp.token=\"\" \\ --NotebookApp.password=\"\" \\ --NotebookApp.allow_origin=\"*\"" \ >> /opt/my_jupyterlab/bin/run_jupyterlab'exit 5. The VM with JupyterLab is now provisioned and configured, and with the exit command at the end above you get back to the Cloud Shell command line. Let’s connect the dots that make the JupyterLab easy to launch and use: echo "" >> .bashrcecho "alias my_jupyterlab=\"gcloud compute ssh my-jupyterlab \\ --zone europe-west1-b \\ -- -L 8080:localhost:8888 -4 \\ '/opt/my_jupyterlab/bin/run_jupyterlab'\"" \ >> .bashrcexit 6. The exit command in the end above closes the Cloud Shell. Open the Cloud Shell again, and enter the following command to test the command line alias we just created: my_jupyterlab 7. The last command above opens the ssh connection to the newly created VM, created the tunnel needed for the Cloud Console Web Preview feature, and launched the JupyterLab service inside the VM — you should see the JupyterLab’s log output on the Console Shell terminal output. If you hit Ctrl+C here and terminate the JupyterLab service, the connection gets closed and you’ll be back on the Console Shell command line prompt. But don’t do it (i.e. don’t hit the Ctrl+C — if you did, enter the above command again) yet, if you want the next step to succeed as well :). 8. To open the JupyterLab UI, click on the “Web Preview” button on the Cloud Shell toolbar, and then click “Preview on port 8080” 9. Voila! You are in JupyterLab! You have the Google Cloud’s python API installed (see the pip3 install --upgrade command above), and it has access to the Google Cloud services (see the --scopes=cloud-platform option at VM creation above). Your JupyterLab python environment is fully integrated with all the Google Cloud services and able to interact with these services the same way the Datalab would be. From here on, you can create and edit notebooks, interact with the underlying Debian platform (through the notebook command line magic or launch a Terminal from JupyterLab for that), or do whatever you feel comfortable to do in Debian based Jupyter environment. Add whatever packages you feel are necessary (apt install git; pip3 install pandas; etc). Whenever you stop working with your notebooks, don’t forget to shut down the VM, to avoid unnecessary cloud costs. When you later return back to working on your notebooks do the following: 1. Relaunch the VM. 2. Open the Cloud Console command prompt. 3. Enter the following command: my_jupyterlab 4. Click on the “Web Preview” button on the Cloud Shell toolbar, and then click “Preview on port 8080”. The default VM primary disk size is 10GB. I would recommend leaving it as it is and adding an additional persistent disk to the VM only when you need to work with bigger datasets. Having that extra space as an additional disk gives you the opportunity to drop and delete it (having those files you want to preserve backed up to Cloud Storage before deleting the disk) if you have finished your project. Persistent disks are a rather costly service at typical personal budget levels so it doesn’t make sense to just let them sit idle, having you to pay for them on a monthly basis. Also, due to the same cost reason, before creating another persistent disk, think a bit about how big disk you actually need. Datalab creates a 200GB disk for you by default (as of writing this, europe-west1 price for a regular 200GB SSD is €31.30/month), but maybe 25GB is already big enough for your current project at hand (€3.91/month)? You can find the instructions for adding a persistent disk to VM from here. One thing that is specific to Google Cloud Web Preview based web UI tunneling, that might happen, is that you suddenly see the Jupyter web UI loses the connection to the Jupyter service (the same thing might happen to the Datalab as well, by the way). In such a case, go and check if your Cloud Shell is still connected, and reconnect it, if necessary. The reason in such case is that the Cloud Shell holds the tunnel, and if Cloud Shell somehow disconnects, it takes the tunnel with it, and causes the Jupyter web UI to lose the connection to the backend. If that disconnect happened due to a temporary network connectivity, then clicking on the “reconnect” link on the Cloud Shell toolbar might suffice to recover the JupyterLab connection without even losing the session state. But if the connection between Cloud Shell and Jupyter VM has been lost (i.e. it is not just the network connectivity issue between your browser and Google Cloud Console services), then you have to enter the my_jupyterlab command again from Cloud Shell, to launch the Jupyter service again. The above is enough to get you up and running with the Jupyter environment in Google Cloud. But to force you to think, practice some Google Cloud tinkering and strengthen your confidence with that environment, here are some bonus exercises, that result in making your life even easier, and that I suggest you try to solve on your own. Feel free to post the description of your solutions or questions you might get as a response below, and I will attempt to comment on them for your feedback. Make the launching of the Jupyter VM more convenient. Improve the my_jupyterlab Cloud Shell alias in the way, that it checks if the VM is already running — if not, then automatically launch the VM, wait for it to be up and ready, and launch Jupyter in it. This way you’ll eliminate the separate manual step of launching the VM. Improve the my_jupyterlab Cloud Shell alias in the way that after stopping the Jupyter service with ctrl+c it would offer you to stop the VM as well (with default action being stopping the VM) — this way you avoid unnecessary cloud costs incurring from accidentally forgetting to shut down the VM. Install the Cloud SDK into your local desktop or laptop machine, and try to achieve the setup where you can connect the ssh tunnel to the cloud-hosted Jupyter VM and launch the Jupyter service there from your local desktop or laptop, instead of using the Cloud Shell and Web Preview. This way you would eliminate another extra step from your everyday workflow (which is opening the cloud console and launching the Console Shell). Automate the deployment of the new Jupyter VM, to avoid manually copy-pasting all the commands above every time you want to create one. This way you make your life even more flexible and agile if you want to maintain separate environments for different projects. There are several ways to do it. Here are a couple of ideas (pick your choice and implement it). Ex. 4 option 1. Script everything in the above instructions so that it would all be triggered from one command line command. Ex. 4 option 2. Create a Jupyter VM image that you can use as a template whenever you want to launch another clean Jupyter environment independent of other projects.
[ { "code": null, "e": 315, "s": 171, "text": "UPDATE: In my next post I gave the equivalent instructions for Setting Up Jupyter on AWS — if you are more into AWS, go and check that article." }, { "code": null, "e": 1746, "s": 315, "text": "Google Cloud is a great, powerful and rapidly evolving contemporary cloud environment, which provides plenty of cool services and tools for data scientists and data engineers. As a data scientist, when you run your analysis projects on your local laptop computer, you often face technical resource challenges, be it network speed for downloading large datasets, disk size limitations, CPU power limitations or memory limitations. In a contemporary cloud environment, you basically have easy solutions at hand for any of those obstacles. You have fast network connectivity. You can always start any task with small, lean and mean resources. Whenever you face disk storage problems, you just hire a bigger disk with a couple of clicks. Or you can load the dataset into BigQuery or some other suitable storage service for cost-effective handling. Too little CPU power? No worries, add more CPU to your VM (which you can scale back down immediately when you don’t need it anymore). Out of memory? A couple of clicks later you have more memory, and again, you can take it back down if it isn’t needed any more. Any sort of cluster formation for distributed computing is also usually just some clicks away, when you just know what you do: boot the cluster up for the heavier compute job, persist the results in some storage service outside of the cluster, and shut the cluster down to not let it stand idle (and incur unnecessary cost)." }, { "code": null, "e": 2354, "s": 1746, "text": "As most of the data scientists these days are used to work with Jupyter Notebook or JupyterLab (the newer version of Jupyter Notebook), one of the first questions that any data scientist faces when getting started with Google Cloud, is how to set it up in a way that is reasonably convenient to use and avoid unnecessary cloud costs. One thing that Google Cloud catches your attention with, is their Datalab product, which is basically Google’s facelift to Jupyter Notebook deployed within a dedicated VM with extra persistent disk and couple of extra services (like automated backup and Ungit) added to it." }, { "code": null, "e": 2846, "s": 2354, "text": "One of the main virtues of using GC Datalab instead of your own deployed Jupyter is that its deployment is all prepared and automated for you — you just type in a specific command line from the Cloud Shell, wait a bit for the provisioning, and there you go, the entire UI environment readily accessible through the GC Cloud Shell Web Preview feature, SDK-s for easy integration with different cloud services already deployed etc. So, it is really easy to get quickly started with GC Datalab." }, { "code": null, "e": 3587, "s": 2846, "text": "However, that convenience of getting quickly started comes with drawbacks of a bit too constrained and custom designed underlying Linux environment and setup (not a familiar Debian family — no apt* based tools to install additional packages), and few other unexpected unnecessary annoyances, at least to my tastes. So I figured out a way to set up Jupyter Lab (a newer version of Jupyter Notebooks) in a way that achieves the similar (or actually even better) ease of use and cloud integration, and is less costly (by avoiding the mandatory additional persistent disk that comes with Datalab while actually not always necessary). I have preferred using Jupyter Lab over Datalab when working in otherwise Google Cloud environment ever since." }, { "code": null, "e": 3740, "s": 3587, "text": "If you are experienced with Jupyter Notebook and feel comfortable with Debian-like environments, then you might find the following instructions helpful." }, { "code": null, "e": 3919, "s": 3740, "text": "For the purpose of being scriptable/automatable, the following instructions rely on Google Cloud Shell command line, i.e. we avoid doing the same things via the Cloud Console UI." }, { "code": null, "e": 3996, "s": 3919, "text": "1. Create or select a cloud project where you want to deploy the Jupyter VM." }, { "code": null, "e": 4167, "s": 3996, "text": "2. Open the Google Cloud console and activate the Cloud Shell from the Cloud Console. You can do that from the toolbar button at to top right corner of the Cloud Console:" }, { "code": null, "e": 4407, "s": 4167, "text": "3. At the Cloud Shell command prompt, enter the following commands (adjust the project name, instance vm name, region and machine-type as you wish — rest of the options I’d recommend to leave as they are here, unless you know what you do):" }, { "code": null, "e": 4864, "s": 4407, "text": "PROJECT_NAME=my-project-name #change this to actual project nameVM_NAME=my-jupyterlabZONE=europe-west1-bMACHINE_TYPE=n1-standard-1gcloud compute --project=$PROJECT_NAME \\ instances create $VM_NAME \\ --zone=$ZONE \\ --machine-type=$MACHINE_TYPE \\ --maintenance-policy=MIGRATE \\ --image-family=debian-10 \\ --image-project=debian-cloud \\ --scopes=cloud-platformgcloud compute ssh my-jupyterlab --zone europe-west1-b" }, { "code": null, "e": 4978, "s": 4864, "text": "4. The last command above takes you to the newly created VM’s command prompt. Enter the following commands there:" }, { "code": null, "e": 5335, "s": 4978, "text": "sudo apt updatesudo apt upgrade # Hit 'Y' and Enter key when askedsudo apt install python3-pip # Hit 'Y' and Enter key when askedsudo pip3 install --upgrade jupyterlab google-api-python-clientsudo mkdir -p /opt/my_jupyterlab/binsudo sh -c \\ 'echo \"#!/bin/bash\" > /opt/my_jupyterlab/bin/run_jupyterlab'sudo chmod a+x /opt/my_jupyterlab/bin/run_jupyterlab" }, { "code": null, "e": 6229, "s": 5335, "text": "IMPORTANT!!! On the next command, --ip=127.0.0.1 is necessary for the security reasons, to block any external access attempt, especially as we are turning off the password and security token here to achieve usage convenience that is identical to Datalab. When you get more familiar with Google Cloud later and learn how to configure networking, then for an added security measure, you can turn off the external IP from the VM at all, and create a firewall setup so the VM would still be able to communicate with the outer world (needed for installing the packages and downloading datasets). However, to not over-complicate the current instructions with the firewall features, this is what already achieves the setup where you can access your notebooks through your GC account authentication, without extra password interaction by Jupyter, while not exposing your notebooks to the public world:" }, { "code": null, "e": 6452, "s": 6229, "text": "sudo sh -c 'echo \"jupyter lab \\\\ --ip=127.0.0.1 \\\\ --NotebookApp.token=\\\"\\\" \\\\ --NotebookApp.password=\\\"\\\" \\\\ --NotebookApp.allow_origin=\\\"*\\\"\" \\ >> /opt/my_jupyterlab/bin/run_jupyterlab'exit" }, { "code": null, "e": 6674, "s": 6452, "text": "5. The VM with JupyterLab is now provisioned and configured, and with the exit command at the end above you get back to the Cloud Shell command line. Let’s connect the dots that make the JupyterLab easy to launch and use:" }, { "code": null, "e": 6897, "s": 6674, "text": "echo \"\" >> .bashrcecho \"alias my_jupyterlab=\\\"gcloud compute ssh my-jupyterlab \\\\ --zone europe-west1-b \\\\ -- -L 8080:localhost:8888 -4 \\\\ '/opt/my_jupyterlab/bin/run_jupyterlab'\\\"\" \\ >> .bashrcexit" }, { "code": null, "e": 7066, "s": 6897, "text": "6. The exit command in the end above closes the Cloud Shell. Open the Cloud Shell again, and enter the following command to test the command line alias we just created:" }, { "code": null, "e": 7080, "s": 7066, "text": "my_jupyterlab" }, { "code": null, "e": 7649, "s": 7080, "text": "7. The last command above opens the ssh connection to the newly created VM, created the tunnel needed for the Cloud Console Web Preview feature, and launched the JupyterLab service inside the VM — you should see the JupyterLab’s log output on the Console Shell terminal output. If you hit Ctrl+C here and terminate the JupyterLab service, the connection gets closed and you’ll be back on the Console Shell command line prompt. But don’t do it (i.e. don’t hit the Ctrl+C — if you did, enter the above command again) yet, if you want the next step to succeed as well :)." }, { "code": null, "e": 7779, "s": 7649, "text": "8. To open the JupyterLab UI, click on the “Web Preview” button on the Cloud Shell toolbar, and then click “Preview on port 8080”" }, { "code": null, "e": 8185, "s": 7779, "text": "9. Voila! You are in JupyterLab! You have the Google Cloud’s python API installed (see the pip3 install --upgrade command above), and it has access to the Google Cloud services (see the --scopes=cloud-platform option at VM creation above). Your JupyterLab python environment is fully integrated with all the Google Cloud services and able to interact with these services the same way the Datalab would be." }, { "code": null, "e": 8537, "s": 8185, "text": "From here on, you can create and edit notebooks, interact with the underlying Debian platform (through the notebook command line magic or launch a Terminal from JupyterLab for that), or do whatever you feel comfortable to do in Debian based Jupyter environment. Add whatever packages you feel are necessary (apt install git; pip3 install pandas; etc)." }, { "code": null, "e": 8726, "s": 8537, "text": "Whenever you stop working with your notebooks, don’t forget to shut down the VM, to avoid unnecessary cloud costs. When you later return back to working on your notebooks do the following:" }, { "code": null, "e": 8746, "s": 8726, "text": "1. Relaunch the VM." }, { "code": null, "e": 8788, "s": 8746, "text": "2. Open the Cloud Console command prompt." }, { "code": null, "e": 8820, "s": 8788, "text": "3. Enter the following command:" }, { "code": null, "e": 8834, "s": 8820, "text": "my_jupyterlab" }, { "code": null, "e": 8938, "s": 8834, "text": "4. Click on the “Web Preview” button on the Cloud Shell toolbar, and then click “Preview on port 8080”." }, { "code": null, "e": 9860, "s": 8938, "text": "The default VM primary disk size is 10GB. I would recommend leaving it as it is and adding an additional persistent disk to the VM only when you need to work with bigger datasets. Having that extra space as an additional disk gives you the opportunity to drop and delete it (having those files you want to preserve backed up to Cloud Storage before deleting the disk) if you have finished your project. Persistent disks are a rather costly service at typical personal budget levels so it doesn’t make sense to just let them sit idle, having you to pay for them on a monthly basis. Also, due to the same cost reason, before creating another persistent disk, think a bit about how big disk you actually need. Datalab creates a 200GB disk for you by default (as of writing this, europe-west1 price for a regular 200GB SSD is €31.30/month), but maybe 25GB is already big enough for your current project at hand (€3.91/month)?" }, { "code": null, "e": 9936, "s": 9860, "text": "You can find the instructions for adding a persistent disk to VM from here." }, { "code": null, "e": 11007, "s": 9936, "text": "One thing that is specific to Google Cloud Web Preview based web UI tunneling, that might happen, is that you suddenly see the Jupyter web UI loses the connection to the Jupyter service (the same thing might happen to the Datalab as well, by the way). In such a case, go and check if your Cloud Shell is still connected, and reconnect it, if necessary. The reason in such case is that the Cloud Shell holds the tunnel, and if Cloud Shell somehow disconnects, it takes the tunnel with it, and causes the Jupyter web UI to lose the connection to the backend. If that disconnect happened due to a temporary network connectivity, then clicking on the “reconnect” link on the Cloud Shell toolbar might suffice to recover the JupyterLab connection without even losing the session state. But if the connection between Cloud Shell and Jupyter VM has been lost (i.e. it is not just the network connectivity issue between your browser and Google Cloud Console services), then you have to enter the my_jupyterlab command again from Cloud Shell, to launch the Jupyter service again." }, { "code": null, "e": 11499, "s": 11007, "text": "The above is enough to get you up and running with the Jupyter environment in Google Cloud. But to force you to think, practice some Google Cloud tinkering and strengthen your confidence with that environment, here are some bonus exercises, that result in making your life even easier, and that I suggest you try to solve on your own. Feel free to post the description of your solutions or questions you might get as a response below, and I will attempt to comment on them for your feedback." }, { "code": null, "e": 11827, "s": 11499, "text": "Make the launching of the Jupyter VM more convenient. Improve the my_jupyterlab Cloud Shell alias in the way, that it checks if the VM is already running — if not, then automatically launch the VM, wait for it to be up and ready, and launch Jupyter in it. This way you’ll eliminate the separate manual step of launching the VM." }, { "code": null, "e": 12125, "s": 11827, "text": "Improve the my_jupyterlab Cloud Shell alias in the way that after stopping the Jupyter service with ctrl+c it would offer you to stop the VM as well (with default action being stopping the VM) — this way you avoid unnecessary cloud costs incurring from accidentally forgetting to shut down the VM." }, { "code": null, "e": 12555, "s": 12125, "text": "Install the Cloud SDK into your local desktop or laptop machine, and try to achieve the setup where you can connect the ssh tunnel to the cloud-hosted Jupyter VM and launch the Jupyter service there from your local desktop or laptop, instead of using the Cloud Shell and Web Preview. This way you would eliminate another extra step from your everyday workflow (which is opening the cloud console and launching the Console Shell)." }, { "code": null, "e": 12915, "s": 12555, "text": "Automate the deployment of the new Jupyter VM, to avoid manually copy-pasting all the commands above every time you want to create one. This way you make your life even more flexible and agile if you want to maintain separate environments for different projects. There are several ways to do it. Here are a couple of ideas (pick your choice and implement it)." }, { "code": null, "e": 13040, "s": 12915, "text": "Ex. 4 option 1. Script everything in the above instructions so that it would all be triggered from one command line command." } ]
A Guide to the Pipe in R. R’s most important operator for data... | by Rory Spanton | Towards Data Science
Data analysis often involves many steps. A typical journey from raw data to results might involve filtering cases, transforming values, summarising data, and then running a statistical test. But how can we link all these steps together, while keeping our code efficient and readable? Enter the pipe, R’s most important operator for data processing. The pipe operator, written as %>%, has been a longstanding feature of the magrittr package for R. It takes the output of one function and passes it into another function as an argument. This allows us to link a sequence of analysis steps. To visualise this process, imagine a factory with different machines placed along a conveyor belt. Each machine is a function that performs a stage of our analysis, like filtering or transforming data. The pipe therefore works like a conveyor belt, transporting the output of one machine to another for further processing. We can see exactly how this works in a real example using the mtcars dataset. This dataset comes with base R, and contains data about the specs and fuel efficiency of various cars. The code below groups the data by the number of cylinders in each car, and then returns the mean miles-per-gallon of each group. Make sure to install the tidyverse suite of packages before running this code, since it includes both the pipe and the group_by and summarise functions. library(tidyverse)result <- mtcars %>% group_by(cyl) %>% summarise(meanMPG = mean(mpg)) The pipe operator feeds the mtcars dataframe into the group_by function, and then the output of group_by into summarise. The outcome of this process is stored in the tibble result, shown below. Although this example is very simple, it demonstrates the basic pipe workflow. To go even further, I’d encourage playing around with this. Perhaps swap and add new functions to the ‘pipeline’ to gain more insight into the data. Doing this is the best way to understand how to work with the pipe. But why should we use it in the first place? The pipe has a huge advantage over any other method of processing data in R: it makes processes easy to read. If we read %>% as “then”, the code from the previous section is very easy to digest as a set of instructions in plain English: Load tidyverse packagesTo get our result, take the mtcars dataframe, THEN Group its entries by number of cylinders, THEN Compute the mean miles-per-gallon of each group This is far more readable than if we were to express this process in another way. The two options below are different ways of expressing the previous code, but both are worse for a few reasons. # Option 1: Store each step in the process sequentiallyresult <- group_by(mtcars, cyl)result <- summarise(result, meanMPG = mean(mpg))# Option 2: chain the functions together> result <- summarise( group_by(mtcars, cyl), meanMPG = mean(mpg)) Option 1 gets the job done, but overwriting our output dataframe result in every line is problematic. For one, doing this for a procedure with lots of steps isn’t efficient and creates unnecessary repetition in the code. This repetition also makes it harder to identify exactly what is changing on each line in some cases. Option 2 is even less practical. Nesting each function we want to use gets ugly fast, especially for long procedures. It’s hard to read, and harder to debug. This approach also makes it tough to see the order of steps in the analysis, which is bad news if you want to add new functionality later. It’s easy to see how using the pipe can substantially improve most R scripts. It makes analyses more readable, removes repetition, and simplifies the process of adding and modifying code. Is there anything it can’t do? Although it’s immensely handy, the pipe isn’t useful in every situation. Here are a few of its limitations: Because it chains functions in a linear order, the pipe is less applicable to problems that include multidirectional relationships. The pipe can only transport one object at a time, meaning it’s not so suited to functions that need multiple inputs or produce multiple outputs. It doesn’t work with functions that use the current environment, nor functions that use lazy evaluation. Hadley Wickham’s book “R for Data Science” has a couple of examples of these. These things are to be expected. Just as you’d struggle to build a house with a single tool, no lone feature will solve all your programming problems. But for what it’s worth, the pipe is still pretty versatile. Although this piece focused on the basics, there’s plenty of scope for using the pipe in advanced or creative ways. I’ve used it in a variety of scripts, data-focused and not, and it’s made my life easier in each instance. Thanks for reading this far. As a reward, here are some bonus pipe tips and resources: Fed up of awkwardly typing %>%? The slightly easier keyboard shortcut CTRL + SHIFT + M will print a pipe in RStudio! Need style guidance about how to format pipes? Check out this helpful section from ‘R Style Guide’ by Hadley Wickham. Want to learn a bit more about the history of pipes in R? Check out this blog post from Adolfo Álvarez. The pipe is great. It turns your code into a list of readable instructions and has lots of other practical benefits. So now you know about the pipe, use it, and watch your code turn into a narrative.
[ { "code": null, "e": 521, "s": 172, "text": "Data analysis often involves many steps. A typical journey from raw data to results might involve filtering cases, transforming values, summarising data, and then running a statistical test. But how can we link all these steps together, while keeping our code efficient and readable? Enter the pipe, R’s most important operator for data processing." }, { "code": null, "e": 760, "s": 521, "text": "The pipe operator, written as %>%, has been a longstanding feature of the magrittr package for R. It takes the output of one function and passes it into another function as an argument. This allows us to link a sequence of analysis steps." }, { "code": null, "e": 1083, "s": 760, "text": "To visualise this process, imagine a factory with different machines placed along a conveyor belt. Each machine is a function that performs a stage of our analysis, like filtering or transforming data. The pipe therefore works like a conveyor belt, transporting the output of one machine to another for further processing." }, { "code": null, "e": 1546, "s": 1083, "text": "We can see exactly how this works in a real example using the mtcars dataset. This dataset comes with base R, and contains data about the specs and fuel efficiency of various cars. The code below groups the data by the number of cylinders in each car, and then returns the mean miles-per-gallon of each group. Make sure to install the tidyverse suite of packages before running this code, since it includes both the pipe and the group_by and summarise functions." }, { "code": null, "e": 1642, "s": 1546, "text": "library(tidyverse)result <- mtcars %>% group_by(cyl) %>% summarise(meanMPG = mean(mpg))" }, { "code": null, "e": 1836, "s": 1642, "text": "The pipe operator feeds the mtcars dataframe into the group_by function, and then the output of group_by into summarise. The outcome of this process is stored in the tibble result, shown below." }, { "code": null, "e": 2177, "s": 1836, "text": "Although this example is very simple, it demonstrates the basic pipe workflow. To go even further, I’d encourage playing around with this. Perhaps swap and add new functions to the ‘pipeline’ to gain more insight into the data. Doing this is the best way to understand how to work with the pipe. But why should we use it in the first place?" }, { "code": null, "e": 2414, "s": 2177, "text": "The pipe has a huge advantage over any other method of processing data in R: it makes processes easy to read. If we read %>% as “then”, the code from the previous section is very easy to digest as a set of instructions in plain English:" }, { "code": null, "e": 2589, "s": 2414, "text": "Load tidyverse packagesTo get our result, take the mtcars dataframe, THEN Group its entries by number of cylinders, THEN Compute the mean miles-per-gallon of each group" }, { "code": null, "e": 2783, "s": 2589, "text": "This is far more readable than if we were to express this process in another way. The two options below are different ways of expressing the previous code, but both are worse for a few reasons." }, { "code": null, "e": 3055, "s": 2783, "text": "# Option 1: Store each step in the process sequentiallyresult <- group_by(mtcars, cyl)result <- summarise(result, meanMPG = mean(mpg))# Option 2: chain the functions together> result <- summarise( group_by(mtcars, cyl), meanMPG = mean(mpg))" }, { "code": null, "e": 3378, "s": 3055, "text": "Option 1 gets the job done, but overwriting our output dataframe result in every line is problematic. For one, doing this for a procedure with lots of steps isn’t efficient and creates unnecessary repetition in the code. This repetition also makes it harder to identify exactly what is changing on each line in some cases." }, { "code": null, "e": 3675, "s": 3378, "text": "Option 2 is even less practical. Nesting each function we want to use gets ugly fast, especially for long procedures. It’s hard to read, and harder to debug. This approach also makes it tough to see the order of steps in the analysis, which is bad news if you want to add new functionality later." }, { "code": null, "e": 3894, "s": 3675, "text": "It’s easy to see how using the pipe can substantially improve most R scripts. It makes analyses more readable, removes repetition, and simplifies the process of adding and modifying code. Is there anything it can’t do?" }, { "code": null, "e": 4002, "s": 3894, "text": "Although it’s immensely handy, the pipe isn’t useful in every situation. Here are a few of its limitations:" }, { "code": null, "e": 4134, "s": 4002, "text": "Because it chains functions in a linear order, the pipe is less applicable to problems that include multidirectional relationships." }, { "code": null, "e": 4279, "s": 4134, "text": "The pipe can only transport one object at a time, meaning it’s not so suited to functions that need multiple inputs or produce multiple outputs." }, { "code": null, "e": 4462, "s": 4279, "text": "It doesn’t work with functions that use the current environment, nor functions that use lazy evaluation. Hadley Wickham’s book “R for Data Science” has a couple of examples of these." }, { "code": null, "e": 4897, "s": 4462, "text": "These things are to be expected. Just as you’d struggle to build a house with a single tool, no lone feature will solve all your programming problems. But for what it’s worth, the pipe is still pretty versatile. Although this piece focused on the basics, there’s plenty of scope for using the pipe in advanced or creative ways. I’ve used it in a variety of scripts, data-focused and not, and it’s made my life easier in each instance." }, { "code": null, "e": 4984, "s": 4897, "text": "Thanks for reading this far. As a reward, here are some bonus pipe tips and resources:" }, { "code": null, "e": 5101, "s": 4984, "text": "Fed up of awkwardly typing %>%? The slightly easier keyboard shortcut CTRL + SHIFT + M will print a pipe in RStudio!" }, { "code": null, "e": 5219, "s": 5101, "text": "Need style guidance about how to format pipes? Check out this helpful section from ‘R Style Guide’ by Hadley Wickham." }, { "code": null, "e": 5324, "s": 5219, "text": "Want to learn a bit more about the history of pipes in R? Check out this blog post from Adolfo Álvarez." } ]
Difference between Array and Array of Objects in JavaScript - GeeksforGeeks
02 Nov, 2021 In this article, we will see the differences between Array and Array of Objects in JavaScript. 1. Array: An Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive data types can be stored in an array. Example: Javascript <script> var myArr = [1, 2, 3, 4, 5]; // Iterating through loop for (var i = 0; i < myArr.length; i++) { console.log(myArr[i]); } // Pop an element from array myArr.pop(); console.log("after using pop()" + myArr);</script> Output: 2. Array of objects: It stores multiple values in a single variable. The object can contain anything in the real world such as person names, cars, game characters. Objects are very easy to use in some situations if you know where the data is being processed. The character set of objects are known as Properties. Properties of an object can be called by using DOT notation and [] notation. Example: Javascript <script> // Array of objects var myObject = { jhon: { name: 'jhon', age: 12, gender: 'male' }, rita: { name: 'rita', age: 32, gender: 'male' } }; // Using DOT notation console.log('using DOT:' + myObject.jhon.gender); // Using [] notation console.log('using []:' + myObject.rita['age']); // Using delete keyword delete myObject.rita; // Iterating using for..in loop for (var key in myObject) { // logs values in myObject console.log(myObject[key]); }</script> Output: Difference between Array and Array of objects: Array Array of objects Pushpender007 javascript-array JavaScript-Questions TrueGeek-2021 JavaScript TrueGeek Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to filter object array based on attributes? How to redirect to another page in ReactJS ? How to remove duplicate elements from JavaScript Array ? SQL Statement to Remove Part of a String Basics of API Testing Using Postman Types of Internet Protocols
[ { "code": null, "e": 25325, "s": 25297, "text": "\n02 Nov, 2021" }, { "code": null, "e": 25420, "s": 25325, "text": "In this article, we will see the differences between Array and Array of Objects in JavaScript." }, { "code": null, "e": 25761, "s": 25420, "text": "1. Array: An Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive data types can be stored in an array." }, { "code": null, "e": 25770, "s": 25761, "text": "Example:" }, { "code": null, "e": 25781, "s": 25770, "text": "Javascript" }, { "code": "<script> var myArr = [1, 2, 3, 4, 5]; // Iterating through loop for (var i = 0; i < myArr.length; i++) { console.log(myArr[i]); } // Pop an element from array myArr.pop(); console.log(\"after using pop()\" + myArr);</script>", "e": 26036, "s": 25781, "text": null }, { "code": null, "e": 26046, "s": 26038, "text": "Output:" }, { "code": null, "e": 26436, "s": 26046, "text": "2. Array of objects: It stores multiple values in a single variable. The object can contain anything in the real world such as person names, cars, game characters. Objects are very easy to use in some situations if you know where the data is being processed. The character set of objects are known as Properties. Properties of an object can be called by using DOT notation and [] notation." }, { "code": null, "e": 26445, "s": 26436, "text": "Example:" }, { "code": null, "e": 26456, "s": 26445, "text": "Javascript" }, { "code": "<script> // Array of objects var myObject = { jhon: { name: 'jhon', age: 12, gender: 'male' }, rita: { name: 'rita', age: 32, gender: 'male' } }; // Using DOT notation console.log('using DOT:' + myObject.jhon.gender); // Using [] notation console.log('using []:' + myObject.rita['age']); // Using delete keyword delete myObject.rita; // Iterating using for..in loop for (var key in myObject) { // logs values in myObject console.log(myObject[key]); }</script>", "e": 27072, "s": 26456, "text": null }, { "code": null, "e": 27080, "s": 27072, "text": "Output:" }, { "code": null, "e": 27127, "s": 27080, "text": "Difference between Array and Array of objects:" }, { "code": null, "e": 27133, "s": 27127, "text": "Array" }, { "code": null, "e": 27150, "s": 27133, "text": "Array of objects" }, { "code": null, "e": 27164, "s": 27150, "text": "Pushpender007" }, { "code": null, "e": 27181, "s": 27164, "text": "javascript-array" }, { "code": null, "e": 27202, "s": 27181, "text": "JavaScript-Questions" }, { "code": null, "e": 27216, "s": 27202, "text": "TrueGeek-2021" }, { "code": null, "e": 27227, "s": 27216, "text": "JavaScript" }, { "code": null, "e": 27236, "s": 27227, "text": "TrueGeek" }, { "code": null, "e": 27253, "s": 27236, "text": "Web Technologies" }, { "code": null, "e": 27351, "s": 27253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27412, "s": 27351, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27452, "s": 27412, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27493, "s": 27452, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27547, "s": 27493, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27595, "s": 27547, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27640, "s": 27595, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27697, "s": 27640, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 27738, "s": 27697, "text": "SQL Statement to Remove Part of a String" }, { "code": null, "e": 27774, "s": 27738, "text": "Basics of API Testing Using Postman" } ]
Measure text height on an HTML5 canvas element
To get the text height, set the font in pt − context.font="15pt Calibri"; Now, get the height like the following − var height = parseInt(context.font.match(/\d+/), 10); Above we have used a match to separate the font size from font face.
[ { "code": null, "e": 1107, "s": 1062, "text": "To get the text height, set the font in pt −" }, { "code": null, "e": 1136, "s": 1107, "text": "context.font=\"15pt Calibri\";" }, { "code": null, "e": 1177, "s": 1136, "text": "Now, get the height like the following −" }, { "code": null, "e": 1231, "s": 1177, "text": "var height = parseInt(context.font.match(/\\d+/), 10);" }, { "code": null, "e": 1300, "s": 1231, "text": "Above we have used a match to separate the font size from font face." } ]
How to get current formatted date dd/mm/yyyy in JavaScript ? - GeeksforGeeks
21 Jul, 2021 The task is to format the current date in dd/mm/yyyy format by using JavaScript. We’re going to discuss few methods.First few methods to know JavaScript getDate() Method:This method returns the day of the month (from 1 to 31) for the defined date.Syntax:Date.getDate() Return value:It returns a number, from 1 to 31, representing the day of the month. Date.getDate() Return value:It returns a number, from 1 to 31, representing the day of the month. JavaScript getFullYear() Method:This method returns the year (four digits for dates between year 1000 and 9999) of the defined date.Syntax:Date.getFullYear() Return value:It returns a number, representing the year of the defined date Date.getFullYear() Return value:It returns a number, representing the year of the defined date JavaScript getMonth() Method:This method returns the month (from 0 to 11) for the defined date, based on to local time.Syntax:Date.getMonth() Return value:It returns a number, from 0 to 11, representing the month. Date.getMonth() Return value:It returns a number, from 0 to 11, representing the month. JavaScript String slice() method:This method gets parts of a string and returns the extracted parts in a new string.It uses the start and end parameters to define the part of the string to extract.First character starts from position 0, the second has position 1, and so on.Syntax:string.slice(start, end) Parameters:start: This parameter is required. It specifies the position from where to start the extraction. First character is at position 0end: This parameter is optional. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position till the end of string.Return value:It returns a string, representing the extracted part of the string. string.slice(start, end) Parameters: start: This parameter is required. It specifies the position from where to start the extraction. First character is at position 0 end: This parameter is optional. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position till the end of string. Return value:It returns a string, representing the extracted part of the string. replace() method:This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue) Parameters:searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value.newvalue: This parameter is required. It specifies the value to replace the search value with.Return value:Returns a new string where the defines value(s) has been replaced by the new value. string.replace(searchVal, newvalue) Parameters: searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value. newvalue: This parameter is required. It specifies the value to replace the search value with. Return value:Returns a new string where the defines value(s) has been replaced by the new value. Example 1: This example format the date in dd/mm/yyyy by checking both date and month, If they are not in 2 digits the zero is added to make them 2 digits. <!DOCTYPE HTML><html> <head> <title> JavaScript | How to get current formatted date dd/mm/yyyy. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> get Date </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = today; var dd = today.getDate(); var mm = today.getMonth() + 1; var yyyy = today.getFullYear(); if (dd < 10) { dd = '0' + dd; } if (mm < 10) { mm = '0' + mm; } var today = dd + '/' + mm + '/' + yyyy; function gfg_Run() { el_down.innerHTML = today; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example first slice the date part from the date object and then format the date in dd/mm/yyyy. <!DOCTYPE HTML><html> <head> <title> JavaScript | How to get current formatted date dd/mm/yyyy. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> get Date </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = today; function gfg_Run() { var date = today.toJSON().slice(0, 10); var nDate = date.slice(8, 10) + '/' + date.slice(5, 7) + '/' + date.slice(0, 4); el_down.innerHTML = nDate; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. javascript-date JavaScript-Misc 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 Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request How to Use the JavaScript Fetch API to Get Data? 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": 24627, "s": 24599, "text": "\n21 Jul, 2021" }, { "code": null, "e": 24769, "s": 24627, "text": "The task is to format the current date in dd/mm/yyyy format by using JavaScript. We’re going to discuss few methods.First few methods to know" }, { "code": null, "e": 24979, "s": 24769, "text": "JavaScript getDate() Method:This method returns the day of the month (from 1 to 31) for the defined date.Syntax:Date.getDate()\nReturn value:It returns a number, from 1 to 31, representing the day of the month." }, { "code": null, "e": 24995, "s": 24979, "text": "Date.getDate()\n" }, { "code": null, "e": 25078, "s": 24995, "text": "Return value:It returns a number, from 1 to 31, representing the day of the month." }, { "code": null, "e": 25312, "s": 25078, "text": "JavaScript getFullYear() Method:This method returns the year (four digits for dates between year 1000 and 9999) of the defined date.Syntax:Date.getFullYear()\nReturn value:It returns a number, representing the year of the defined date" }, { "code": null, "e": 25332, "s": 25312, "text": "Date.getFullYear()\n" }, { "code": null, "e": 25408, "s": 25332, "text": "Return value:It returns a number, representing the year of the defined date" }, { "code": null, "e": 25622, "s": 25408, "text": "JavaScript getMonth() Method:This method returns the month (from 0 to 11) for the defined date, based on to local time.Syntax:Date.getMonth()\nReturn value:It returns a number, from 0 to 11, representing the month." }, { "code": null, "e": 25639, "s": 25622, "text": "Date.getMonth()\n" }, { "code": null, "e": 25711, "s": 25639, "text": "Return value:It returns a number, from 0 to 11, representing the month." }, { "code": null, "e": 26433, "s": 25711, "text": "JavaScript String slice() method:This method gets parts of a string and returns the extracted parts in a new string.It uses the start and end parameters to define the part of the string to extract.First character starts from position 0, the second has position 1, and so on.Syntax:string.slice(start, end)\nParameters:start: This parameter is required. It specifies the position from where to start the extraction. First character is at position 0end: This parameter is optional. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position till the end of string.Return value:It returns a string, representing the extracted part of the string." }, { "code": null, "e": 26459, "s": 26433, "text": "string.slice(start, end)\n" }, { "code": null, "e": 26471, "s": 26459, "text": "Parameters:" }, { "code": null, "e": 26601, "s": 26471, "text": "start: This parameter is required. It specifies the position from where to start the extraction. First character is at position 0" }, { "code": null, "e": 26797, "s": 26601, "text": "end: This parameter is optional. It specifies the position (excluding it) where to stop the extraction. If not used, slice() selects all characters from the start-position till the end of string." }, { "code": null, "e": 26878, "s": 26797, "text": "Return value:It returns a string, representing the extracted part of the string." }, { "code": null, "e": 27401, "s": 26878, "text": "replace() method:This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue)\nParameters:searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value.newvalue: This parameter is required. It specifies the value to replace the search value with.Return value:Returns a new string where the defines value(s) has been replaced by the new value." }, { "code": null, "e": 27438, "s": 27401, "text": "string.replace(searchVal, newvalue)\n" }, { "code": null, "e": 27450, "s": 27438, "text": "Parameters:" }, { "code": null, "e": 27579, "s": 27450, "text": "searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value." }, { "code": null, "e": 27674, "s": 27579, "text": "newvalue: This parameter is required. It specifies the value to replace the search value with." }, { "code": null, "e": 27771, "s": 27674, "text": "Return value:Returns a new string where the defines value(s) has been replaced by the new value." }, { "code": null, "e": 27927, "s": 27771, "text": "Example 1: This example format the date in dd/mm/yyyy by checking both date and month, If they are not in 2 digits the zero is added to make them 2 digits." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | How to get current formatted date dd/mm/yyyy. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> get Date </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = today; var dd = today.getDate(); var mm = today.getMonth() + 1; var yyyy = today.getFullYear(); if (dd < 10) { dd = '0' + dd; } if (mm < 10) { mm = '0' + mm; } var today = dd + '/' + mm + '/' + yyyy; function gfg_Run() { el_down.innerHTML = today; } </script></body> </html>", "e": 29020, "s": 27927, "text": null }, { "code": null, "e": 29028, "s": 29020, "text": "Output:" }, { "code": null, "e": 29059, "s": 29028, "text": "Before clicking on the button:" }, { "code": null, "e": 29089, "s": 29059, "text": "After clicking on the button:" }, { "code": null, "e": 29200, "s": 29089, "text": "Example 2: This example first slice the date part from the date object and then format the date in dd/mm/yyyy." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | How to get current formatted date dd/mm/yyyy. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> get Date </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = today; function gfg_Run() { var date = today.toJSON().slice(0, 10); var nDate = date.slice(8, 10) + '/' + date.slice(5, 7) + '/' + date.slice(0, 4); el_down.innerHTML = nDate; } </script></body> </html>", "e": 30207, "s": 29200, "text": null }, { "code": null, "e": 30215, "s": 30207, "text": "Output:" }, { "code": null, "e": 30246, "s": 30215, "text": "Before clicking on the button:" }, { "code": null, "e": 30276, "s": 30246, "text": "After clicking on the button:" }, { "code": null, "e": 30495, "s": 30276, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 30511, "s": 30495, "text": "javascript-date" }, { "code": null, "e": 30527, "s": 30511, "text": "JavaScript-Misc" }, { "code": null, "e": 30538, "s": 30527, "text": "JavaScript" }, { "code": null, "e": 30555, "s": 30538, "text": "Web Technologies" }, { "code": null, "e": 30653, "s": 30555, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30662, "s": 30653, "text": "Comments" }, { "code": null, "e": 30675, "s": 30662, "text": "Old Comments" }, { "code": null, "e": 30736, "s": 30675, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30781, "s": 30736, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30853, "s": 30781, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30894, "s": 30853, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30943, "s": 30894, "text": "How to Use the JavaScript Fetch API to Get Data?" }, { "code": null, "e": 30999, "s": 30943, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31032, "s": 30999, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31094, "s": 31032, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31137, "s": 31094, "text": "How to fetch data from an API in ReactJS ?" } ]
How to draw shapes using Graphics - onlinetutorialspoint
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, I am going to show you how to draw shapes using Graphics in Java. Graphics is an abstract base class for all graphics contexts. This class allows us to draw on components. For this example, I am going to draw Rectangles and Ovals on the JPanel component. drawRect() : This method allows us to draw a rectangle with a specific/given dimensions. drawOval() : This method allows us to draw oval with given dimensions. package com.onlinetutorialspoint.swing; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class DrawShapes extends JPanel { private int input; public DrawShapes(int choice) { input = choice; } public void paintComponent(Graphics g) { super.paintComponent(g); for (int i = 0; i < 10; i++) { switch (input) { case 1: g.drawRect(10+i*10, 10+i*10, 50+i*10, 50+i*10); break; case 2: g.drawOval(10+i*10, 10+i*10, 50+i*10, 50+i*10); break; } } } public static void main(String[] args) { String choice = JOptionPane.showInputDialog("Enter 1 to draw rectangles \n"+"Enter 2 to draw Ovals"); DrawShapes shapes = new DrawShapes(Integer.parseInt(choice)); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(shapes); frame.setSize(300, 300); frame.setVisible(true); } } Output : Draw Rectangles : Selecting Ovals : Draw Ovals : Happy Learning 🙂 Java Graphics2D Class Example How to create Java Smiley Swing How to create Java Rainbow using Swing Java Swing JOptionPane Example Java Swing BorderFactory Example How to use Java JSlider Example Java Swing JSplitPane Example Java Swing JTabbedPane Example Java Swing JOptionPane Html Content Example Java Swing Login Example Java JColorChooser Example Java Swing ProgressBar Example Java Swing JTable Example Java Swing JList Example Java Swing JLabel Example Java Graphics2D Class Example How to create Java Smiley Swing How to create Java Rainbow using Swing Java Swing JOptionPane Example Java Swing BorderFactory Example How to use Java JSlider Example Java Swing JSplitPane Example Java Swing JTabbedPane Example Java Swing JOptionPane Html Content Example Java Swing Login Example Java JColorChooser Example Java Swing ProgressBar Example Java Swing JTable Example Java Swing JList Example Java Swing JLabel Example Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "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": 589, "s": 398, "text": "In this tutorial, I am going to show you how to draw shapes using Graphics in Java. Graphics is an abstract base class for all graphics contexts. This class allows us to draw on components." }, { "code": null, "e": 672, "s": 589, "text": "For this example, I am going to draw Rectangles and Ovals on the JPanel component." }, { "code": null, "e": 761, "s": 672, "text": "drawRect() : This method allows us to draw a rectangle with a specific/given dimensions." }, { "code": null, "e": 832, "s": 761, "text": "drawOval() : This method allows us to draw oval with given dimensions." }, { "code": null, "e": 1933, "s": 832, "text": "package com.onlinetutorialspoint.swing;\n\nimport java.awt.Graphics;\n\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\n\npublic class DrawShapes extends JPanel {\n private int input;\n\n public DrawShapes(int choice) {\n input = choice;\n }\n\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n for (int i = 0; i < 10; i++) {\n switch (input) {\n case 1:\n g.drawRect(10+i*10, 10+i*10, 50+i*10, 50+i*10);\n break;\n case 2:\n g.drawOval(10+i*10, 10+i*10, 50+i*10, 50+i*10);\n break;\n }\n }\n }\n public static void main(String[] args) {\n String choice = JOptionPane.showInputDialog(\"Enter 1 to draw rectangles \\n\"+\"Enter 2 to draw Ovals\");\n DrawShapes shapes = new DrawShapes(Integer.parseInt(choice));\n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(shapes);\n frame.setSize(300, 300);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 1942, "s": 1933, "text": "Output :" }, { "code": null, "e": 1960, "s": 1942, "text": "Draw Rectangles :" }, { "code": null, "e": 1978, "s": 1960, "text": "Selecting Ovals :" }, { "code": null, "e": 1991, "s": 1978, "text": "Draw Ovals :" }, { "code": null, "e": 2008, "s": 1991, "text": "Happy Learning 🙂" }, { "code": null, "e": 2472, "s": 2008, "text": "\nJava Graphics2D Class Example\nHow to create Java Smiley Swing\nHow to create Java Rainbow using Swing\nJava Swing JOptionPane Example\nJava Swing BorderFactory Example\nHow to use Java JSlider Example\nJava Swing JSplitPane Example\nJava Swing JTabbedPane Example\nJava Swing JOptionPane Html Content Example\nJava Swing Login Example\nJava JColorChooser Example\nJava Swing ProgressBar Example\nJava Swing JTable Example\nJava Swing JList Example\nJava Swing JLabel Example\n" }, { "code": null, "e": 2502, "s": 2472, "text": "Java Graphics2D Class Example" }, { "code": null, "e": 2534, "s": 2502, "text": "How to create Java Smiley Swing" }, { "code": null, "e": 2573, "s": 2534, "text": "How to create Java Rainbow using Swing" }, { "code": null, "e": 2604, "s": 2573, "text": "Java Swing JOptionPane Example" }, { "code": null, "e": 2637, "s": 2604, "text": "Java Swing BorderFactory Example" }, { "code": null, "e": 2669, "s": 2637, "text": "How to use Java JSlider Example" }, { "code": null, "e": 2699, "s": 2669, "text": "Java Swing JSplitPane Example" }, { "code": null, "e": 2730, "s": 2699, "text": "Java Swing JTabbedPane Example" }, { "code": null, "e": 2774, "s": 2730, "text": "Java Swing JOptionPane Html Content Example" }, { "code": null, "e": 2799, "s": 2774, "text": "Java Swing Login Example" }, { "code": null, "e": 2826, "s": 2799, "text": "Java JColorChooser Example" }, { "code": null, "e": 2857, "s": 2826, "text": "Java Swing ProgressBar Example" }, { "code": null, "e": 2883, "s": 2857, "text": "Java Swing JTable Example" }, { "code": null, "e": 2908, "s": 2883, "text": "Java Swing JList Example" }, { "code": null, "e": 2934, "s": 2908, "text": "Java Swing JLabel Example" }, { "code": null, "e": 2940, "s": 2938, "text": "Δ" }, { "code": null, "e": 2964, "s": 2940, "text": " Install Java on Mac OS" }, { "code": null, "e": 2992, "s": 2964, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 3021, "s": 2992, "text": " Install Minikube on Windows" }, { "code": null, "e": 3056, "s": 3021, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 3083, "s": 3056, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 3110, "s": 3083, "text": " Install Gradle on Windows" }, { "code": null, "e": 3139, "s": 3110, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 3165, "s": 3139, "text": " Install PuTTY on windows" }, { "code": null, "e": 3191, "s": 3165, "text": " Install Mysql on Windows" }, { "code": null, "e": 3227, "s": 3191, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 3261, "s": 3227, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 3287, "s": 3261, "text": " Install Maven on Windows" }, { "code": null, "e": 3312, "s": 3287, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 3346, "s": 3312, "text": " Install Maven on Windows Command" }, { "code": null, "e": 3381, "s": 3346, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 3405, "s": 3381, "text": " Install Ant on Windows" }, { "code": null, "e": 3434, "s": 3405, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 3466, "s": 3434, "text": " Install Apache Kafka on Ubuntu" }, { "code": null, "e": 3499, "s": 3466, "text": " Install Apache Kafka on Windows" }, { "code": null, "e": 3524, "s": 3499, "text": " Java8 – Install Windows" }, { "code": null, "e": 3541, "s": 3524, "text": " Java8 – foreach" }, { "code": null, "e": 3569, "s": 3541, "text": " Java8 – forEach with index" }, { "code": null, "e": 3600, "s": 3569, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 3632, "s": 3600, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 3652, "s": 3632, "text": " Java8 – GroupingBy" }, { "code": null, "e": 3672, "s": 3652, "text": " Java8 – SummingInt" }, { "code": null, "e": 3696, "s": 3672, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 3726, "s": 3696, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 3758, "s": 3726, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 3794, "s": 3758, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 3838, "s": 3794, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 3870, "s": 3838, "text": " Howto – Convert List to String" }, { "code": null, "e": 3911, "s": 3870, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 3948, "s": 3911, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 3988, "s": 3948, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 4017, "s": 3988, "text": " Howto – Convert List to Map" }, { "code": null, "e": 4049, "s": 4017, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 4069, "s": 4049, "text": " Howto – Sort a Map" }, { "code": null, "e": 4091, "s": 4069, "text": " Howto – Filter a Map" }, { "code": null, "e": 4121, "s": 4091, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 4172, "s": 4121, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 4208, "s": 4172, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 4240, "s": 4208, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 4275, "s": 4240, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 4298, "s": 4275, "text": " Howto – Merge Streams" }, { "code": null, "e": 4345, "s": 4298, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 4370, "s": 4345, "text": " Howto -Get Stream count" }, { "code": null, "e": 4414, "s": 4370, "text": " Howto – Get Min and Max values in a Stream" } ]
React.js useImperativeHandle Additional Hook - GeeksforGeeks
17 Mar, 2021 The useImperativeHandle hook works in the similar phase of useRef hook but only it allows us to modify the instance that is going to be passed with the ref object which provides a reference to any DOM element. Although this hook is used in rare cases, it has some most advanced functionality. Syntax: useImperativeHandle(ref, createHandle, [deps]) Creating React Application: Step 1: Create a React application using the following command.npx create-react-app functiondemo Step 1: Create a React application using the following command. npx create-react-app functiondemo Step 2: After creating your project folder i.e. functiondemo, move to it using the following command.cd functiondemo Step 2: After creating your project folder i.e. functiondemo, move to it using the following command. cd functiondemo Project Structure: It will look like the following. Project Structure Example: In this example, we are going to build a custom input button which on being in focus performs the custom user-defined. It is our custom input field which we will import in App.js file. Input.js import React, { useRef, useImperativeHandle, forwardRef } from 'react'; function Input(props, ref) { const btn = useRef(); useImperativeHandle(ref, () => ({ focus: () => { console.log('Input is in focus'); }, })); return <input ref={btn} {...props} placeholder="type here" />;} export default forwardRef(Input); App.js import React, { useRef } from 'react';import Input from './Input'; const App = () => { const inputRef = useRef(null); return ( <div> <Input onFocus={() => inputRef.current.focus()} ref={inputRef} /> </div> );}; export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Reference:https://reactjs.org/docs/hooks-reference.html#useimperativehandle React-Hooks ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? How to create a multi-page website using React.js ? ReactJS useNavigate() Hook 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 insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24397, "s": 24369, "text": "\n17 Mar, 2021" }, { "code": null, "e": 24690, "s": 24397, "text": "The useImperativeHandle hook works in the similar phase of useRef hook but only it allows us to modify the instance that is going to be passed with the ref object which provides a reference to any DOM element. Although this hook is used in rare cases, it has some most advanced functionality." }, { "code": null, "e": 24698, "s": 24690, "text": "Syntax:" }, { "code": null, "e": 24745, "s": 24698, "text": "useImperativeHandle(ref, createHandle, [deps])" }, { "code": null, "e": 24773, "s": 24745, "text": "Creating React Application:" }, { "code": null, "e": 24870, "s": 24773, "text": "Step 1: Create a React application using the following command.npx create-react-app functiondemo" }, { "code": null, "e": 24934, "s": 24870, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 24968, "s": 24934, "text": "npx create-react-app functiondemo" }, { "code": null, "e": 25085, "s": 24968, "text": "Step 2: After creating your project folder i.e. functiondemo, move to it using the following command.cd functiondemo" }, { "code": null, "e": 25187, "s": 25085, "text": "Step 2: After creating your project folder i.e. functiondemo, move to it using the following command." }, { "code": null, "e": 25203, "s": 25187, "text": "cd functiondemo" }, { "code": null, "e": 25255, "s": 25203, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25273, "s": 25255, "text": "Project Structure" }, { "code": null, "e": 25467, "s": 25273, "text": "Example: In this example, we are going to build a custom input button which on being in focus performs the custom user-defined. It is our custom input field which we will import in App.js file." }, { "code": null, "e": 25476, "s": 25467, "text": "Input.js" }, { "code": "import React, { useRef, useImperativeHandle, forwardRef } from 'react'; function Input(props, ref) { const btn = useRef(); useImperativeHandle(ref, () => ({ focus: () => { console.log('Input is in focus'); }, })); return <input ref={btn} {...props} placeholder=\"type here\" />;} export default forwardRef(Input);", "e": 25805, "s": 25476, "text": null }, { "code": null, "e": 25812, "s": 25805, "text": "App.js" }, { "code": "import React, { useRef } from 'react';import Input from './Input'; const App = () => { const inputRef = useRef(null); return ( <div> <Input onFocus={() => inputRef.current.focus()} ref={inputRef} /> </div> );}; export default App;", "e": 26065, "s": 25812, "text": null }, { "code": null, "e": 26178, "s": 26065, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 26188, "s": 26178, "text": "npm start" }, { "code": null, "e": 26196, "s": 26188, "text": "Output:" }, { "code": null, "e": 26272, "s": 26196, "text": "Reference:https://reactjs.org/docs/hooks-reference.html#useimperativehandle" }, { "code": null, "e": 26284, "s": 26272, "text": "React-Hooks" }, { "code": null, "e": 26292, "s": 26284, "text": "ReactJS" }, { "code": null, "e": 26309, "s": 26292, "text": "Web Technologies" }, { "code": null, "e": 26407, "s": 26309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26416, "s": 26407, "text": "Comments" }, { "code": null, "e": 26429, "s": 26416, "text": "Old Comments" }, { "code": null, "e": 26471, "s": 26429, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 26506, "s": 26471, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 26564, "s": 26506, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 26616, "s": 26564, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 26643, "s": 26616, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 26699, "s": 26643, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26732, "s": 26699, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26794, "s": 26732, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26844, "s": 26794, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python Program to Replace Specific Line in File - GeeksforGeeks
14 Sep, 2021 In this article, we are going to write a Python program to replace specific lines in the file. We will first open the file in read-only mode and read all the lines using readlines(), creating a list of lines storing it in a variable. We will make the necessary changes to a specific line and after that, we open the file in write-only mode and write the modified data using writelines(). File for demonstration: First, open the File in read-only mode and read the file line by line using readlines() method, and store it in a variable. with open('example.txt','r',encoding='utf-8') as file: data = file.readlines() The variable will contain a list of lines, Printing it will show all the lines present inside the list. print(data) Make necessary changes to a specific line. (Here, I have modified the second line) data[1] = "Here is my modified Line 2\n" Open the file again in write-only mode and write the modified data using writelines() method. With open('example.txt', 'w', encoding='utf-8') as file: file.writelines(data) Python3 with open('example.txt', 'r', encoding='utf-8') as file: data = file.readlines() print(data)data[1] = "Here is my modified Line 2\n" with open('example.txt', 'w', encoding='utf-8') as file: file.writelines(data) Output: ['Line 1\n', 'Here is my modified Line 2\n', 'Line 3'] After Modification: Blogathon-2021 Picked Python file-handling-programs Blogathon Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Import JSON Data into SQL Server? How to Install Tkinter in Windows? SQL - Multiple Column Ordering How to pass data into table from a form using React Components How to Create a Table With Multiple Foreign Keys in SQL? Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24421, "s": 24393, "text": "\n14 Sep, 2021" }, { "code": null, "e": 24516, "s": 24421, "text": "In this article, we are going to write a Python program to replace specific lines in the file." }, { "code": null, "e": 24809, "s": 24516, "text": "We will first open the file in read-only mode and read all the lines using readlines(), creating a list of lines storing it in a variable. We will make the necessary changes to a specific line and after that, we open the file in write-only mode and write the modified data using writelines()." }, { "code": null, "e": 24833, "s": 24809, "text": "File for demonstration:" }, { "code": null, "e": 24957, "s": 24833, "text": "First, open the File in read-only mode and read the file line by line using readlines() method, and store it in a variable." }, { "code": null, "e": 25040, "s": 24957, "text": "with open('example.txt','r',encoding='utf-8') as file:\n data = file.readlines()" }, { "code": null, "e": 25144, "s": 25040, "text": "The variable will contain a list of lines, Printing it will show all the lines present inside the list." }, { "code": null, "e": 25156, "s": 25144, "text": "print(data)" }, { "code": null, "e": 25239, "s": 25156, "text": "Make necessary changes to a specific line. (Here, I have modified the second line)" }, { "code": null, "e": 25280, "s": 25239, "text": "data[1] = \"Here is my modified Line 2\\n\"" }, { "code": null, "e": 25374, "s": 25280, "text": "Open the file again in write-only mode and write the modified data using writelines() method." }, { "code": null, "e": 25457, "s": 25374, "text": "With open('example.txt', 'w', encoding='utf-8') as file:\n file.writelines(data)" }, { "code": null, "e": 25465, "s": 25457, "text": "Python3" }, { "code": "with open('example.txt', 'r', encoding='utf-8') as file: data = file.readlines() print(data)data[1] = \"Here is my modified Line 2\\n\" with open('example.txt', 'w', encoding='utf-8') as file: file.writelines(data)", "e": 25685, "s": 25465, "text": null }, { "code": null, "e": 25693, "s": 25685, "text": "Output:" }, { "code": null, "e": 25748, "s": 25693, "text": "['Line 1\\n', 'Here is my modified Line 2\\n', 'Line 3']" }, { "code": null, "e": 25768, "s": 25748, "text": "After Modification:" }, { "code": null, "e": 25783, "s": 25768, "text": "Blogathon-2021" }, { "code": null, "e": 25790, "s": 25783, "text": "Picked" }, { "code": null, "e": 25820, "s": 25790, "text": "Python file-handling-programs" }, { "code": null, "e": 25830, "s": 25820, "text": "Blogathon" }, { "code": null, "e": 25837, "s": 25830, "text": "Python" }, { "code": null, "e": 25935, "s": 25837, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25944, "s": 25935, "text": "Comments" }, { "code": null, "e": 25957, "s": 25944, "text": "Old Comments" }, { "code": null, "e": 25998, "s": 25957, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 26033, "s": 25998, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 26064, "s": 26033, "text": "SQL - Multiple Column Ordering" }, { "code": null, "e": 26127, "s": 26064, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 26184, "s": 26127, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 26212, "s": 26184, "text": "Read JSON file using Python" }, { "code": null, "e": 26262, "s": 26212, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26284, "s": 26262, "text": "Python map() function" } ]
How to install and import Python modules at runtime?
You can use pip to install packages at runtime and importlib.import_module(moduleName) to import module by using its name as a string. For example, import pip import importlib def import_with_auto_install(package): try: return importlib.import_module(package) except ImportError: pip.main(['install', package]) return importlib.import_module(package) # Example if __name__ == '__main__': scrapy = import_with_auto_install('scrapy') print(scrapy) The above script installs the scrapy module and imports it when installation of the module completes.
[ { "code": null, "e": 1210, "s": 1062, "text": "You can use pip to install packages at runtime and importlib.import_module(moduleName) to import module by using its name as a string. For example," }, { "code": null, "e": 1544, "s": 1210, "text": "import pip\nimport importlib\ndef import_with_auto_install(package):\n try:\n return importlib.import_module(package)\n except ImportError:\n pip.main(['install', package])\n return importlib.import_module(package)\n# Example\nif __name__ == '__main__':\n scrapy = import_with_auto_install('scrapy')\n print(scrapy)" }, { "code": null, "e": 1646, "s": 1544, "text": "The above script installs the scrapy module and imports it when installation of the module completes." } ]
Scrape Table from Website using Python - Selenium - GeeksforGeeks
03 Mar, 2021 Selenium is the automation software testing tool that obtains the website, performs various actions, or obtains the data from the website. It was chiefly developed for easing the testing work by automating the web applications. Nowadays, apart from being used for testing, it can also be used for making tedious work interesting. Do you know that with the help of Selenium, you can also extract data from the table on the website? The answer is Yes, we can easily scrap the table data from the website. What you need to do in order to scrape table data from the website is explained in this article. Let us consider the simple HTML program containing tables only to understand the approach of scraping the table from the website. HTML <!DOCTYPE html><html> <head> <title>Selenium Table</title> </head> <body> <table border="1"> <thead> <tr> <th>Name</th> <th>Class</th> </tr> </thead> <tbody> <tr> <td>Vinayak</td> <td>12</td> </tr> <tr> <td>Ishita</td> <td>10</td> </tr> </tbody> </table> </body></html> Once you have created the HTML file, you can follow the below steps and extract data from the table from the website on your own. First, declare the web driver driver=webdriver.Chrome(executable_path=”Declare the path where web driver is installed”) Now, open the website from which you want to obtain table data driver.get("Specify the path of the website") Next, you need to find rows in the table rows=1+len(driver.find_elements_by_xpath("Specify the altered path")) Here, the altered xpath means that if xpath of the row 1 is /html/body/table/tbody/tr[1] then, altered xpath will be /html/body/table/tbody/tr What needs to be done here is to remove the index value of table row. NOTE: Remember to add 1 to the row’s value for the table header as it was not included while calculating the table rows. Further, find columns in the table cols=len(driver.find_elements_by_xpath("Specify the altered path")) Here, the altered xpath means that if xpath of the column showing output Vinayak is /html/body/table/tbody/tr[1]/td[1] then, altered xpath will be /html/body/table/tbody/tr/td What needs to be done here is to remove the index value of table row and table data. Moreover, obtain data from each column of the table body for r in range(2, rows+1): for p in range(1, cols+1): value = driver.find_element_by_xpath("Specify the altered path").text Here, the altered xpath means that if xpath of the column showing output Vinayak is /html/body/table/tbody/tr[1]/td[1] then, altered xpath will be /html/body/table/tbody/tr[“+str(r)+”]/td[“+str(p)+”] What needs to be done here is to add the str(r) and str(p) for the index value of table row and table data respectively. Finally, print data of the table print(value, end=' ') print() As we have now seen the approach to be followed to extract the table data while using the automation tool Selenium. Now, let’s see the complete example for the scrapping table data from the website. We will use this website to extract its table data in the given below program. Python # Python program to scrape table from website # import libraries selenium and timefrom selenium import webdriverfrom time import sleep # Create webdriver objectdriver = webdriver.Chrome( executable_path="C:\selenium\chromedriver_win32\chromedriver.exe") # Get the websitedriver.get( "https://www.geeksforgeeks.org/find_element_by_link_text-driver-method-selenium-python/") # Make Python sleep for some timesleep(2) # Obtain the number of rows in bodyrows = 1+len(driver.find_elements_by_xpath( "/html/body/div[3]/div[2]/div/div[1]/div/div/div/article/div[3]/div/table/tbody/tr")) # Obtain the number of columns in tablecols = len(driver.find_elements_by_xpath( "/html/body/div[3]/div[2]/div/div[1]/div/div/div/article/div[3]/div/table/tbody/tr[1]/td")) # Print rows and columnsprint(rows)print(cols) # Printing the table headersprint("Locators "+" Description") # Printing the data of the tablefor r in range(2, rows+1): for p in range(1, cols+1): # obtaining the text from each column of the table value = driver.find_element_by_xpath( "/html/body/div[3]/div[2]/div/div[1]/div/div/div/article/div[3]/div/table/tbody/tr["+str(r)+"]/td["+str(p)+"]").text print(value, end=' ') print() Further, run the python code using: python run.py Output: Picked Python Selenium-Exercises Python-selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n03 Mar, 2021" }, { "code": null, "e": 24501, "s": 23901, "text": "Selenium is the automation software testing tool that obtains the website, performs various actions, or obtains the data from the website. It was chiefly developed for easing the testing work by automating the web applications. Nowadays, apart from being used for testing, it can also be used for making tedious work interesting. Do you know that with the help of Selenium, you can also extract data from the table on the website? The answer is Yes, we can easily scrap the table data from the website. What you need to do in order to scrape table data from the website is explained in this article." }, { "code": null, "e": 24631, "s": 24501, "text": "Let us consider the simple HTML program containing tables only to understand the approach of scraping the table from the website." }, { "code": null, "e": 24636, "s": 24631, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Selenium Table</title> </head> <body> <table border=\"1\"> <thead> <tr> <th>Name</th> <th>Class</th> </tr> </thead> <tbody> <tr> <td>Vinayak</td> <td>12</td> </tr> <tr> <td>Ishita</td> <td>10</td> </tr> </tbody> </table> </body></html>", "e": 25071, "s": 24636, "text": null }, { "code": null, "e": 25201, "s": 25071, "text": "Once you have created the HTML file, you can follow the below steps and extract data from the table from the website on your own." }, { "code": null, "e": 25231, "s": 25201, "text": "First, declare the web driver" }, { "code": null, "e": 25321, "s": 25231, "text": "driver=webdriver.Chrome(executable_path=”Declare the path where web driver is installed”)" }, { "code": null, "e": 25384, "s": 25321, "text": "Now, open the website from which you want to obtain table data" }, { "code": null, "e": 25430, "s": 25384, "text": "driver.get(\"Specify the path of the website\")" }, { "code": null, "e": 25471, "s": 25430, "text": "Next, you need to find rows in the table" }, { "code": null, "e": 25541, "s": 25471, "text": "rows=1+len(driver.find_elements_by_xpath(\"Specify the altered path\"))" }, { "code": null, "e": 25755, "s": 25541, "text": "Here, the altered xpath means that if xpath of the row 1 is /html/body/table/tbody/tr[1] then, altered xpath will be /html/body/table/tbody/tr What needs to be done here is to remove the index value of table row. " }, { "code": null, "e": 25876, "s": 25755, "text": "NOTE: Remember to add 1 to the row’s value for the table header as it was not included while calculating the table rows." }, { "code": null, "e": 25911, "s": 25876, "text": "Further, find columns in the table" }, { "code": null, "e": 25979, "s": 25911, "text": "cols=len(driver.find_elements_by_xpath(\"Specify the altered path\"))" }, { "code": null, "e": 26240, "s": 25979, "text": "Here, the altered xpath means that if xpath of the column showing output Vinayak is /html/body/table/tbody/tr[1]/td[1] then, altered xpath will be /html/body/table/tbody/tr/td What needs to be done here is to remove the index value of table row and table data." }, { "code": null, "e": 26297, "s": 26240, "text": "Moreover, obtain data from each column of the table body" }, { "code": null, "e": 26437, "s": 26297, "text": "for r in range(2, rows+1):\n for p in range(1, cols+1):\n value = driver.find_element_by_xpath(\"Specify the altered path\").text" }, { "code": null, "e": 26758, "s": 26437, "text": "Here, the altered xpath means that if xpath of the column showing output Vinayak is /html/body/table/tbody/tr[1]/td[1] then, altered xpath will be /html/body/table/tbody/tr[“+str(r)+”]/td[“+str(p)+”] What needs to be done here is to add the str(r) and str(p) for the index value of table row and table data respectively." }, { "code": null, "e": 26791, "s": 26758, "text": "Finally, print data of the table" }, { "code": null, "e": 26833, "s": 26791, "text": "print(value, end=' ') \n print() " }, { "code": null, "e": 27111, "s": 26833, "text": "As we have now seen the approach to be followed to extract the table data while using the automation tool Selenium. Now, let’s see the complete example for the scrapping table data from the website. We will use this website to extract its table data in the given below program." }, { "code": null, "e": 27118, "s": 27111, "text": "Python" }, { "code": "# Python program to scrape table from website # import libraries selenium and timefrom selenium import webdriverfrom time import sleep # Create webdriver objectdriver = webdriver.Chrome( executable_path=\"C:\\selenium\\chromedriver_win32\\chromedriver.exe\") # Get the websitedriver.get( \"https://www.geeksforgeeks.org/find_element_by_link_text-driver-method-selenium-python/\") # Make Python sleep for some timesleep(2) # Obtain the number of rows in bodyrows = 1+len(driver.find_elements_by_xpath( \"/html/body/div[3]/div[2]/div/div[1]/div/div/div/article/div[3]/div/table/tbody/tr\")) # Obtain the number of columns in tablecols = len(driver.find_elements_by_xpath( \"/html/body/div[3]/div[2]/div/div[1]/div/div/div/article/div[3]/div/table/tbody/tr[1]/td\")) # Print rows and columnsprint(rows)print(cols) # Printing the table headersprint(\"Locators \"+\" Description\") # Printing the data of the tablefor r in range(2, rows+1): for p in range(1, cols+1): # obtaining the text from each column of the table value = driver.find_element_by_xpath( \"/html/body/div[3]/div[2]/div/div[1]/div/div/div/article/div[3]/div/table/tbody/tr[\"+str(r)+\"]/td[\"+str(p)+\"]\").text print(value, end=' ') print()", "e": 28397, "s": 27118, "text": null }, { "code": null, "e": 28433, "s": 28397, "text": "Further, run the python code using:" }, { "code": null, "e": 28447, "s": 28433, "text": "python run.py" }, { "code": null, "e": 28455, "s": 28447, "text": "Output:" }, { "code": null, "e": 28462, "s": 28455, "text": "Picked" }, { "code": null, "e": 28488, "s": 28462, "text": "Python Selenium-Exercises" }, { "code": null, "e": 28504, "s": 28488, "text": "Python-selenium" }, { "code": null, "e": 28511, "s": 28504, "text": "Python" }, { "code": null, "e": 28609, "s": 28511, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28618, "s": 28609, "text": "Comments" }, { "code": null, "e": 28631, "s": 28618, "text": "Old Comments" }, { "code": null, "e": 28663, "s": 28631, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28719, "s": 28663, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28761, "s": 28719, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28803, "s": 28761, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28839, "s": 28803, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 28861, "s": 28839, "text": "Defaultdict in Python" }, { "code": null, "e": 28900, "s": 28861, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28927, "s": 28900, "text": "Python Classes and Objects" }, { "code": null, "e": 28958, "s": 28927, "text": "Python | os.path.join() method" } ]
Java Concurrency - AtomicLong Class
A java.util.concurrent.atomic.AtomicLong class provides operations on underlying long value that can be read and written atomically, and also contains advanced atomic operations. AtomicLong supports atomic operations on underlying long variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features. Following is the list of important methods available in the AtomicLong class. public long addAndGet(long delta) Atomically adds the given value to the current value. public boolean compareAndSet(long expect, long update) Atomically sets the value to the given updated value if the current value is same as the expected value. public long decrementAndGet() Atomically decrements by one the current value. public double doubleValue() Returns the value of the specified number as a double. public float floatValue() Returns the value of the specified number as a float. public long get() Gets the current value. public long getAndAdd(long delta) Atomiclly adds the given value to the current value. public long getAndDecrement() Atomically decrements by one the current value. public long getAndIncrement() Atomically increments by one the current value. public long getAndSet(long newValue) Atomically sets to the given value and returns the old value. public long incrementAndGet() Atomically increments by one the current value. public int intValue() Returns the value of the specified number as an int. public void lazySet(long newValue) Eventually sets to the given value. public long longValue() Returns the value of the specified number as a long. public void set(long newValue) Sets to the given value. public String toString() Returns the String representation of the current value. public boolean weakCompareAndSet(long expect, long update) Atomically sets the value to the given updated value if the current value is same as the expected value. The following TestThread program shows a safe implementation of counter using AtomicLong in thread based environment. import java.util.concurrent.atomic.AtomicLong; public class TestThread { static class Counter { private AtomicLong c = new AtomicLong(0); public void increment() { c.getAndIncrement(); } public long value() { return c.get(); } } public static void main(final String[] arguments) throws InterruptedException { final Counter counter = new Counter(); //1000 threads for(int i = 0; i < 1000 ; i++) { new Thread(new Runnable() { public void run() { counter.increment(); } }).start(); } Thread.sleep(6000); System.out.println("Final number (should be 1000): " + counter.value()); } } This will produce the following result. Final number (should be 1000): 1000 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 3157, "s": 2657, "text": "A java.util.concurrent.atomic.AtomicLong class provides operations on underlying long value that can be read and written atomically, and also contains advanced atomic operations. AtomicLong supports atomic operations on underlying long variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features." }, { "code": null, "e": 3235, "s": 3157, "text": "Following is the list of important methods available in the AtomicLong class." }, { "code": null, "e": 3269, "s": 3235, "text": "public long addAndGet(long delta)" }, { "code": null, "e": 3323, "s": 3269, "text": "Atomically adds the given value to the current value." }, { "code": null, "e": 3378, "s": 3323, "text": "public boolean compareAndSet(long expect, long update)" }, { "code": null, "e": 3483, "s": 3378, "text": "Atomically sets the value to the given updated value if the current value is same as the expected value." }, { "code": null, "e": 3513, "s": 3483, "text": "public long decrementAndGet()" }, { "code": null, "e": 3561, "s": 3513, "text": "Atomically decrements by one the current value." }, { "code": null, "e": 3589, "s": 3561, "text": "public double doubleValue()" }, { "code": null, "e": 3644, "s": 3589, "text": "Returns the value of the specified number as a double." }, { "code": null, "e": 3670, "s": 3644, "text": "public float floatValue()" }, { "code": null, "e": 3724, "s": 3670, "text": "Returns the value of the specified number as a float." }, { "code": null, "e": 3742, "s": 3724, "text": "public long get()" }, { "code": null, "e": 3766, "s": 3742, "text": "Gets the current value." }, { "code": null, "e": 3800, "s": 3766, "text": "public long getAndAdd(long delta)" }, { "code": null, "e": 3853, "s": 3800, "text": "Atomiclly adds the given value to the current value." }, { "code": null, "e": 3883, "s": 3853, "text": "public long getAndDecrement()" }, { "code": null, "e": 3931, "s": 3883, "text": "Atomically decrements by one the current value." }, { "code": null, "e": 3961, "s": 3931, "text": "public long getAndIncrement()" }, { "code": null, "e": 4010, "s": 3961, "text": "\nAtomically increments by one the current value." }, { "code": null, "e": 4047, "s": 4010, "text": "public long getAndSet(long newValue)" }, { "code": null, "e": 4109, "s": 4047, "text": "Atomically sets to the given value and returns the old value." }, { "code": null, "e": 4139, "s": 4109, "text": "public long incrementAndGet()" }, { "code": null, "e": 4187, "s": 4139, "text": "Atomically increments by one the current value." }, { "code": null, "e": 4209, "s": 4187, "text": "public int intValue()" }, { "code": null, "e": 4262, "s": 4209, "text": "Returns the value of the specified number as an int." }, { "code": null, "e": 4297, "s": 4262, "text": "public void lazySet(long newValue)" }, { "code": null, "e": 4333, "s": 4297, "text": "Eventually sets to the given value." }, { "code": null, "e": 4357, "s": 4333, "text": "public long longValue()" }, { "code": null, "e": 4410, "s": 4357, "text": "Returns the value of the specified number as a long." }, { "code": null, "e": 4441, "s": 4410, "text": "public void set(long newValue)" }, { "code": null, "e": 4466, "s": 4441, "text": "Sets to the given value." }, { "code": null, "e": 4491, "s": 4466, "text": "public String toString()" }, { "code": null, "e": 4547, "s": 4491, "text": "Returns the String representation of the current value." }, { "code": null, "e": 4606, "s": 4547, "text": "public boolean weakCompareAndSet(long expect, long update)" }, { "code": null, "e": 4711, "s": 4606, "text": "Atomically sets the value to the given updated value if the current value is same as the expected value." }, { "code": null, "e": 4829, "s": 4711, "text": "The following TestThread program shows a safe implementation of counter using AtomicLong in thread based environment." }, { "code": null, "e": 5606, "s": 4829, "text": "import java.util.concurrent.atomic.AtomicLong;\n\npublic class TestThread {\n\n static class Counter {\n private AtomicLong c = new AtomicLong(0);\n\n public void increment() {\n c.getAndIncrement();\n }\n\n public long value() {\n return c.get();\n }\n }\n\n public static void main(final String[] arguments) throws InterruptedException {\n final Counter counter = new Counter();\n \n //1000 threads\n for(int i = 0; i < 1000 ; i++) {\n \n new Thread(new Runnable() {\n \n public void run() {\n counter.increment();\n }\n }).start();\t\n }\n Thread.sleep(6000);\t\t\t \t\t \n System.out.println(\"Final number (should be 1000): \" + counter.value());\n }\n}" }, { "code": null, "e": 5646, "s": 5606, "text": "This will produce the following result." }, { "code": null, "e": 5683, "s": 5646, "text": "Final number (should be 1000): 1000\n" }, { "code": null, "e": 5716, "s": 5683, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5732, "s": 5716, "text": " Malhar Lathkar" }, { "code": null, "e": 5765, "s": 5732, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5781, "s": 5765, "text": " Malhar Lathkar" }, { "code": null, "e": 5816, "s": 5781, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5830, "s": 5816, "text": " Anadi Sharma" }, { "code": null, "e": 5864, "s": 5830, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5878, "s": 5864, "text": " Tushar Kale" }, { "code": null, "e": 5915, "s": 5878, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5930, "s": 5915, "text": " Monica Mittal" }, { "code": null, "e": 5963, "s": 5930, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5982, "s": 5963, "text": " Arnab Chakraborty" }, { "code": null, "e": 5989, "s": 5982, "text": " Print" }, { "code": null, "e": 6000, "s": 5989, "text": " Add Notes" } ]
Finding the elements of nth row of Pascal's triangle in JavaScript
Pascal's triangle is a triangular array constructed by summing adjacent elements in preceding rows. The first few elements of Pascals triangle are − We are required to write a JavaScript function that takes in a positive number, say num as the only argument. The function should return an array of all the elements that must be present in the pascal's triangle in the (num)th row. For example − If the input number is − const num = 9; Then the output should be − const output = [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]; Following is the code − const num = 9; const pascalRow = (num) => { const res = [] while (res.length <= num) { res.unshift(1); for(let i = 1; i < res.length - 1; i++) { res[i] += res[i + 1]; }; }; return res }; console.log(pascalRow(num)); Following is the console output − [ 1, 9, 36, 84, 126, 126, 84, 36, 9, 1 ]
[ { "code": null, "e": 1162, "s": 1062, "text": "Pascal's triangle is a triangular array constructed by summing adjacent elements in preceding\nrows." }, { "code": null, "e": 1211, "s": 1162, "text": "The first few elements of Pascals triangle are −" }, { "code": null, "e": 1321, "s": 1211, "text": "We are required to write a JavaScript function that takes in a positive number, say num as the\nonly argument." }, { "code": null, "e": 1443, "s": 1321, "text": "The function should return an array of all the elements that must be present in the pascal's\ntriangle in the (num)th row." }, { "code": null, "e": 1457, "s": 1443, "text": "For example −" }, { "code": null, "e": 1482, "s": 1457, "text": "If the input number is −" }, { "code": null, "e": 1497, "s": 1482, "text": "const num = 9;" }, { "code": null, "e": 1525, "s": 1497, "text": "Then the output should be −" }, { "code": null, "e": 1580, "s": 1525, "text": "const output = [1, 9, 36, 84, 126, 126, 84, 36, 9, 1];" }, { "code": null, "e": 1604, "s": 1580, "text": "Following is the code −" }, { "code": null, "e": 1859, "s": 1604, "text": "const num = 9;\nconst pascalRow = (num) => {\n const res = []\n while (res.length <= num) {\n res.unshift(1);\n for(let i = 1; i < res.length - 1; i++) {\n res[i] += res[i + 1];\n };\n };\n return res\n};\nconsole.log(pascalRow(num));" }, { "code": null, "e": 1893, "s": 1859, "text": "Following is the console output −" }, { "code": null, "e": 1940, "s": 1893, "text": "[\n 1, 9, 36, 84, 126,\n 126, 84, 36, 9, 1\n]" } ]
Python Pillow - Cropping an Image
Cropping is one of the important operations of the image processing to remove unwanted portions of an image as well as to add required features to an image. It is widely used process in web applications, for uploading an image. The crop() function of the image class in Pillow requires the portion to be cropped as rectangle. The rectangle portion to be cropped from an image is specified as a four-element tuple and returns the rectangle portion of the image that has been cropped as an image Object. Following example demonstrates how to rotate an image using python pillow − #Import required Image library from PIL import Image #Create an Image Object from an Image im = Image.open('images/elephant.jpg') #Display actual image im.show() #left, upper, right, lowe #Crop cropped = im.crop((1,2,300,300)) #Display the cropped portion cropped.show() #Save the cropped image cropped.save('images/croppedBeach1.jpg') If you save the above program as Example.py and execute, it displays the original and cropped images using standard PNG display utility, as follows − Original image Cropped image 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": 2428, "s": 2200, "text": "Cropping is one of the important operations of the image processing to remove unwanted portions of an image as well as to add required features to an image. It is widely used process in web applications, for uploading an image." }, { "code": null, "e": 2702, "s": 2428, "text": "The crop() function of the image class in Pillow requires the portion to be cropped as rectangle. The rectangle portion to be cropped from an image is specified as a four-element tuple and returns the rectangle portion of the image that has been cropped as an image Object." }, { "code": null, "e": 2778, "s": 2702, "text": "Following example demonstrates how to rotate an image using python pillow −" }, { "code": null, "e": 3119, "s": 2778, "text": "#Import required Image library\nfrom PIL import Image\n\n#Create an Image Object from an Image\nim = Image.open('images/elephant.jpg')\n\n#Display actual image\nim.show()\n\n#left, upper, right, lowe\n#Crop\ncropped = im.crop((1,2,300,300))\n\n#Display the cropped portion\ncropped.show()\n\n#Save the cropped image\ncropped.save('images/croppedBeach1.jpg')" }, { "code": null, "e": 3269, "s": 3119, "text": "If you save the above program as Example.py and execute, it displays the original and cropped images using standard PNG display utility, as follows −" }, { "code": null, "e": 3286, "s": 3269, "text": "Original image\n\n" }, { "code": null, "e": 3302, "s": 3286, "text": "Cropped image\n\n" }, { "code": null, "e": 3339, "s": 3302, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3355, "s": 3339, "text": " Malhar Lathkar" }, { "code": null, "e": 3388, "s": 3355, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3407, "s": 3388, "text": " Arnab Chakraborty" }, { "code": null, "e": 3442, "s": 3407, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3464, "s": 3442, "text": " In28Minutes Official" }, { "code": null, "e": 3498, "s": 3464, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3526, "s": 3498, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3561, "s": 3526, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3575, "s": 3561, "text": " Lets Kode It" }, { "code": null, "e": 3608, "s": 3575, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3625, "s": 3608, "text": " Abhilash Nelson" }, { "code": null, "e": 3632, "s": 3625, "text": " Print" }, { "code": null, "e": 3643, "s": 3632, "text": " Add Notes" } ]
Python has a built-in Logo Turtle, and it’s great for reinforcement learning | by Tom Grek | Towards Data Science
A little while ago I was teaching a Berkeley class on data analytics, and one of the exercises had students go through the Python stdlib to find interesting modules. I went through the docs too and was delighted to find that Python has a turtle! Do you remember? FORWARD 10LEFT 90 My high school in the 90s was not rich enough to have a robotic turtle with a pen built in (tiny violins start playing) but I remember being entranced by the on-screen movements of the magical creature, which I think at the time was running on an Acorn Archimedes, an early product from today’s chip giant ARM. I never needed a Spirograph, as the turtle amply took its place in the production of mathematical mandalas. I’ve written about reinforcement learning before here and here: it’s a topic I’m particularly interested in, as it provides a path forward to AGI (the singularity), while at the same time really exposing today’s limitations of deep learning and AI. I wanted to create an agent that taught itself to keep moving about on the screen as long as possible: avoiding the edges of the screen, and also avoiding bumping into itself (in the style of the old Snake game). Intuitively, this should lead to the turtle coiling around itself. I quickly found a sad problem with Python’s built in turtle: it draws to a Tkinter canvas (just think of it as ‘some object’ if you haven’t done GUI development in Python before — like me!) and there’s no way to read back the pixels from that canvas. So, I implemented my own turtle library, which wraps the built-in one (still using it to draw to screen), but also keeps a NumPy array of the canvas available (as well as a specified number of previous frames, which is useful for RL). It provides a few other functions convenient for RL, you can grab the library at my Github here. The final code I used to make this project is in the examples folder of that repo. Here’s the env.step() function I built. You can see that there are 3 possible actions, two end-game situations (turtle went off screen or back over its tail), a cumulative reward given at the end of an episode (moving forward yields higher rewards), and an immediate reward for the action (each action gets 1 reward). The earlier articles provide a lot more background, but the principle is really rather simple: An agent makes an action in an environment, and receives a reward. The reward is made out of two parts: an immediate, aka dense, reward (“the agent ate an apple”), and a deferred, aka sparse, reward (“the agent ate 10 apples and won the game”). The agent’s critic part compares its expectation of a reward (given the state of the environment and the action it took; those expectations start out random) with the actual reward it received. The closer they align, the better: this means it’s usable as a loss signal. The deferred reward (multiplied by some discount factor for each step from now until the end of the game) is added to earlier rewards , so that the agent has an idea at each timestep of whether its action at that timestep led ultimately to a good reward or not. This is actor-critic RL, because there are essentially two agents: an actor, and a critic. We implement them with a single neural network that has two heads. The actor network has a number of outputs corresponding to the number of possible actions; the chosen action is the softmax of that. (The activations, or values, of each neuron at the output layer is interpreted as a probability — softmax makes sure that with 3 possible actions, the max activation of each neuron is 0.33 — so it’s easy to pick the one with the highest value). Not only is the critic head learning to get better at estimating rewards, but the action head is learning to get better at actions, too: Added to the loss signal is a term that increases when unlikely actions yield high rewards, and decreases as the certainty of an action increases. In general, actions yielding rewards should become more certain over time. Because both the action loss and the value loss are lumped together as ‘loss’ (and who can say whether they are going in the same direction or not?), and because there isn’t much difference in the actor and critic networks — clearly it’s going to take a lot of data (iterations, epochs, episodes, playthroughs) to get convergence. There last important factor is to encourage exploration vs exploitation, that is to say, avoiding local minima. There are a few ways to do this which are combined in the agent I made: Epsilon greedy (choose a random action sometimes with a decreasing probability epsilon over time — when that probability decreases exponentially we say ‘annealing’ instead of decreasing, in case you were wondering) Perturb the reward signals coming from the environment by a random amount It’s very unlikely that any of the neural net’s outputs will get to 1.0 probability. Instead of just choosing the action corresponding to the max output each time, sample from its probability distribution. Dropout in the neural network adds inherent randomness. Each of these methods leads to the need for more training cycles, but they do lead to a smarter agent. Luckily, in this kind of game-playing RL there is no shortage of data; the agent can play as long as we let it. The agent I made was really dull and basic in the end: two convolutional layers, a couple of fully connected layers with different nonlinearities, and the aforementioned two heads comprised of linear layers. As input to the network, I made a stack of the current frame/canvas, plus the two previous frames. (Each frame would differ by just a single pixel and/or the orientation of the turtle). As you may know if you’ve read my writing before, I won’t claim that making this RL turtle was easy. Some things I learned: As always, reward design (both immediate and at end-of-game) is difficult, finicky, and not entirely intuitive. More noise and sources of entropy really help in the exploration phase. Don’t assume that one is enough. It’s not enough for the action head and the value head just to comprise a single linear layer. Two layers for each head, with a non-linearity in-between, worked much better when bolted on to the main ‘body’ of the network. RL easily can plateau. Often there’s not much difference between the losses after five minutes training, and five hours. Injecting signals like ‘last_action’ into later layers of the network (bypassing the convolutional layer and attempting to provide the network with some useful time-dependent context) don’t necessarily help. Randomizing the start position and angle of the turtle made the problem much more complex. I thought it would help the agent learn generalization, but at least in the training time I gave it, it slowed convergence a lot. A 200x200 grid, most of which is kind of sparse (not much going on), with only a single pixel line thickness, and not much difference between the 3 time-sequenced frames I provided to the network, resulted in quite slow learning. Instead of learning a hard and fast rule never to go off the boundaries of the screen, the agent I made gets better at avoiding it, over time, as the probabilities of it turning left or right near the edge get higher. It has no common sense! It’s hard to say the agent has learned anything at all. How then do you crystallize learned or partly-learned probability distributions into actual rules? This could give a much more effective agent, that could also learn vastly quicker. And how about rules that can be broken sometimes, or outright unlearning some rules when they are no longer useful? And then of course there is the classic RL problem that nothing the agent has learned here would be useful in, for example, a game of Space Invaders. And that the agent has no concept of a turtle and its trail and the edge of a screen, just a bunch of tensors that it tirelessly multiplies over and over and adjusts based on some derivative. And that the reward signal is hand coded, surely playing as long as possible should be a decent reward in and of itself. Why hasn’t anyone yet found a way to intrinsically motivate AIs? AGI is coming but we still have to solve massive engineering and philosophical challenges. The humble Python turtle continues to give me a fun test-bed for that. Thank you for reading! I love talking with people about AGI, and specifically how we build stuff to get there from where we are now, so please get in touch if you like. There’s more to come :)
[ { "code": null, "e": 435, "s": 172, "text": "A little while ago I was teaching a Berkeley class on data analytics, and one of the exercises had students go through the Python stdlib to find interesting modules. I went through the docs too and was delighted to find that Python has a turtle! Do you remember?" }, { "code": null, "e": 453, "s": 435, "text": "FORWARD 10LEFT 90" }, { "code": null, "e": 872, "s": 453, "text": "My high school in the 90s was not rich enough to have a robotic turtle with a pen built in (tiny violins start playing) but I remember being entranced by the on-screen movements of the magical creature, which I think at the time was running on an Acorn Archimedes, an early product from today’s chip giant ARM. I never needed a Spirograph, as the turtle amply took its place in the production of mathematical mandalas." }, { "code": null, "e": 1121, "s": 872, "text": "I’ve written about reinforcement learning before here and here: it’s a topic I’m particularly interested in, as it provides a path forward to AGI (the singularity), while at the same time really exposing today’s limitations of deep learning and AI." }, { "code": null, "e": 1334, "s": 1121, "text": "I wanted to create an agent that taught itself to keep moving about on the screen as long as possible: avoiding the edges of the screen, and also avoiding bumping into itself (in the style of the old Snake game)." }, { "code": null, "e": 1401, "s": 1334, "text": "Intuitively, this should lead to the turtle coiling around itself." }, { "code": null, "e": 1652, "s": 1401, "text": "I quickly found a sad problem with Python’s built in turtle: it draws to a Tkinter canvas (just think of it as ‘some object’ if you haven’t done GUI development in Python before — like me!) and there’s no way to read back the pixels from that canvas." }, { "code": null, "e": 2067, "s": 1652, "text": "So, I implemented my own turtle library, which wraps the built-in one (still using it to draw to screen), but also keeps a NumPy array of the canvas available (as well as a specified number of previous frames, which is useful for RL). It provides a few other functions convenient for RL, you can grab the library at my Github here. The final code I used to make this project is in the examples folder of that repo." }, { "code": null, "e": 2385, "s": 2067, "text": "Here’s the env.step() function I built. You can see that there are 3 possible actions, two end-game situations (turtle went off screen or back over its tail), a cumulative reward given at the end of an episode (moving forward yields higher rewards), and an immediate reward for the action (each action gets 1 reward)." }, { "code": null, "e": 2480, "s": 2385, "text": "The earlier articles provide a lot more background, but the principle is really rather simple:" }, { "code": null, "e": 2547, "s": 2480, "text": "An agent makes an action in an environment, and receives a reward." }, { "code": null, "e": 2725, "s": 2547, "text": "The reward is made out of two parts: an immediate, aka dense, reward (“the agent ate an apple”), and a deferred, aka sparse, reward (“the agent ate 10 apples and won the game”)." }, { "code": null, "e": 2995, "s": 2725, "text": "The agent’s critic part compares its expectation of a reward (given the state of the environment and the action it took; those expectations start out random) with the actual reward it received. The closer they align, the better: this means it’s usable as a loss signal." }, { "code": null, "e": 3257, "s": 2995, "text": "The deferred reward (multiplied by some discount factor for each step from now until the end of the game) is added to earlier rewards , so that the agent has an idea at each timestep of whether its action at that timestep led ultimately to a good reward or not." }, { "code": null, "e": 3415, "s": 3257, "text": "This is actor-critic RL, because there are essentially two agents: an actor, and a critic. We implement them with a single neural network that has two heads." }, { "code": null, "e": 3793, "s": 3415, "text": "The actor network has a number of outputs corresponding to the number of possible actions; the chosen action is the softmax of that. (The activations, or values, of each neuron at the output layer is interpreted as a probability — softmax makes sure that with 3 possible actions, the max activation of each neuron is 0.33 — so it’s easy to pick the one with the highest value)." }, { "code": null, "e": 3930, "s": 3793, "text": "Not only is the critic head learning to get better at estimating rewards, but the action head is learning to get better at actions, too:" }, { "code": null, "e": 4152, "s": 3930, "text": "Added to the loss signal is a term that increases when unlikely actions yield high rewards, and decreases as the certainty of an action increases. In general, actions yielding rewards should become more certain over time." }, { "code": null, "e": 4483, "s": 4152, "text": "Because both the action loss and the value loss are lumped together as ‘loss’ (and who can say whether they are going in the same direction or not?), and because there isn’t much difference in the actor and critic networks — clearly it’s going to take a lot of data (iterations, epochs, episodes, playthroughs) to get convergence." }, { "code": null, "e": 4667, "s": 4483, "text": "There last important factor is to encourage exploration vs exploitation, that is to say, avoiding local minima. There are a few ways to do this which are combined in the agent I made:" }, { "code": null, "e": 4882, "s": 4667, "text": "Epsilon greedy (choose a random action sometimes with a decreasing probability epsilon over time — when that probability decreases exponentially we say ‘annealing’ instead of decreasing, in case you were wondering)" }, { "code": null, "e": 4956, "s": 4882, "text": "Perturb the reward signals coming from the environment by a random amount" }, { "code": null, "e": 5162, "s": 4956, "text": "It’s very unlikely that any of the neural net’s outputs will get to 1.0 probability. Instead of just choosing the action corresponding to the max output each time, sample from its probability distribution." }, { "code": null, "e": 5218, "s": 5162, "text": "Dropout in the neural network adds inherent randomness." }, { "code": null, "e": 5433, "s": 5218, "text": "Each of these methods leads to the need for more training cycles, but they do lead to a smarter agent. Luckily, in this kind of game-playing RL there is no shortage of data; the agent can play as long as we let it." }, { "code": null, "e": 5641, "s": 5433, "text": "The agent I made was really dull and basic in the end: two convolutional layers, a couple of fully connected layers with different nonlinearities, and the aforementioned two heads comprised of linear layers." }, { "code": null, "e": 5827, "s": 5641, "text": "As input to the network, I made a stack of the current frame/canvas, plus the two previous frames. (Each frame would differ by just a single pixel and/or the orientation of the turtle)." }, { "code": null, "e": 5951, "s": 5827, "text": "As you may know if you’ve read my writing before, I won’t claim that making this RL turtle was easy. Some things I learned:" }, { "code": null, "e": 6063, "s": 5951, "text": "As always, reward design (both immediate and at end-of-game) is difficult, finicky, and not entirely intuitive." }, { "code": null, "e": 6168, "s": 6063, "text": "More noise and sources of entropy really help in the exploration phase. Don’t assume that one is enough." }, { "code": null, "e": 6391, "s": 6168, "text": "It’s not enough for the action head and the value head just to comprise a single linear layer. Two layers for each head, with a non-linearity in-between, worked much better when bolted on to the main ‘body’ of the network." }, { "code": null, "e": 6512, "s": 6391, "text": "RL easily can plateau. Often there’s not much difference between the losses after five minutes training, and five hours." }, { "code": null, "e": 6720, "s": 6512, "text": "Injecting signals like ‘last_action’ into later layers of the network (bypassing the convolutional layer and attempting to provide the network with some useful time-dependent context) don’t necessarily help." }, { "code": null, "e": 6941, "s": 6720, "text": "Randomizing the start position and angle of the turtle made the problem much more complex. I thought it would help the agent learn generalization, but at least in the training time I gave it, it slowed convergence a lot." }, { "code": null, "e": 7171, "s": 6941, "text": "A 200x200 grid, most of which is kind of sparse (not much going on), with only a single pixel line thickness, and not much difference between the 3 time-sequenced frames I provided to the network, resulted in quite slow learning." }, { "code": null, "e": 7469, "s": 7171, "text": "Instead of learning a hard and fast rule never to go off the boundaries of the screen, the agent I made gets better at avoiding it, over time, as the probabilities of it turning left or right near the edge get higher. It has no common sense! It’s hard to say the agent has learned anything at all." }, { "code": null, "e": 7767, "s": 7469, "text": "How then do you crystallize learned or partly-learned probability distributions into actual rules? This could give a much more effective agent, that could also learn vastly quicker. And how about rules that can be broken sometimes, or outright unlearning some rules when they are no longer useful?" }, { "code": null, "e": 8295, "s": 7767, "text": "And then of course there is the classic RL problem that nothing the agent has learned here would be useful in, for example, a game of Space Invaders. And that the agent has no concept of a turtle and its trail and the edge of a screen, just a bunch of tensors that it tirelessly multiplies over and over and adjusts based on some derivative. And that the reward signal is hand coded, surely playing as long as possible should be a decent reward in and of itself. Why hasn’t anyone yet found a way to intrinsically motivate AIs?" }, { "code": null, "e": 8457, "s": 8295, "text": "AGI is coming but we still have to solve massive engineering and philosophical challenges. The humble Python turtle continues to give me a fun test-bed for that." } ]
What is the difference between ++i and i++ in C++?
There is a big distinction between the suffix and prefix versions of ++. In the prefix version (i.e., ++i), the value of i is incremented, and the value of the expression is the new value of i. So basically it first increments then assigns a value to the expression. In the postfix version (i.e., i++), the value of i is incremented, but the value of the expression is the original value of i. So basically it first assigns a value to expression and then increments the variable. Let's look at some code to get a better understanding − #include<iostream> using namespace std; int main() { int x = 3, y, z; y = x++; z = ++x; cout << x << ", " << y << ", " << z; return 0; } This would give us the output − 5, 3, 5 Why is this? Let's look at it in detail − Initialize x to 3 Assign y the value we get by evaluating the expression x++, ie, the value of x before increment then increment x. Increment x then assign z the value we get by evaluating the expression ++x, ie, value of x after the increment. Print these values
[ { "code": null, "e": 1135, "s": 1062, "text": "There is a big distinction between the suffix and prefix versions of ++." }, { "code": null, "e": 1329, "s": 1135, "text": "In the prefix version (i.e., ++i), the value of i is incremented, and the value of the expression is the new value of i. So basically it first increments then assigns a value to the expression." }, { "code": null, "e": 1579, "s": 1329, "text": "In the postfix version (i.e., i++), the value of i is incremented, but the value of the expression is the original value of i. So basically it first assigns a value to expression and then increments the variable. " }, { "code": null, "e": 1635, "s": 1579, "text": "Let's look at some code to get a better understanding −" }, { "code": null, "e": 1787, "s": 1635, "text": "#include<iostream>\nusing namespace std;\nint main() {\n int x = 3, y, z;\n y = x++;\n z = ++x;\n cout << x << \", \" << y << \", \" << z;\n return 0;\n}" }, { "code": null, "e": 1819, "s": 1787, "text": "This would give us the output −" }, { "code": null, "e": 1827, "s": 1819, "text": "5, 3, 5" }, { "code": null, "e": 1869, "s": 1827, "text": "Why is this? Let's look at it in detail −" }, { "code": null, "e": 1888, "s": 1869, "text": " Initialize x to 3" }, { "code": null, "e": 2003, "s": 1888, "text": " Assign y the value we get by evaluating the expression x++, ie, the value of x before increment then increment x." }, { "code": null, "e": 2117, "s": 2003, "text": " Increment x then assign z the value we get by evaluating the expression ++x, ie, value of x after the increment." }, { "code": null, "e": 2137, "s": 2117, "text": " Print these values" } ]
Creating First REST API with FastAPI - GeeksforGeeks
05 Sep, 2020 FastAPI :FastAPI is modern Web Framework . It is used for building API and is very easy to learn . Features of FastAPI : High Performance than many Web Frameworks, faster than Node.js, etc . Easy to Develop API’s Production Ready Well Documentation to learn code fast Swagger UI to form API Documentation Avoid Redundancy of Code Easy Testing Support for GraphQL, Background Fetching, Dependency Injection CREATING REST API USING FastAPI : Install Python 3 and pip/pip3 according to your Operating System Now, install fastapi using pip or pip3 : pip install fastapi pip install fastapi Install the uvicorn which is the Asynchronous Gateway Interface for your Server using : pip install uvicorn pip install uvicorn Now create a main.py file and import fastapi, also create a server from fastapi import FastAPI app = FastAPI() from fastapi import FastAPI app = FastAPI() Now, let’s add the code for sample get request as shown below : @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/") def read_root(): return {"Hello": "World"} Hence, the main.py file will look like :from fastapi import FastAPIapp = FastAPI() @app.get("/")def first_example(): """ GFG Example First Fast API Example """ return {"GFG Example": "FastAPI"} from fastapi import FastAPIapp = FastAPI() @app.get("/")def first_example(): """ GFG Example First Fast API Example """ return {"GFG Example": "FastAPI"} Now, start the server usinguvicorn main:app --reload uvicorn main:app --reload Now open the browser and open http://localhost:8000/docs or http://127.0.0.1:8000/docsYou will be able to see the Swagger UI Home page as below : Expand the “First Example” : Now try to Execute the API, you will get the success status with 200 code .The Response will be {“GFG Example”: “FastAPI”} as shown below : Programming Language Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction of Object Oriented Programming 5 Best Languages for Competitive Programming R - Matrices 7 Highest Paying Programming Languages For Freelancers in 2022 R - Data Types Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25981, "s": 25953, "text": "\n05 Sep, 2020" }, { "code": null, "e": 26080, "s": 25981, "text": "FastAPI :FastAPI is modern Web Framework . It is used for building API and is very easy to learn ." }, { "code": null, "e": 26102, "s": 26080, "text": "Features of FastAPI :" }, { "code": null, "e": 26172, "s": 26102, "text": "High Performance than many Web Frameworks, faster than Node.js, etc ." }, { "code": null, "e": 26194, "s": 26172, "text": "Easy to Develop API’s" }, { "code": null, "e": 26211, "s": 26194, "text": "Production Ready" }, { "code": null, "e": 26249, "s": 26211, "text": "Well Documentation to learn code fast" }, { "code": null, "e": 26286, "s": 26249, "text": "Swagger UI to form API Documentation" }, { "code": null, "e": 26311, "s": 26286, "text": "Avoid Redundancy of Code" }, { "code": null, "e": 26324, "s": 26311, "text": "Easy Testing" }, { "code": null, "e": 26387, "s": 26324, "text": "Support for GraphQL, Background Fetching, Dependency Injection" }, { "code": null, "e": 26421, "s": 26387, "text": "CREATING REST API USING FastAPI :" }, { "code": null, "e": 26486, "s": 26421, "text": "Install Python 3 and pip/pip3 according to your Operating System" }, { "code": null, "e": 26550, "s": 26486, "text": "Now, install fastapi using pip or pip3 : pip install fastapi\n" }, { "code": null, "e": 26574, "s": 26550, "text": " pip install fastapi\n" }, { "code": null, "e": 26684, "s": 26574, "text": "Install the uvicorn which is the Asynchronous Gateway Interface for your Server using : pip install uvicorn\n" }, { "code": null, "e": 26707, "s": 26684, "text": " pip install uvicorn\n" }, { "code": null, "e": 26822, "s": 26707, "text": "Now create a main.py file and import fastapi, also create a server from fastapi import FastAPI\n app = FastAPI()\n" }, { "code": null, "e": 26871, "s": 26822, "text": " from fastapi import FastAPI\n app = FastAPI()\n" }, { "code": null, "e": 26998, "s": 26871, "text": "Now, let’s add the code for sample get request as shown below : @app.get(\"/\")\n def read_root():\n return {\"Hello\": \"World\"}\n" }, { "code": null, "e": 27062, "s": 26998, "text": " @app.get(\"/\")\n def read_root():\n return {\"Hello\": \"World\"}\n" }, { "code": null, "e": 27271, "s": 27062, "text": "Hence, the main.py file will look like :from fastapi import FastAPIapp = FastAPI() @app.get(\"/\")def first_example(): \"\"\" GFG Example First Fast API Example \"\"\" return {\"GFG Example\": \"FastAPI\"}" }, { "code": "from fastapi import FastAPIapp = FastAPI() @app.get(\"/\")def first_example(): \"\"\" GFG Example First Fast API Example \"\"\" return {\"GFG Example\": \"FastAPI\"}", "e": 27440, "s": 27271, "text": null }, { "code": null, "e": 27494, "s": 27440, "text": "Now, start the server usinguvicorn main:app --reload\n" }, { "code": null, "e": 27521, "s": 27494, "text": "uvicorn main:app --reload\n" }, { "code": null, "e": 27667, "s": 27521, "text": "Now open the browser and open http://localhost:8000/docs or http://127.0.0.1:8000/docsYou will be able to see the Swagger UI Home page as below :" }, { "code": null, "e": 27696, "s": 27667, "text": "Expand the “First Example” :" }, { "code": null, "e": 27836, "s": 27696, "text": "Now try to Execute the API, you will get the success status with 200 code .The Response will be {“GFG Example”: “FastAPI”} as shown below :" }, { "code": null, "e": 27857, "s": 27836, "text": "Programming Language" }, { "code": null, "e": 27864, "s": 27857, "text": "Python" }, { "code": null, "e": 27962, "s": 27864, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28006, "s": 27962, "text": "Introduction of Object Oriented Programming" }, { "code": null, "e": 28051, "s": 28006, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 28064, "s": 28051, "text": "R - Matrices" }, { "code": null, "e": 28127, "s": 28064, "text": "7 Highest Paying Programming Languages For Freelancers in 2022" }, { "code": null, "e": 28142, "s": 28127, "text": "R - Data Types" }, { "code": null, "e": 28170, "s": 28142, "text": "Read JSON file using Python" }, { "code": null, "e": 28220, "s": 28170, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28242, "s": 28220, "text": "Python map() function" } ]
Get the Day of the Week from Today's Date in Java
To get the day of the week, use the Calendar.DAY_OF_WEEK. Firstly, let us get the current date. java.util.Date utilDate = new java.util.Date(); java.sql.Date dt = new java.sql.Date(utilDate.getTime()); Now, using GregorianCalendar, set the time. java.util.GregorianCalendar cal = new java.util.GregorianCalendar(); cal.setTime(dt); The last step would display the day of the week as shown in the following example. Live Demo import java.text.ParseException; public class Demo { public static void main(String[] args) throws ParseException { java.util.Date utilDate = new java.util.Date(); java.sql.Date dt = new java.sql.Date(utilDate.getTime()); System.out.println("Today's date: "+dt); java.util.GregorianCalendar cal = new java.util.GregorianCalendar(); cal.setTime(dt); // Getting the day of the week System.out.println("Day of the week: "+cal.get(java.util.Calendar.DAY_OF_WEEK)); } } Today's date: 2018-11-19 Day of the week: 2
[ { "code": null, "e": 1120, "s": 1062, "text": "To get the day of the week, use the Calendar.DAY_OF_WEEK." }, { "code": null, "e": 1158, "s": 1120, "text": "Firstly, let us get the current date." }, { "code": null, "e": 1264, "s": 1158, "text": "java.util.Date utilDate = new java.util.Date();\njava.sql.Date dt = new java.sql.Date(utilDate.getTime());" }, { "code": null, "e": 1308, "s": 1264, "text": "Now, using GregorianCalendar, set the time." }, { "code": null, "e": 1394, "s": 1308, "text": "java.util.GregorianCalendar cal = new java.util.GregorianCalendar();\ncal.setTime(dt);" }, { "code": null, "e": 1477, "s": 1394, "text": "The last step would display the day of the week as shown in the following example." }, { "code": null, "e": 1488, "s": 1477, "text": " Live Demo" }, { "code": null, "e": 2001, "s": 1488, "text": "import java.text.ParseException;\npublic class Demo {\n public static void main(String[] args) throws ParseException {\n java.util.Date utilDate = new java.util.Date();\n java.sql.Date dt = new java.sql.Date(utilDate.getTime());\n System.out.println(\"Today's date: \"+dt);\n java.util.GregorianCalendar cal = new java.util.GregorianCalendar();\n cal.setTime(dt);\n // Getting the day of the week\n System.out.println(\"Day of the week: \"+cal.get(java.util.Calendar.DAY_OF_WEEK));\n }\n}" }, { "code": null, "e": 2045, "s": 2001, "text": "Today's date: 2018-11-19\nDay of the week: 2" } ]
Print all the leaf nodes of Binary Heap - GeeksforGeeks
07 Apr, 2022 Given an array of N elements which denotes the array representation of binary heap, the task is to find the leaf nodes of this binary heap. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 5 6 7 Explanation: 1 / \ 2 3 / \ / \ 4 5 6 7 Leaf nodes of the Binary Heap are: 4 5 6 7 Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Output: 6 7 8 9 10 Explanation: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10 Leaf Nodes of the Binary Heap are: 6 7 8 9 10 Approach: The key observation in the problem is that the every leaf node of the Binary Heap will be at the Height H or H -1, If H is the height of the Binary Heap. Therefore, the leaf nodes can be computed as follows: Calculate the total height of the binary heap. Traverse the array in reverse order and compare the height of each node to the compute height H of the Binary Heap. If the height of the current node is H, then add the current node to the leaf nodes. Otherwise, If the height of current node is H-1 and there are no child nodes, then also add the node as leaf node. Below is the implementation of the above approach: Java C# Python3 Javascript // Java implementation to print// the leaf nodes of a Binary Heap import java.lang.*;import java.util.*;class GFG { // Function to calculate height // of the Binary heap with given // the count of the nodes static int height(int N) { return (int)Math.ceil( Math.log(N + 1) / Math.log(2)) - 1; } // Function to find the leaf // nodes of binary heap static void findLeafNodes( int arr[], int n) { // Calculate the height of // the complete binary tree int h = height(n); ArrayList<Integer> arrlist = new ArrayList<>(); for (int i = n - 1; i >= 0; i--) { if (height(i + 1) == h) { arrlist.add(arr[i]); } else if (height(i + 1) == h - 1 && n <= ((2 * i) + 1)) { // if the height if h-1, // then there should not // be any child nodes arrlist.add(arr[i]); } else { break; } } printLeafNodes(arrlist); } // Function to print the leaf nodes static void printLeafNodes( ArrayList<Integer> arrlist) { for (int i = arrlist.size() - 1; i >= 0; i--) { System.out.print( arrlist.get(i) + " "); } } // Driver Code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; findLeafNodes(arr, arr.length); }} // C# implementation to print// the leaf nodes of a Binary Heapusing System;using System.Collections.Generic;class GFG{ // Function to calculate height// of the Binary heap with given// the count of the nodesstatic int height(int N){ return (int)Math.Ceiling( Math.Log(N + 1) / Math.Log(2)) - 1;} // Function to find the leaf// nodes of binary heapstatic void findLeafNodes(int []arr, int n){ // Calculate the height of // the complete binary tree int h = height(n); List<int> arrlist = new List<int>(); for (int i = n - 1; i >= 0; i--) { if (height(i + 1) == h) { arrlist.Add(arr[i]); } else if (height(i + 1) == h - 1 && n <= ((2 * i) + 1)) { // if the height if h-1, // then there should not // be any child nodes arrlist.Add(arr[i]); } else { break; } } printLeafNodes(arrlist);} // Function to print the leaf nodesstatic void printLeafNodes(List<int> arrlist){ for (int i = arrlist.Count - 1; i >= 0; i--) { Console.Write(arrlist[i] + " "); }} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; findLeafNodes(arr, arr.Length);}} // This code is contributed by Princi Singh # Python3 implementation to print# the leaf nodes of a Binary Heapimport math def height(N): return math.log(N + 1) // math.log(2) # Function to find the leaf# nodes of binary heapdef findLeafNodes(arr, n): # Calculate the height of # the complete binary tree h = height(n) arrlist = [] for i in range(n - 1,-1,-1): if (height(i + 1) == h): arrlist.append(arr[i]) elif (height(i + 1) == h - 1 and n <= ((2 * i) + 1)): # if the height if h-1, # then there should not # be any child nodes arrlist.append(arr[i]) else: break prLeafNodes(arrlist) # Function to pr the leaf nodesdef prLeafNodes(arrlist): for i in range(len(arrlist) - 1,-1,-1): print(arrlist[i],end=" ") # Driver Codearr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]findLeafNodes(arr, len(arr)) # This code is contributed by shinjanpatra <script>// JavaScript implementation to print// the leaf nodes of a Binary Heapfunction height(N){ return Math.floor(Math.log(N + 1) / Math.log(2))} // Function to find the leaf// nodes of binary heapfunction findLeafNodes(arr, n){ // Calculate the height of // the complete binary tree let h = height(n) let arrlist = [] for(let i = n - 1;i >= 0 ;i--){ if (height(i + 1) == h) arrlist.push(arr[i]) else if (height(i + 1) == h - 1 && n <= ((2 * i) + 1)) // if the height if h-1, // then there should not // be any child nodes arrlist.push(arr[i]) else break } prLeafNodes(arrlist)} // Function to pr the leaf nodesfunction prLeafNodes(arrlist){ for(let i = arrlist.length - 1 ; i>=-0; i--) document.write(arrlist[i]," ")} // Driver Code let arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]findLeafNodes(arr, arr.length) // This code is contributed by shinjanpatra </script> 6 7 8 9 10 Performance Analysis: Time Complexity: O(L), where L is the number of leaf nodes. Auxiliary Space: O(1) princi singh Akanksha_Rai shinjanpatra binary-representation Data Structures-Heap Arrays Bit Magic Heap Arrays Bit Magic Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Reversal algorithm for array rotation Window Sliding Technique Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 24920, "s": 24892, "text": "\n07 Apr, 2022" }, { "code": null, "e": 25060, "s": 24920, "text": "Given an array of N elements which denotes the array representation of binary heap, the task is to find the leaf nodes of this binary heap." }, { "code": null, "e": 25071, "s": 25060, "text": "Examples: " }, { "code": null, "e": 25557, "s": 25071, "text": "Input: \narr[] = {1, 2, 3, 4, 5, 6, 7}\nOutput: 4 5 6 7\nExplanation:\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\nLeaf nodes of the Binary Heap are:\n4 5 6 7\n \nInput: \narr[] = {1, 2, 3, 4, 5,\n 6, 7, 8, 9, 10}\nOutput: 6 7 8 9 10\nExplanation:\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n / \\ /\n 8 9 10\nLeaf Nodes of the Binary Heap are:\n6 7 8 9 10" }, { "code": null, "e": 25776, "s": 25557, "text": "Approach: The key observation in the problem is that the every leaf node of the Binary Heap will be at the Height H or H -1, If H is the height of the Binary Heap. Therefore, the leaf nodes can be computed as follows:" }, { "code": null, "e": 25823, "s": 25776, "text": "Calculate the total height of the binary heap." }, { "code": null, "e": 25939, "s": 25823, "text": "Traverse the array in reverse order and compare the height of each node to the compute height H of the Binary Heap." }, { "code": null, "e": 26024, "s": 25939, "text": "If the height of the current node is H, then add the current node to the leaf nodes." }, { "code": null, "e": 26139, "s": 26024, "text": "Otherwise, If the height of current node is H-1 and there are no child nodes, then also add the node as leaf node." }, { "code": null, "e": 26190, "s": 26139, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26195, "s": 26190, "text": "Java" }, { "code": null, "e": 26198, "s": 26195, "text": "C#" }, { "code": null, "e": 26206, "s": 26198, "text": "Python3" }, { "code": null, "e": 26217, "s": 26206, "text": "Javascript" }, { "code": "// Java implementation to print// the leaf nodes of a Binary Heap import java.lang.*;import java.util.*;class GFG { // Function to calculate height // of the Binary heap with given // the count of the nodes static int height(int N) { return (int)Math.ceil( Math.log(N + 1) / Math.log(2)) - 1; } // Function to find the leaf // nodes of binary heap static void findLeafNodes( int arr[], int n) { // Calculate the height of // the complete binary tree int h = height(n); ArrayList<Integer> arrlist = new ArrayList<>(); for (int i = n - 1; i >= 0; i--) { if (height(i + 1) == h) { arrlist.add(arr[i]); } else if (height(i + 1) == h - 1 && n <= ((2 * i) + 1)) { // if the height if h-1, // then there should not // be any child nodes arrlist.add(arr[i]); } else { break; } } printLeafNodes(arrlist); } // Function to print the leaf nodes static void printLeafNodes( ArrayList<Integer> arrlist) { for (int i = arrlist.size() - 1; i >= 0; i--) { System.out.print( arrlist.get(i) + \" \"); } } // Driver Code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; findLeafNodes(arr, arr.length); }}", "e": 27795, "s": 26217, "text": null }, { "code": "// C# implementation to print// the leaf nodes of a Binary Heapusing System;using System.Collections.Generic;class GFG{ // Function to calculate height// of the Binary heap with given// the count of the nodesstatic int height(int N){ return (int)Math.Ceiling( Math.Log(N + 1) / Math.Log(2)) - 1;} // Function to find the leaf// nodes of binary heapstatic void findLeafNodes(int []arr, int n){ // Calculate the height of // the complete binary tree int h = height(n); List<int> arrlist = new List<int>(); for (int i = n - 1; i >= 0; i--) { if (height(i + 1) == h) { arrlist.Add(arr[i]); } else if (height(i + 1) == h - 1 && n <= ((2 * i) + 1)) { // if the height if h-1, // then there should not // be any child nodes arrlist.Add(arr[i]); } else { break; } } printLeafNodes(arrlist);} // Function to print the leaf nodesstatic void printLeafNodes(List<int> arrlist){ for (int i = arrlist.Count - 1; i >= 0; i--) { Console.Write(arrlist[i] + \" \"); }} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; findLeafNodes(arr, arr.Length);}} // This code is contributed by Princi Singh", "e": 29192, "s": 27795, "text": null }, { "code": "# Python3 implementation to print# the leaf nodes of a Binary Heapimport math def height(N): return math.log(N + 1) // math.log(2) # Function to find the leaf# nodes of binary heapdef findLeafNodes(arr, n): # Calculate the height of # the complete binary tree h = height(n) arrlist = [] for i in range(n - 1,-1,-1): if (height(i + 1) == h): arrlist.append(arr[i]) elif (height(i + 1) == h - 1 and n <= ((2 * i) + 1)): # if the height if h-1, # then there should not # be any child nodes arrlist.append(arr[i]) else: break prLeafNodes(arrlist) # Function to pr the leaf nodesdef prLeafNodes(arrlist): for i in range(len(arrlist) - 1,-1,-1): print(arrlist[i],end=\" \") # Driver Codearr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]findLeafNodes(arr, len(arr)) # This code is contributed by shinjanpatra", "e": 30121, "s": 29192, "text": null }, { "code": "<script>// JavaScript implementation to print// the leaf nodes of a Binary Heapfunction height(N){ return Math.floor(Math.log(N + 1) / Math.log(2))} // Function to find the leaf// nodes of binary heapfunction findLeafNodes(arr, n){ // Calculate the height of // the complete binary tree let h = height(n) let arrlist = [] for(let i = n - 1;i >= 0 ;i--){ if (height(i + 1) == h) arrlist.push(arr[i]) else if (height(i + 1) == h - 1 && n <= ((2 * i) + 1)) // if the height if h-1, // then there should not // be any child nodes arrlist.push(arr[i]) else break } prLeafNodes(arrlist)} // Function to pr the leaf nodesfunction prLeafNodes(arrlist){ for(let i = arrlist.length - 1 ; i>=-0; i--) document.write(arrlist[i],\" \")} // Driver Code let arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]findLeafNodes(arr, arr.length) // This code is contributed by shinjanpatra </script>", "e": 31128, "s": 30121, "text": null }, { "code": null, "e": 31139, "s": 31128, "text": "6 7 8 9 10" }, { "code": null, "e": 31161, "s": 31139, "text": "Performance Analysis:" }, { "code": null, "e": 31221, "s": 31161, "text": "Time Complexity: O(L), where L is the number of leaf nodes." }, { "code": null, "e": 31243, "s": 31221, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 31256, "s": 31243, "text": "princi singh" }, { "code": null, "e": 31269, "s": 31256, "text": "Akanksha_Rai" }, { "code": null, "e": 31282, "s": 31269, "text": "shinjanpatra" }, { "code": null, "e": 31304, "s": 31282, "text": "binary-representation" }, { "code": null, "e": 31325, "s": 31304, "text": "Data Structures-Heap" }, { "code": null, "e": 31332, "s": 31325, "text": "Arrays" }, { "code": null, "e": 31342, "s": 31332, "text": "Bit Magic" }, { "code": null, "e": 31347, "s": 31342, "text": "Heap" }, { "code": null, "e": 31354, "s": 31347, "text": "Arrays" }, { "code": null, "e": 31364, "s": 31354, "text": "Bit Magic" }, { "code": null, "e": 31369, "s": 31364, "text": "Heap" }, { "code": null, "e": 31467, "s": 31369, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31498, "s": 31467, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 31536, "s": 31498, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 31561, "s": 31536, "text": "Window Sliding Technique" }, { "code": null, "e": 31582, "s": 31561, "text": "Next Greater Element" }, { "code": null, "e": 31640, "s": 31582, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 31667, "s": 31640, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 31713, "s": 31667, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 31781, "s": 31713, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 31810, "s": 31781, "text": "Count set bits in an integer" } ]
Angular 10 getLocaleTimeFormat() Function - GeeksforGeeks
30 Apr, 2021 The getLocaleTimeFormat is used to get the localized time-value formatting for the given locale. Syntax: getLocaleTimeFormat(locale: string, width: FormatWidth): string NgModule: Module used by getLocaleTimeFormat is: CommonModule Approach: Create the angular app to be used In app.module.ts import LOCALE_ID because we need locale to be imported for using get getLocaleTimeFormat.import { LOCALE_ID, NgModule } from '@angular/core'; import { LOCALE_ID, NgModule } from '@angular/core'; In app.component.ts import getLocaleTimeFormat and LOCALE_ID inject LOCALE_ID as a public variable. In app.component.html show the local variable using string interpolation serve the angular app using ng serve to see the output. Parameters: locale: A string containing locale code with rules. width: String widths available for date-time formats. Return value: string: string of localized formatting strings. Example 1: app.module.ts import { LOCALE_ID, NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { } app.component.ts import {FormStyle, getLocaleTimeFormat, TranslationWidth, FormatWidth} from '@angular/common'; import { Component, Inject,OnInit, LOCALE_ID } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { for = getLocaleTimeFormat(this.locale, FormatWidth.Short); constructor( @Inject(LOCALE_ID) public locale: string,){} } app.component.html <h1> GeeksforGeeks </h1> <p>Time format is: {{for}}</p> Output: Example 2: app.module.ts import { LOCALE_ID, NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { } app.component.ts import {FormStyle, getLocaleTimeFormat, TranslationWidth, FormatWidth} from '@angular/common'; import { Component, Inject,OnInit, LOCALE_ID } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { for = getLocaleTimeFormat(this.locale, FormatWidth.Full); constructor( @Inject(LOCALE_ID) public locale: string,){} } app.component.html <h1> GeeksforGeeks </h1> <p>Time format is: {{for}}</p> Output: Reference: https://angular.io/api/common/getLocaleTimeFormat Angular10 AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26464, "s": 26436, "text": "\n30 Apr, 2021" }, { "code": null, "e": 26561, "s": 26464, "text": "The getLocaleTimeFormat is used to get the localized time-value formatting for the given locale." }, { "code": null, "e": 26569, "s": 26561, "text": "Syntax:" }, { "code": null, "e": 26633, "s": 26569, "text": "getLocaleTimeFormat(locale: string, width: FormatWidth): string" }, { "code": null, "e": 26682, "s": 26633, "text": "NgModule: Module used by getLocaleTimeFormat is:" }, { "code": null, "e": 26695, "s": 26682, "text": "CommonModule" }, { "code": null, "e": 26705, "s": 26695, "text": "Approach:" }, { "code": null, "e": 26739, "s": 26705, "text": "Create the angular app to be used" }, { "code": null, "e": 26898, "s": 26739, "text": "In app.module.ts import LOCALE_ID because we need locale to be imported for using get getLocaleTimeFormat.import { LOCALE_ID, NgModule } from '@angular/core';" }, { "code": null, "e": 26951, "s": 26898, "text": "import { LOCALE_ID, NgModule } from '@angular/core';" }, { "code": null, "e": 27012, "s": 26951, "text": "In app.component.ts import getLocaleTimeFormat and LOCALE_ID" }, { "code": null, "e": 27051, "s": 27012, "text": "inject LOCALE_ID as a public variable." }, { "code": null, "e": 27124, "s": 27051, "text": "In app.component.html show the local variable using string interpolation" }, { "code": null, "e": 27180, "s": 27124, "text": "serve the angular app using ng serve to see the output." }, { "code": null, "e": 27192, "s": 27180, "text": "Parameters:" }, { "code": null, "e": 27244, "s": 27192, "text": "locale: A string containing locale code with rules." }, { "code": null, "e": 27298, "s": 27244, "text": "width: String widths available for date-time formats." }, { "code": null, "e": 27312, "s": 27298, "text": "Return value:" }, { "code": null, "e": 27360, "s": 27312, "text": "string: string of localized formatting strings." }, { "code": null, "e": 27371, "s": 27360, "text": "Example 1:" }, { "code": null, "e": 27385, "s": 27371, "text": "app.module.ts" }, { "code": "import { LOCALE_ID, NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { }", "e": 27826, "s": 27385, "text": null }, { "code": null, "e": 27843, "s": 27826, "text": "app.component.ts" }, { "code": "import {FormStyle, getLocaleTimeFormat, TranslationWidth, FormatWidth} from '@angular/common'; import { Component, Inject,OnInit, LOCALE_ID } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { for = getLocaleTimeFormat(this.locale, FormatWidth.Short); constructor( @Inject(LOCALE_ID) public locale: string,){} }", "e": 28267, "s": 27843, "text": null }, { "code": null, "e": 28286, "s": 28267, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks </h1> <p>Time format is: {{for}}</p>", "e": 28346, "s": 28286, "text": null }, { "code": null, "e": 28354, "s": 28346, "text": "Output:" }, { "code": null, "e": 28365, "s": 28354, "text": "Example 2:" }, { "code": null, "e": 28379, "s": 28365, "text": "app.module.ts" }, { "code": "import { LOCALE_ID, NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { }", "e": 28820, "s": 28379, "text": null }, { "code": null, "e": 28837, "s": 28820, "text": "app.component.ts" }, { "code": "import {FormStyle, getLocaleTimeFormat, TranslationWidth, FormatWidth} from '@angular/common'; import { Component, Inject,OnInit, LOCALE_ID } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { for = getLocaleTimeFormat(this.locale, FormatWidth.Full); constructor( @Inject(LOCALE_ID) public locale: string,){} }", "e": 29264, "s": 28837, "text": null }, { "code": null, "e": 29283, "s": 29264, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks </h1> <p>Time format is: {{for}}</p>", "e": 29343, "s": 29283, "text": null }, { "code": null, "e": 29351, "s": 29343, "text": "Output:" }, { "code": null, "e": 29412, "s": 29351, "text": "Reference: https://angular.io/api/common/getLocaleTimeFormat" }, { "code": null, "e": 29422, "s": 29412, "text": "Angular10" }, { "code": null, "e": 29432, "s": 29422, "text": "AngularJS" }, { "code": null, "e": 29449, "s": 29432, "text": "Web Technologies" }, { "code": null, "e": 29547, "s": 29449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29582, "s": 29547, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29617, "s": 29582, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29652, "s": 29617, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 29676, "s": 29652, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 29729, "s": 29676, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 29769, "s": 29729, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29802, "s": 29769, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29847, "s": 29802, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29890, "s": 29847, "text": "How to fetch data from an API in ReactJS ?" } ]
Can we declare an interface as final in java?
Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static. Since all the methods are abstract you cannot instantiate it. To use it, you need to implement this interface using a class and provide body to all the abstract methods int it. If you declare a class final cannot extend it. If you make a method final you cannot override it and, if you make a variable final you cannot modify it. i.e. use final with Java entities you cannot modify them further. If you make an interface final, you cannot implement its methods which defies the very purpose of the interfaces. Therefore, you cannot make an interface final in Java. Still if you try to do so, a compile time exception is generated saying “illegal combination of modifiers − interface and final”. In the following example we are defining an interface with name MyInterface and using the final modifier with it. public final interface MyInterface{ public static final int num = 10; public abstract void demo(); } On compiling, the above program generates the following error MyInterface.java:1: error: illegal combination of modifiers: interface and final public final interface MyInterface{ ^ 1 error
[ { "code": null, "e": 1178, "s": 1062, "text": "Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static." }, { "code": null, "e": 1355, "s": 1178, "text": "Since all the methods are abstract you cannot instantiate it. To use it, you need to implement this interface using a class and provide body to all the abstract methods int it." }, { "code": null, "e": 1574, "s": 1355, "text": "If you declare a class final cannot extend it. If you make a method final you cannot override it and, if you make a variable final you cannot modify it. i.e. use final with Java entities you cannot modify them further." }, { "code": null, "e": 1873, "s": 1574, "text": "If you make an interface final, you cannot implement its methods which defies the very purpose of the interfaces. Therefore, you cannot make an interface final in Java. Still if you try to do so, a compile time exception is generated saying “illegal combination of modifiers − interface and final”." }, { "code": null, "e": 1987, "s": 1873, "text": "In the following example we are defining an interface with name MyInterface and using the final modifier with it." }, { "code": null, "e": 2094, "s": 1987, "text": "public final interface MyInterface{\n public static final int num = 10;\n public abstract void demo();\n}" }, { "code": null, "e": 2156, "s": 2094, "text": "On compiling, the above program generates the following error" }, { "code": null, "e": 2286, "s": 2156, "text": "MyInterface.java:1: error: illegal combination of modifiers: interface and final\n public final interface MyInterface{\n^\n1 error" } ]
Hash Table Data Structure in Javascript
Hash Table is a data structure which stores data in an associative manner. In a hash table, data is stored in an array format, where each data value has its own unique index value. Access to data becomes very fast if we know the index of the desired data. Thus, it becomes a data structure in which insertion and search operations are very fast irrespective of the size of the data. Hash Table uses an array as a storage medium and uses the hash technique to generate an index where an element is to be inserted or is to be located from. Hashing is a technique to convert a range of key values into a range of indexes of an array. We're going to use modulo operator to get a range of key values. Consider an example of a hash table of size 20, and the following items are to be stored. Item is in the (key, value) format. Here we have a hash function that takes in keys and generates indices for a table. These indices let us know where the value is stored. Now whenever we want to search for a value associated with a key, we just need to run the hash function on the key again and get the value in nearly constant time. Hash functions are pretty hard to design though. Let's take an example − Let's say we have the following hash function − function modBy11(key) { return key % 11; } And we start running this on key-value pairs we want to store, for example − (15, 20) - Hash code: 4 (25, 39) - Hash code: 3 (8, 55) - Hash code: 8 (26, 84) - Hash code: 4 Here we see that we have a collision, ie, if we were to store 15 first and then encounter the key 26 with this hash function, it'll try to fix this entry in the same hole. This is called a collision. And to handle such situations, we need to define a collision handling mechanism. There are some well defined simple collision resolution algorithms. For example − Linear Probing: In this algorithm, we can search the next empty location in the array by looking into the next cell until we find an empty cell. In our example, since hole at 4 is taken, we can fill it in 5. Separate Chaining: In this implementation: We associate each location in the hash table with a list. Whenever we get a collision, we append the key-value pair at the end of this list. This can lead to much longer search times if chains keep getting longer. Now that we understand how a hash table works and how we can use collision resolution, let's implement the HashTable class. We'll implement these methods in our implementation − put(key, value): Adds a new key-value pair to the hash table get(key): Gets the value associated with a key remove(key): Removes the key-value pair from the table forEach(): Allows iterating over all key-value pairs static join(): A static method to join 2 hash tables in a new one
[ { "code": null, "e": 1318, "s": 1062, "text": "Hash Table is a data structure which stores data in an associative manner. In a hash table, data is stored in an array format, where each data value has its own unique index value. Access to data becomes very fast if we know the index of the desired data." }, { "code": null, "e": 1600, "s": 1318, "text": "Thus, it becomes a data structure in which insertion and search operations are very fast irrespective of the size of the data. Hash Table uses an array as a storage medium and uses the hash technique to generate an index where an element is to be inserted or is to be located from." }, { "code": null, "e": 1884, "s": 1600, "text": "Hashing is a technique to convert a range of key values into a range of indexes of an array. We're going to use modulo operator to get a range of key values. Consider an example of a hash table of size 20, and the following items are to be stored. Item is in the (key, value) format." }, { "code": null, "e": 2184, "s": 1884, "text": "Here we have a hash function that takes in keys and generates indices for a table. These indices let us know where the value is stored. Now whenever we want to search for a value associated with a key, we just need to run the hash function on the key again and get the value in nearly constant time." }, { "code": null, "e": 2257, "s": 2184, "text": "Hash functions are pretty hard to design though. Let's take an example −" }, { "code": null, "e": 2306, "s": 2257, "text": "Let's say we have the following hash function − " }, { "code": null, "e": 2352, "s": 2306, "text": "function modBy11(key) {\n return key % 11;\n}" }, { "code": null, "e": 2429, "s": 2352, "text": "And we start running this on key-value pairs we want to store, for example −" }, { "code": null, "e": 2453, "s": 2429, "text": "(15, 20) - Hash code: 4" }, { "code": null, "e": 2477, "s": 2453, "text": "(25, 39) - Hash code: 3" }, { "code": null, "e": 2500, "s": 2477, "text": "(8, 55) - Hash code: 8" }, { "code": null, "e": 2524, "s": 2500, "text": "(26, 84) - Hash code: 4" }, { "code": null, "e": 2887, "s": 2524, "text": "Here we see that we have a collision, ie, if we were to store 15 first and then encounter the key 26 with this hash function, it'll try to fix this entry in the same hole. This is called a collision. And to handle such situations, we need to define a collision handling mechanism. There are some well defined simple collision resolution algorithms. For example −" }, { "code": null, "e": 3095, "s": 2887, "text": "Linear Probing: In this algorithm, we can search the next empty location in the array by looking into the next cell until we find an empty cell. In our example, since hole at 4 is taken, we can fill it in 5." }, { "code": null, "e": 3352, "s": 3095, "text": "Separate Chaining: In this implementation: We associate each location in the hash table with a list. Whenever we get a collision, we append the key-value pair at the end of this list. This can lead to much longer search times if chains keep getting longer." }, { "code": null, "e": 3476, "s": 3352, "text": "Now that we understand how a hash table works and how we can use collision resolution, let's implement the HashTable class." }, { "code": null, "e": 3530, "s": 3476, "text": "We'll implement these methods in our implementation −" }, { "code": null, "e": 3591, "s": 3530, "text": "put(key, value): Adds a new key-value pair to the hash table" }, { "code": null, "e": 3638, "s": 3591, "text": "get(key): Gets the value associated with a key" }, { "code": null, "e": 3693, "s": 3638, "text": "remove(key): Removes the key-value pair from the table" }, { "code": null, "e": 3746, "s": 3693, "text": "forEach(): Allows iterating over all key-value pairs" }, { "code": null, "e": 3812, "s": 3746, "text": "static join(): A static method to join 2 hash tables in a new one" } ]
Python | Pandas dataframe.median()
24 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.median() function return the median of the values for the requested axisIf the method is applied on a pandas series object, then the method returns a scalar value which is the median value of all the observations in the dataframe. If the method is applied on a pandas dataframe object, then the method returns a pandas series object which contains the median of the values over the specified axis. Syntax:DataFrame.median(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)Parameters :axis : Align object with threshold along the given axis.skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. Returns : median : Series or DataFrame (if level specified) Example #1: Use median() function to find the median of all the observations over the index axis. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, 44, 1], "B":[5, 2, 54, 3, 2], "C":[20, 16, 7, 3, 8], "D":[14, 3, 17, 2, 6]}) # Print the dataframedf Lets use the dataframe.median() function to find the median over the index axis # Find median Even if we do not specify axis = 0, the method # will return the median over the index axis by defaultdf.median(axis = 0) Output : Example #2: Use median() function on a dataframe which has Na values. Also find the median over the column axis. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # Print the dataframedf Lets implement the median function. # skip the Na values while finding the mediandf.median(axis = 1, skipna = True) Output : Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 657, "s": 242, "text": "Pandas dataframe.median() function return the median of the values for the requested axisIf the method is applied on a pandas series object, then the method returns a scalar value which is the median value of all the observations in the dataframe. If the method is applied on a pandas dataframe object, then the method returns a pandas series object which contains the median of the values over the specified axis." }, { "code": null, "e": 1132, "s": 657, "text": "Syntax:DataFrame.median(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)Parameters :axis : Align object with threshold along the given axis.skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series." }, { "code": null, "e": 1192, "s": 1132, "text": "Returns : median : Series or DataFrame (if level specified)" }, { "code": null, "e": 1290, "s": 1192, "text": "Example #1: Use median() function to find the median of all the observations over the index axis." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, 44, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 16, 7, 3, 8], \"D\":[14, 3, 17, 2, 6]}) # Print the dataframedf", "e": 1551, "s": 1290, "text": null }, { "code": null, "e": 1631, "s": 1551, "text": "Lets use the dataframe.median() function to find the median over the index axis" }, { "code": "# Find median Even if we do not specify axis = 0, the method # will return the median over the index axis by defaultdf.median(axis = 0)", "e": 1767, "s": 1631, "text": null }, { "code": null, "e": 1776, "s": 1767, "text": "Output :" }, { "code": null, "e": 1890, "s": 1776, "text": " Example #2: Use median() function on a dataframe which has Na values. Also find the median over the column axis." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # Print the dataframedf", "e": 2160, "s": 1890, "text": null }, { "code": null, "e": 2196, "s": 2160, "text": "Lets implement the median function." }, { "code": "# skip the Na values while finding the mediandf.median(axis = 1, skipna = True)", "e": 2276, "s": 2196, "text": null }, { "code": null, "e": 2285, "s": 2276, "text": "Output :" }, { "code": null, "e": 2309, "s": 2285, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2341, "s": 2309, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2355, "s": 2341, "text": "Python-pandas" }, { "code": null, "e": 2362, "s": 2355, "text": "Python" } ]
Difference between EDF and LST CPU scheduling algorithms
20 Jun, 2020 1. Earliest Deadline First (EDF) :In Earliest Deadline First scheduling algorithm, at every scheduling point the task having the shortest deadline is scheduled for the execution. It is an optimal dynamic priority-driven scheduling algorithm used in real-time systems. It uses priorities of the tasks for scheduling. In EDF, priorities to the task are assigned according to the absolute deadline. The task having shortest deadline gets the highest priority. Example –Suppose here are two processes P1 and P2.Let the period of P1 be p1 = 50Let the processing time of P1 be t1 = 25Let the period of P2 be p2 = 75Let the processing time of P2 be t2 = 30 Explanation : Deadline pf P1 is earlier, so priority of P1>P2.Initially P1 runs and completes its execution of 25 time.After 25 times, P2 starts to execute until 50 times, when P1 is able to execute.Now, comparing the deadline of (P1, P2) = (100, 75), P2 continues to execute.P2 completes its processing at time 55.P1 starts to execute until time 75, when P2 is able to execute.Now, again comparing the deadline of (P1, P2) = (100, 150), P1 continues to execute.Repeat the above steps.Finally at time 150, both P1 and P2 have the same deadline, so P2 will continue to execute till its processing time after which P1 starts to execute. Deadline pf P1 is earlier, so priority of P1>P2. Initially P1 runs and completes its execution of 25 time. After 25 times, P2 starts to execute until 50 times, when P1 is able to execute. Now, comparing the deadline of (P1, P2) = (100, 75), P2 continues to execute. P2 completes its processing at time 55. P1 starts to execute until time 75, when P2 is able to execute. Now, again comparing the deadline of (P1, P2) = (100, 150), P1 continues to execute. Repeat the above steps. Finally at time 150, both P1 and P2 have the same deadline, so P2 will continue to execute till its processing time after which P1 starts to execute. 2. Least Slack Time (LST) :In Least Slack Time scheduling algorithm, at every scheduling point the task having the minimum laxity is executed first. It is also a dynamic priority-driven scheduling algorithm used in real-time systems. It assigns some priority to all the tasks in the system according to their slack time. The task having the least slack time (laxity) gets the highest priority. Example –Process P1:Arrival Time=0, Duration=10, Deadline=33Process P2:Arrival Time=4, Duration=3, Deadline=28Process P3:Arrival Time=5, Duration=10, Deadline=29 Explanation : At time t=0:Only process P1 has arrived.P1 is executed till time t=4. At time t=4: P2 has arrived.Slack time of P1: 33-4-6=23Slack time of P2: 28-4-3=21Hence P2 starts to execute till time t=5 when P3 arrives. At time t=5:Slack Time of P1: 33-5-6=22Slack Time of P2: 28-5-2=21Slack Time of P3: 29-5-10=12Hence P3 starts to execute till time t=13 At time t=13:Slack Time of P1: 33-13-6=14Slack Time of P2: 28-13-2=13Slack Time of P3: 29-13-2=14Hence P2 starts to execute till time t=15 At time t=15:Slack Time of P1: 33-15-6=12Slack Time of P3: 29-15-2=12Hence P3 starts to execute till time t=16 At time t=16:Slack Time of P1: 33-16-6=11Slack Time of P3:29-16-=12Hence P1 starts to execute till time t=18 and so on. Difference between EDF and LST scheduling algorithms : CPU Scheduling Operating Systems-CPU Scheduling Difference Between Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2020" }, { "code": null, "e": 485, "s": 28, "text": "1. Earliest Deadline First (EDF) :In Earliest Deadline First scheduling algorithm, at every scheduling point the task having the shortest deadline is scheduled for the execution. It is an optimal dynamic priority-driven scheduling algorithm used in real-time systems. It uses priorities of the tasks for scheduling. In EDF, priorities to the task are assigned according to the absolute deadline. The task having shortest deadline gets the highest priority." }, { "code": null, "e": 678, "s": 485, "text": "Example –Suppose here are two processes P1 and P2.Let the period of P1 be p1 = 50Let the processing time of P1 be t1 = 25Let the period of P2 be p2 = 75Let the processing time of P2 be t2 = 30" }, { "code": null, "e": 692, "s": 678, "text": "Explanation :" }, { "code": null, "e": 1313, "s": 692, "text": "Deadline pf P1 is earlier, so priority of P1>P2.Initially P1 runs and completes its execution of 25 time.After 25 times, P2 starts to execute until 50 times, when P1 is able to execute.Now, comparing the deadline of (P1, P2) = (100, 75), P2 continues to execute.P2 completes its processing at time 55.P1 starts to execute until time 75, when P2 is able to execute.Now, again comparing the deadline of (P1, P2) = (100, 150), P1 continues to execute.Repeat the above steps.Finally at time 150, both P1 and P2 have the same deadline, so P2 will continue to execute till its processing time after which P1 starts to execute." }, { "code": null, "e": 1362, "s": 1313, "text": "Deadline pf P1 is earlier, so priority of P1>P2." }, { "code": null, "e": 1420, "s": 1362, "text": "Initially P1 runs and completes its execution of 25 time." }, { "code": null, "e": 1501, "s": 1420, "text": "After 25 times, P2 starts to execute until 50 times, when P1 is able to execute." }, { "code": null, "e": 1579, "s": 1501, "text": "Now, comparing the deadline of (P1, P2) = (100, 75), P2 continues to execute." }, { "code": null, "e": 1619, "s": 1579, "text": "P2 completes its processing at time 55." }, { "code": null, "e": 1683, "s": 1619, "text": "P1 starts to execute until time 75, when P2 is able to execute." }, { "code": null, "e": 1768, "s": 1683, "text": "Now, again comparing the deadline of (P1, P2) = (100, 150), P1 continues to execute." }, { "code": null, "e": 1792, "s": 1768, "text": "Repeat the above steps." }, { "code": null, "e": 1942, "s": 1792, "text": "Finally at time 150, both P1 and P2 have the same deadline, so P2 will continue to execute till its processing time after which P1 starts to execute." }, { "code": null, "e": 2336, "s": 1942, "text": "2. Least Slack Time (LST) :In Least Slack Time scheduling algorithm, at every scheduling point the task having the minimum laxity is executed first. It is also a dynamic priority-driven scheduling algorithm used in real-time systems. It assigns some priority to all the tasks in the system according to their slack time. The task having the least slack time (laxity) gets the highest priority." }, { "code": null, "e": 2498, "s": 2336, "text": "Example –Process P1:Arrival Time=0, Duration=10, Deadline=33Process P2:Arrival Time=4, Duration=3, Deadline=28Process P3:Arrival Time=5, Duration=10, Deadline=29" }, { "code": null, "e": 2512, "s": 2498, "text": "Explanation :" }, { "code": null, "e": 2582, "s": 2512, "text": "At time t=0:Only process P1 has arrived.P1 is executed till time t=4." }, { "code": null, "e": 2722, "s": 2582, "text": "At time t=4: P2 has arrived.Slack time of P1: 33-4-6=23Slack time of P2: 28-4-3=21Hence P2 starts to execute till time t=5 when P3 arrives." }, { "code": null, "e": 2858, "s": 2722, "text": "At time t=5:Slack Time of P1: 33-5-6=22Slack Time of P2: 28-5-2=21Slack Time of P3: 29-5-10=12Hence P3 starts to execute till time t=13" }, { "code": null, "e": 2997, "s": 2858, "text": "At time t=13:Slack Time of P1: 33-13-6=14Slack Time of P2: 28-13-2=13Slack Time of P3: 29-13-2=14Hence P2 starts to execute till time t=15" }, { "code": null, "e": 3108, "s": 2997, "text": "At time t=15:Slack Time of P1: 33-15-6=12Slack Time of P3: 29-15-2=12Hence P3 starts to execute till time t=16" }, { "code": null, "e": 3228, "s": 3108, "text": "At time t=16:Slack Time of P1: 33-16-6=11Slack Time of P3:29-16-=12Hence P1 starts to execute till time t=18 and so on." }, { "code": null, "e": 3283, "s": 3228, "text": "Difference between EDF and LST scheduling algorithms :" }, { "code": null, "e": 3298, "s": 3283, "text": "CPU Scheduling" }, { "code": null, "e": 3331, "s": 3298, "text": "Operating Systems-CPU Scheduling" }, { "code": null, "e": 3350, "s": 3331, "text": "Difference Between" }, { "code": null, "e": 3368, "s": 3350, "text": "Operating Systems" }, { "code": null, "e": 3386, "s": 3368, "text": "Operating Systems" } ]
Rounding off values in R Language – round() Function
15 Apr, 2021 round() function in R Language is used to round off values to a specific number of decimal value. Syntax: round(x, digits)Parameters: x: Value to be round off digits: Number of digits to which value has to be round off Example 1: Rounding off the values Python3 # R program to illustrate# round function # Create example valuesx1 <- 1.2 x2 <- 1.8x3 <- - 1.3x4 <- 1.7 # Apply round functionround(x1) round(x2)round(x3)round(x4) print(x1, x2, x3, x4) Output : 1 2 -1 2 Here in the above code, we have round off the values with 4 data x1, x2, x3, and x4 using the function round(), and printed the new values.Example 2: Rounding off to certain digits Python3 # R program to illustrate# round to a certain digit # Create numeric with many digitsx2 <- 3.14734343243 # Round to three decimal places round(x2, digits = 3) print(x2) Output: 3.147 Here in the above code, the value of a numeric vector is round off till 3 digits. arorakashish0911 R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Apr, 2021" }, { "code": null, "e": 127, "s": 28, "text": "round() function in R Language is used to round off values to a specific number of decimal value. " }, { "code": null, "e": 248, "s": 127, "text": "Syntax: round(x, digits)Parameters: x: Value to be round off digits: Number of digits to which value has to be round off" }, { "code": null, "e": 285, "s": 248, "text": "Example 1: Rounding off the values " }, { "code": null, "e": 293, "s": 285, "text": "Python3" }, { "code": "# R program to illustrate# round function # Create example valuesx1 <- 1.2 x2 <- 1.8x3 <- - 1.3x4 <- 1.7 # Apply round functionround(x1) round(x2)round(x3)round(x4) print(x1, x2, x3, x4)", "e": 530, "s": 293, "text": null }, { "code": null, "e": 541, "s": 530, "text": "Output : " }, { "code": null, "e": 553, "s": 541, "text": " 1\n 2\n-1\n 2" }, { "code": null, "e": 736, "s": 553, "text": "Here in the above code, we have round off the values with 4 data x1, x2, x3, and x4 using the function round(), and printed the new values.Example 2: Rounding off to certain digits " }, { "code": null, "e": 744, "s": 736, "text": "Python3" }, { "code": "# R program to illustrate# round to a certain digit # Create numeric with many digitsx2 <- 3.14734343243 # Round to three decimal places round(x2, digits = 3) print(x2) ", "e": 944, "s": 744, "text": null }, { "code": null, "e": 952, "s": 944, "text": "Output:" }, { "code": null, "e": 960, "s": 952, "text": " 3.147 " }, { "code": null, "e": 1043, "s": 960, "text": "Here in the above code, the value of a numeric vector is round off till 3 digits. " }, { "code": null, "e": 1060, "s": 1043, "text": "arorakashish0911" }, { "code": null, "e": 1071, "s": 1060, "text": "R Language" } ]
PyQtGraph – Setting Pen of Graph Item
08 Dec, 2021 In this article we will see how we can set the pen of the graph item in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes. Pen is used to draw the line of graph i.e joining edges, by setting pen we can set the color, size and opacity of each line. We can create a graphic layout widget and graphic item with the help of command given below # creating graphics layout widget win = pg.GraphicsLayoutWidget() # creating a graph item graph_item = pg.GraphItem() In order to do this we use setPenmethod with the graph item objectSyntax : imv.setPen(lines)Argument : It takes numpy array as argumentReturn : It returns None Below is the implementation Python3 # importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import *import pyqtgraph.ptime as ptime # Image View classclass ImageView(pg.ImageView): # constructor which inherit original # ImageView def __init__(self, *args, **kwargs): pg.ImageView.__init__(self, *args, **kwargs) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a label label = QLabel("Geeksforgeeks Graph Item") # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # setting configuration options pg.setConfigOptions(antialias=True) # creating graphics layout widget win = pg.GraphicsLayoutWidget() # adding view box to the graphic layout widget view = win.addViewBox() # lock the aspect ratio view.setAspectLocked() # creating a graph item graph_item = pg.GraphItem() # adding graph item to the view box view.addItem(graph_item) # Define positions of nodes pos = np.array([ [0, 0], [10, 0], [0, 10], [10, 10], [5, 5], [15, 5] ]) # Define the set of connections in the graph adj = np.array([ [0, 1], [1, 3], [3, 2], [2, 0], [1, 5], [3, 5], ]) # Define the symbol to use for each node (this is optional) symbols = ['o', 'x', 'o', 'o', 't', '+'] # setting data to the graph item graph_item.setData(pos=pos, adj=adj, size=1, symbol=symbols, pxMode=False) # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setMinimumWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(win, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # Define the line style for each connection (this is optional) lines_pen = np.array([ (255, 0, 150, 255, 10), (255, 0, 255, 255, 2), (255, 0, 255, 255, 3), (255, 255, 0, 255, 2), (255, 0, 50, 255, 1), (255, 255, 255, 255, 4), ], dtype=[('red', np.ubyte), ('green', np.ubyte), ('blue', np.ubyte), ('alpha', np.ubyte), ('width', float)]) # setting pen to the graph item graph_item.setPen(lines_pen) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : sagartomar9927 surinderdawra388 Python-gui Python-PyQtGraph Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Dec, 2021" }, { "code": null, "e": 782, "s": 28, "text": "In this article we will see how we can set the pen of the graph item in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes. Pen is used to draw the line of graph i.e joining edges, by setting pen we can set the color, size and opacity of each line." }, { "code": null, "e": 875, "s": 782, "text": "We can create a graphic layout widget and graphic item with the help of command given below " }, { "code": null, "e": 994, "s": 875, "text": "# creating graphics layout widget\nwin = pg.GraphicsLayoutWidget()\n\n# creating a graph item\ngraph_item = pg.GraphItem()" }, { "code": null, "e": 1155, "s": 994, "text": "In order to do this we use setPenmethod with the graph item objectSyntax : imv.setPen(lines)Argument : It takes numpy array as argumentReturn : It returns None " }, { "code": null, "e": 1184, "s": 1155, "text": "Below is the implementation " }, { "code": null, "e": 1192, "s": 1184, "text": "Python3" }, { "code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import *import pyqtgraph.ptime as ptime # Image View classclass ImageView(pg.ImageView): # constructor which inherit original # ImageView def __init__(self, *args, **kwargs): pg.ImageView.__init__(self, *args, **kwargs) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a label label = QLabel(\"Geeksforgeeks Graph Item\") # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # setting configuration options pg.setConfigOptions(antialias=True) # creating graphics layout widget win = pg.GraphicsLayoutWidget() # adding view box to the graphic layout widget view = win.addViewBox() # lock the aspect ratio view.setAspectLocked() # creating a graph item graph_item = pg.GraphItem() # adding graph item to the view box view.addItem(graph_item) # Define positions of nodes pos = np.array([ [0, 0], [10, 0], [0, 10], [10, 10], [5, 5], [15, 5] ]) # Define the set of connections in the graph adj = np.array([ [0, 1], [1, 3], [3, 2], [2, 0], [1, 5], [3, 5], ]) # Define the symbol to use for each node (this is optional) symbols = ['o', 'x', 'o', 'o', 't', '+'] # setting data to the graph item graph_item.setData(pos=pos, adj=adj, size=1, symbol=symbols, pxMode=False) # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setMinimumWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(win, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # Define the line style for each connection (this is optional) lines_pen = np.array([ (255, 0, 150, 255, 10), (255, 0, 255, 255, 2), (255, 0, 255, 255, 3), (255, 255, 0, 255, 2), (255, 0, 50, 255, 1), (255, 255, 255, 255, 4), ], dtype=[('red', np.ubyte), ('green', np.ubyte), ('blue', np.ubyte), ('alpha', np.ubyte), ('width', float)]) # setting pen to the graph item graph_item.setPen(lines_pen) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 4618, "s": 1192, "text": null }, { "code": null, "e": 4628, "s": 4618, "text": "Output : " }, { "code": null, "e": 4645, "s": 4630, "text": "sagartomar9927" }, { "code": null, "e": 4662, "s": 4645, "text": "surinderdawra388" }, { "code": null, "e": 4673, "s": 4662, "text": "Python-gui" }, { "code": null, "e": 4690, "s": 4673, "text": "Python-PyQtGraph" }, { "code": null, "e": 4697, "s": 4690, "text": "Python" } ]
Python Tweepy – Getting the name of a user
18 Jun, 2020 In this article we will see how we can get the name of a user. Name is the display name of the twitter account. It is the name that users choose to identify themselves on the network. Many users choose to either use their real name as the basis for their display name. Unlike screen names, the names need not be unique. Moreover the names can be in any language script, the screen name can only be in English(Latin). Names can also have spaces and special characters in them. Identifying the name in the GUI : In the above mentioned profile, GeeksforGeeks is the name of the profile. In order to get the name we have to do the following : Identify the user ID or screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the name attribute present in it. Identify the user ID or screen name of the profile. Get the User object of the profile using the get_user() method with the user ID or the screen name. From this object, fetch the name attribute present in it. Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058. # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the userid = 57741058 # fetching the useruser = api.get_user(id) # fetching the namename = user.name print("The name of the user is : " + name) Output : The name of the user is : GeeksforGeeks Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG. # the screen name of the userscreen_name = "PracticeGfG" # fetching the useruser = api.get_user(screen_name) # fetching the namename = user.name print("The name of the user is : " + name) Output : The name of the user is : Practice GfG Python-Tweepy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jun, 2020" }, { "code": null, "e": 504, "s": 28, "text": "In this article we will see how we can get the name of a user. Name is the display name of the twitter account. It is the name that users choose to identify themselves on the network. Many users choose to either use their real name as the basis for their display name. Unlike screen names, the names need not be unique. Moreover the names can be in any language script, the screen name can only be in English(Latin). Names can also have spaces and special characters in them." }, { "code": null, "e": 538, "s": 504, "text": "Identifying the name in the GUI :" }, { "code": null, "e": 612, "s": 538, "text": "In the above mentioned profile, GeeksforGeeks is the name of the profile." }, { "code": null, "e": 667, "s": 612, "text": "In order to get the name we have to do the following :" }, { "code": null, "e": 875, "s": 667, "text": "Identify the user ID or screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the name attribute present in it." }, { "code": null, "e": 927, "s": 875, "text": "Identify the user ID or screen name of the profile." }, { "code": null, "e": 1027, "s": 927, "text": "Get the User object of the profile using the get_user() method with the user ID or the screen name." }, { "code": null, "e": 1085, "s": 1027, "text": "From this object, fetch the name attribute present in it." }, { "code": null, "e": 1227, "s": 1085, "text": "Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058." }, { "code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the userid = 57741058 # fetching the useruser = api.get_user(id) # fetching the namename = user.name print(\"The name of the user is : \" + name)", "e": 1793, "s": 1227, "text": null }, { "code": null, "e": 1802, "s": 1793, "text": "Output :" }, { "code": null, "e": 1843, "s": 1802, "text": "The name of the user is : GeeksforGeeks\n" }, { "code": null, "e": 1996, "s": 1843, "text": "Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG." }, { "code": "# the screen name of the userscreen_name = \"PracticeGfG\" # fetching the useruser = api.get_user(screen_name) # fetching the namename = user.name print(\"The name of the user is : \" + name)", "e": 2187, "s": 1996, "text": null }, { "code": null, "e": 2196, "s": 2187, "text": "Output :" }, { "code": null, "e": 2236, "s": 2196, "text": "The name of the user is : Practice GfG\n" }, { "code": null, "e": 2250, "s": 2236, "text": "Python-Tweepy" }, { "code": null, "e": 2257, "s": 2250, "text": "Python" } ]
Java Program to Extract Last two Digits of a Given Year
02 Nov, 2020 As the name suggests where there is an execution to be operated required to deal with digits of the number, the modulo operator plays a vital role. Here the goal is to extract the last digits of a number. So making the problem easier to think about what if the goal is to extract the last digit from a number. Here in this case number is representing the year. The mathematical concept involved in extracting the last is to divide the given number by such a number that the remainder should be the same as that of the last digit. In order to extract the last digit that number with which the given number has to be divided must be 10. Modulo is represented by ‘%’ and is used to get the remainder Example: Extracting Last One Digit From A Number Random Number = 1997 Last Digit = 7 Goal: 1997 % (x) = 7 // Goal is Divide 1997 by x such that remainder is 7 if x = 10 // 1997 % 10 = 7 that is the last digit Now, in order to extract the last two digits, we will be treating the number with the same approach just the given number will be modulo by 100 as per the mathematics unit standard. Example: Extracting the Last Two-Digit From A Number Input : year = 2020 Output : 20 Input : year = 1983 Output : 83 Input : year = 2000 Output : 00 We can implement this using 2 different methods: Using Modulo Arithmetic Operator Using String substring() method A. Using Modulo Arithmetic Operator: We can use the modulo operator (%) to extract the last two digits by taking the modulo of the year by 100. Internal Working Of Mathematics Unit System Let us consider 1983, we can write it as 1983 = 1*1000 + 9*100 + 8*10 + 3 So when we take modulo by 100, we will just have the last two digits as remainder. 1983 % 100 = 1*1000 % 100 + 9*100 % 100 + 8*10 % 100 + 3 % 100 = 0 + 0 + 8*10 + 3 = 83 The implementation of the above approach is described below Java // Java code to extract last two digits of a year // Importing Classes/Filesimport java.util.*; public class GFG { // Main Driver Code public static void main(String args[]) { // Initializing year as String int year = 1983; // Printing last two digits of a number // by modulo with 100 System.out.print(year % 100); }} 83 B. Using String substring() method: This method returns a new string that is a substring of the given string. Thus, to extract the last two digits we need to get the substring after index 2. Java // Java code to extract last two digits of a yearpublic class GFG { // Function to extract last to digits of a year static int extractLastTwo(String year) { // using substring() to extract the last two digit // as substring String lastTwoDigits = year.substring(2); return Integer.parseInt( lastTwoDigits); // Returning last two digits as // an integer } public static void main(String args[]) { // Initializing year as String String year = "1983"; System.out.print(extractLastTwo(year)); }} 83 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Nov, 2020" }, { "code": null, "e": 687, "s": 52, "text": "As the name suggests where there is an execution to be operated required to deal with digits of the number, the modulo operator plays a vital role. Here the goal is to extract the last digits of a number. So making the problem easier to think about what if the goal is to extract the last digit from a number. Here in this case number is representing the year. The mathematical concept involved in extracting the last is to divide the given number by such a number that the remainder should be the same as that of the last digit. In order to extract the last digit that number with which the given number has to be divided must be 10." }, { "code": null, "e": 749, "s": 687, "text": "Modulo is represented by ‘%’ and is used to get the remainder" }, { "code": null, "e": 799, "s": 749, "text": "Example: Extracting Last One Digit From A Number " }, { "code": null, "e": 1000, "s": 799, "text": "Random Number = 1997\nLast Digit = 7\nGoal: 1997 % (x) = 7 // Goal is Divide 1997 by x such that remainder is 7\n if x = 10 // 1997 % 10 = 7 that is the last digit \n" }, { "code": null, "e": 1182, "s": 1000, "text": "Now, in order to extract the last two digits, we will be treating the number with the same approach just the given number will be modulo by 100 as per the mathematics unit standard." }, { "code": null, "e": 1236, "s": 1182, "text": "Example: Extracting the Last Two-Digit From A Number " }, { "code": null, "e": 1338, "s": 1236, "text": "Input : year = 2020\nOutput : 20\n\nInput : year = 1983\nOutput : 83\n\nInput : year = 2000\nOutput : 00\n" }, { "code": null, "e": 1387, "s": 1338, "text": "We can implement this using 2 different methods:" }, { "code": null, "e": 1420, "s": 1387, "text": "Using Modulo Arithmetic Operator" }, { "code": null, "e": 1452, "s": 1420, "text": "Using String substring() method" }, { "code": null, "e": 1596, "s": 1452, "text": "A. Using Modulo Arithmetic Operator: We can use the modulo operator (%) to extract the last two digits by taking the modulo of the year by 100." }, { "code": null, "e": 1640, "s": 1596, "text": "Internal Working Of Mathematics Unit System" }, { "code": null, "e": 1885, "s": 1640, "text": "Let us consider 1983, we can write it as \n1983 = 1*1000 + 9*100 + 8*10 + 3\nSo when we take modulo by 100, we will just have the last two digits as remainder.\n1983 % 100 = 1*1000 % 100 + 9*100 % 100 + 8*10 % 100 + 3 % 100 = 0 + 0 + 8*10 + 3 = 83" }, { "code": null, "e": 1945, "s": 1885, "text": "The implementation of the above approach is described below" }, { "code": null, "e": 1950, "s": 1945, "text": "Java" }, { "code": "// Java code to extract last two digits of a year // Importing Classes/Filesimport java.util.*; public class GFG { // Main Driver Code public static void main(String args[]) { // Initializing year as String int year = 1983; // Printing last two digits of a number // by modulo with 100 System.out.print(year % 100); }}", "e": 2322, "s": 1950, "text": null }, { "code": null, "e": 2325, "s": 2322, "text": "83" }, { "code": null, "e": 2516, "s": 2325, "text": "B. Using String substring() method: This method returns a new string that is a substring of the given string. Thus, to extract the last two digits we need to get the substring after index 2." }, { "code": null, "e": 2521, "s": 2516, "text": "Java" }, { "code": "// Java code to extract last two digits of a yearpublic class GFG { // Function to extract last to digits of a year static int extractLastTwo(String year) { // using substring() to extract the last two digit // as substring String lastTwoDigits = year.substring(2); return Integer.parseInt( lastTwoDigits); // Returning last two digits as // an integer } public static void main(String args[]) { // Initializing year as String String year = \"1983\"; System.out.print(extractLastTwo(year)); }}", "e": 3129, "s": 2521, "text": null }, { "code": null, "e": 3132, "s": 3129, "text": "83" }, { "code": null, "e": 3137, "s": 3132, "text": "Java" }, { "code": null, "e": 3151, "s": 3137, "text": "Java Programs" }, { "code": null, "e": 3156, "s": 3151, "text": "Java" } ]
Goldeneye DDos Tool in Kali Linux
24 Jun, 2021 Goldeneye is a free and Open source tool available on GitHub. We can perform a denial of service attack using this tool. It’s a framework written in .NET Core. This tool provides many base classes and extensions to use with your daily work. This tool allows a single machine to take down another machine’s web server it uses perfectly legitimate HTTP traffic. It makes a full TCP connection and then requires only a few hundred requests at long-term and regular intervals. As a result, the tool doesn’t need to use a lot of traffic to exhaust the available connections on a server. Goldeneye uses perfectly legitimate HTTP traffic. Deniel of service attack can be executed with the help of Goldeneye by generating heavy traffic of botnets. Goldeneye sends multiple requests to the target as a result generates heavy traffic botnets. Goldeneye is an open-source tool, so you can download it from GitHub free of cost. Goldeneye can be used to perform ddos attacks on any webserver. Step 1: Open your Kali Linux and then Open your Terminal. Use the following command to install the tool. git clone https://github.com/jseidl/GoldenEye.git Step 2: Use the following command to move to Goldeneye directory. cd GoldenEye Step 3: Use the following command to list out the contents of the directory. ls Step 4: The tool is running successfully now. Example 1: Use the GoldenEye tool to perform DDoS attack on any domain. ./goldeneye.py https://www.google.com -s 1000 The tool is running successfully and started attacking the domain www.google.com. This tool is useful for security researchers. Example 2: To display all usage options of the golden eye tool, type the following command sudo ./goldeneye.py -h Example 3: To send traffic in ‘random’ mode with 5 workers running 10 connections each sudo ./goldeneye.py http://192.168.0.233:80/ -s 10 -m random Example 4: Use the GoldenEye tool to send traffic to the target machine and capture traffic on Wireshark tool. Wireshark The tool will start hitting the server. Now open Wireshark and capture packets. The tool is running successfully and started attacking the domain and the Wireshark is capturing the packets. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jun, 2021" }, { "code": null, "e": 636, "s": 53, "text": "Goldeneye is a free and Open source tool available on GitHub. We can perform a denial of service attack using this tool. It’s a framework written in .NET Core. This tool provides many base classes and extensions to use with your daily work. This tool allows a single machine to take down another machine’s web server it uses perfectly legitimate HTTP traffic. It makes a full TCP connection and then requires only a few hundred requests at long-term and regular intervals. As a result, the tool doesn’t need to use a lot of traffic to exhaust the available connections on a server. " }, { "code": null, "e": 686, "s": 636, "text": "Goldeneye uses perfectly legitimate HTTP traffic." }, { "code": null, "e": 794, "s": 686, "text": "Deniel of service attack can be executed with the help of Goldeneye by generating heavy traffic of botnets." }, { "code": null, "e": 887, "s": 794, "text": "Goldeneye sends multiple requests to the target as a result generates heavy traffic botnets." }, { "code": null, "e": 970, "s": 887, "text": "Goldeneye is an open-source tool, so you can download it from GitHub free of cost." }, { "code": null, "e": 1034, "s": 970, "text": "Goldeneye can be used to perform ddos attacks on any webserver." }, { "code": null, "e": 1139, "s": 1034, "text": "Step 1: Open your Kali Linux and then Open your Terminal. Use the following command to install the tool." }, { "code": null, "e": 1189, "s": 1139, "text": "git clone https://github.com/jseidl/GoldenEye.git" }, { "code": null, "e": 1255, "s": 1189, "text": "Step 2: Use the following command to move to Goldeneye directory." }, { "code": null, "e": 1268, "s": 1255, "text": "cd GoldenEye" }, { "code": null, "e": 1345, "s": 1268, "text": "Step 3: Use the following command to list out the contents of the directory." }, { "code": null, "e": 1348, "s": 1345, "text": "ls" }, { "code": null, "e": 1394, "s": 1348, "text": "Step 4: The tool is running successfully now." }, { "code": null, "e": 1466, "s": 1394, "text": "Example 1: Use the GoldenEye tool to perform DDoS attack on any domain." }, { "code": null, "e": 1512, "s": 1466, "text": "./goldeneye.py https://www.google.com -s 1000" }, { "code": null, "e": 1640, "s": 1512, "text": "The tool is running successfully and started attacking the domain www.google.com. This tool is useful for security researchers." }, { "code": null, "e": 1731, "s": 1640, "text": "Example 2: To display all usage options of the golden eye tool, type the following command" }, { "code": null, "e": 1754, "s": 1731, "text": "sudo ./goldeneye.py -h" }, { "code": null, "e": 1841, "s": 1754, "text": "Example 3: To send traffic in ‘random’ mode with 5 workers running 10 connections each" }, { "code": null, "e": 1903, "s": 1841, "text": "sudo ./goldeneye.py http://192.168.0.233:80/ -s 10 -m random" }, { "code": null, "e": 2014, "s": 1903, "text": "Example 4: Use the GoldenEye tool to send traffic to the target machine and capture traffic on Wireshark tool." }, { "code": null, "e": 2024, "s": 2014, "text": "Wireshark" }, { "code": null, "e": 2104, "s": 2024, "text": "The tool will start hitting the server. Now open Wireshark and capture packets." }, { "code": null, "e": 2215, "s": 2104, "text": "The tool is running successfully and started attacking the domain and the Wireshark is capturing the packets. " }, { "code": null, "e": 2226, "s": 2215, "text": "Kali-Linux" }, { "code": null, "e": 2238, "s": 2226, "text": "Linux-Tools" }, { "code": null, "e": 2249, "s": 2238, "text": "Linux-Unix" } ]
Top 5 PSUs for Computer Science Engineers in India
13 Mar, 2020 Every year, the Public Sector Undertakings(PSUs) of India offers an ample amount of employment opportunities (especially for Engineering Graduates!). And who wouldn’t want to work in such prestigious Government organizations like IOCL, DRDO, ONGC, etc? (Everyone wants!) There may be many other reasons too why a number of people aspire to make a career in Indian PSUs such as job security (Yes, it is worthy to have a stable job in today’s unstable employing environment), prestige, various allowances, etc. So, what are these PSUs? Public Sector Undertakings (PSUs) are the organizations that are completely or partially owned (51% or more share) by the Government and are classified as Maharatna, Navratna, Miniratna (Category I & II) based on their net worth and annual turnover. There are nearly 300 Public Sector Undertakings in India. PSUs generally recruit the candidates through the competitive examination or on the basis of GATE Scores or in some cases, the candidates are directly recruited during their campus placements from the top institutes such as IITs, IIMs, IISC, etc. In Indian PSUs, the average CTC of employees is around 12-15 Lakhs Per Annum. However, there is a misconception that there are not enough opportunities in PSUs for those who belong to the Computer Science domain. But the real scenario is somewhat different as there are many PSUs that recruit candidates from the CS / IT field. Here, in this article, we will let you know about the Top 5 PSUs for Computer Science Engineers in India with all the details such as eligibility, recruitment process, salary, etc. Indian Oil Corporation Limited (IOCL) is one of the prestigious Public Sector Undertaking and the largest commercial oil company in India. IOCL, entitled with the ‘Maharatna’ stature, has been accomplishing the energy demand of the country for nearly the last 60 years (yes, its almost 6 decades!). The company is having around 33, 500 employees with a revenue of approx. Rs. 606, 000 crore (as of 2019). IOCL offers career opportunities to CS / IT candidates by recruiting them for the profile of Engineers / Officers. The candidates recruited as Engineers / Officers in IOCL are posted in one of the various disciplines of the organization such as Information Systems, Refineries, etc. Let’s take a look at eligibility criteria, selection process and other aspects of the job profile. Educational Eligibility: B.E./B.Tech (Computer Science & Information Technology) with at least 65% marks. Age Limit: The age of the candidate must be a maximum of 26 years as of the year of recruitment. There is a relaxation in age limit for reserved categories. Selection Process: The candidates are shortlisted on the basis of valid GATE scorecard followed by the Group Discussion/Group Task & Personal Interview. Pay Scale: Candidates recruited as Engineers / Officers receive a starting basic pay of Rs. 60,000/- per month along with various allowances such as HRA, DA, etc. The gross remuneration to the organization is around 17 Lakhs per Annum including performance-related pay. Bhabha Atomic Research Centre (BARC), headquartered in Mumbai (Maharashtra), is the nation’s premier nuclear research center. It has an immense infrastructure for various advanced research and development processes. BARC offers career opportunities to CS/IT candidates by recruiting them for the profile of Scientific Officers. The candidates are recruited after the successful completion of training in Orientation Course for Engineering Graduates & Science Postgraduates (OCES)/DAE Graduate Fellowship Scheme for Engineering Graduates & Physics Postgraduates (DGFS). Let’s take a look at eligibility criteria, selection process and other aspects of the job profile. Educational Eligibility: B.E. / B.Tech. / B.Sc. (Engineering) / 5 year Integrated M.Tech in Computer Science discipline with atleast 60% aggregate marks. Age Limit: The age of the candidate must be a maximum of 26 years as of the year of recruitment (Relaxation in age limit for reserved categories). Selection Process: The selection to OCES / DGFS is done through the Screening Round followed by the Selection Interview and Medical Fitness round. The screening of the candidates for the selection interview is done in two ways – either by an Online Screening Test or through GATE score. Candidates can choose any one or both of the mentioned screening alternatives. Pay Scale: Candidates appointed as a Scientific Officer ‘C’ receive a basic pay of Rs. 56,100/- per month along with various allowances such as HRA, DA, etc. Oil and Natural Gas Corporation (ONGC), headquartered in New Delhi, India, is a multinational Crude Oil and Gas Corporation. ONGC produces nearly 70% of the nation’s crude oil and holds the ‘Maharatna’ status. The company is having around 34, 000 employees with a revenue of approx. Rs. 876,487 crore (as of 2019). ONGC offers one of the best career opportunities (at E-1 Level) to CS/IT candidates by recruiting them for the profile of Programming Officers. The recruited candidates can be posted anywhere in India or other countries as per the requirements of the organization. Let’s take a look at eligibility criteria, selection process and other aspects of the job profile. Educational Eligibility: B.E. / B.Tech. in Computer Science / Information Technology discipline with at least 60% marks. The Postgraduates in Computer Applications (MCA) and Computer Science are also eligible. Age Limit: The age of the candidate must be a maximum of 30 years as of the year of recruitment (Relaxation in age limit for reserved categories). Selection Process: The selection of the candidates is done on the basis of valid GATE scorecard followed by the Personal Interview process. Pay Scale: Candidates recruited as a Programming Officer receive a basic salary of Rs. 60,000 – 1,80,000 per month along with an annual increment of 3% and various allowances such as Dearness Allowance, HRA, Performance Related Pay, etc. Power System Operation Corporation (POSOCO) is an enterprise that manages the power system operations and comes under the Government of India. POSOCO is responsible for the efficient and steady functioning of the integrated operations of the Grid and it also operates 5 Regional Load Despatch Centres along with a National Load Despatch Centre. POSOCO offers career opportunities in the disciplines of Computer Science by recruiting for the profile of Executive Trainees. The selected candidates are liable to be posted anywhere in India and other countries as per the requirements of the organization. Let’s take a look at eligibility criteria, selection process and other aspects of the job profile. Educational Eligibility: B.E. / B.Tech. / B.Sc (Engineering) in Computer Science / Information Technology discipline with at least 65% marks. Age Limit: The age of the candidate must be a maximum of 28 years as of the year of recruitment (Relaxation in age limit for reserved categories). Selection Process: The selection of the candidates is done on the basis of valid GATE scorecard followed by the Group Discussion and Personal Interview. Pay Scale: Candidates recruited as an Executive Trainee in Power System Operation Corporation Ltd. receive a basic salary of Rs. 60,000 – 1,80,000 per month along with various allowances such as Performance Related Pay, Group Insurance, Gratuity, etc. Defense Research and Development Organisation (DRDO), headquartered in Delhi (India), is the nation’s premier military research and development organization that comes under the Government of India. Having around 30,000 working professionals (including 5000 scientists), DRDO is empowering the nation for nearly the last 60 years. DRDO offers career opportunities for CS/IT candidates by recruiting for the profile of Junior Research Fellow (JRF). Let’s take a look at eligibility criteria, selection process and other aspects of the job profile. Educational Eligibility: B.E. / B.Tech. in Computer Science discipline with valid NET / SLET/ GATE Score or M.E. / M.Tech. in Computer Science discipline passed with the first-class division. Age Limit: The age of the candidate must be a maximum of 28 years as of the year of recruitment (Relaxation in age limit for reserved categories). Selection Process: The selection of the candidates is done on the basis of valid GATE scorecard followed by the Written Test and Interview. Pay Scale: Candidates recruited as a Junior Research Fellow in DRDO receive a basic salary of Rs. 31,000 per month along with various allowances such as HRA, DA, etc. Now, if you are a CS/IT candidate and want to make a career in Indian PSUs then you can consider the above-mentioned organizations. However, regardless of the job profile, it is your hard work and determination that leads you to the success point. So, work hard and achieve your goals!! Career-Advices GATE CS GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Mar, 2020" }, { "code": null, "e": 563, "s": 54, "text": "Every year, the Public Sector Undertakings(PSUs) of India offers an ample amount of employment opportunities (especially for Engineering Graduates!). And who wouldn’t want to work in such prestigious Government organizations like IOCL, DRDO, ONGC, etc? (Everyone wants!) There may be many other reasons too why a number of people aspire to make a career in Indian PSUs such as job security (Yes, it is worthy to have a stable job in today’s unstable employing environment), prestige, various allowances, etc." }, { "code": null, "e": 1221, "s": 563, "text": "So, what are these PSUs? Public Sector Undertakings (PSUs) are the organizations that are completely or partially owned (51% or more share) by the Government and are classified as Maharatna, Navratna, Miniratna (Category I & II) based on their net worth and annual turnover. There are nearly 300 Public Sector Undertakings in India. PSUs generally recruit the candidates through the competitive examination or on the basis of GATE Scores or in some cases, the candidates are directly recruited during their campus placements from the top institutes such as IITs, IIMs, IISC, etc. In Indian PSUs, the average CTC of employees is around 12-15 Lakhs Per Annum." }, { "code": null, "e": 1652, "s": 1221, "text": "However, there is a misconception that there are not enough opportunities in PSUs for those who belong to the Computer Science domain. But the real scenario is somewhat different as there are many PSUs that recruit candidates from the CS / IT field. Here, in this article, we will let you know about the Top 5 PSUs for Computer Science Engineers in India with all the details such as eligibility, recruitment process, salary, etc." }, { "code": null, "e": 2439, "s": 1652, "text": "Indian Oil Corporation Limited (IOCL) is one of the prestigious Public Sector Undertaking and the largest commercial oil company in India. IOCL, entitled with the ‘Maharatna’ stature, has been accomplishing the energy demand of the country for nearly the last 60 years (yes, its almost 6 decades!). The company is having around 33, 500 employees with a revenue of approx. Rs. 606, 000 crore (as of 2019). IOCL offers career opportunities to CS / IT candidates by recruiting them for the profile of Engineers / Officers. The candidates recruited as Engineers / Officers in IOCL are posted in one of the various disciplines of the organization such as Information Systems, Refineries, etc. Let’s take a look at eligibility criteria, selection process and other aspects of the job profile." }, { "code": null, "e": 2545, "s": 2439, "text": "Educational Eligibility: B.E./B.Tech (Computer Science & Information Technology) with at least 65% marks." }, { "code": null, "e": 2702, "s": 2545, "text": "Age Limit: The age of the candidate must be a maximum of 26 years as of the year of recruitment. There is a relaxation in age limit for reserved categories." }, { "code": null, "e": 2855, "s": 2702, "text": "Selection Process: The candidates are shortlisted on the basis of valid GATE scorecard followed by the Group Discussion/Group Task & Personal Interview." }, { "code": null, "e": 3125, "s": 2855, "text": "Pay Scale: Candidates recruited as Engineers / Officers receive a starting basic pay of Rs. 60,000/- per month along with various allowances such as HRA, DA, etc. The gross remuneration to the organization is around 17 Lakhs per Annum including performance-related pay." }, { "code": null, "e": 3793, "s": 3125, "text": "Bhabha Atomic Research Centre (BARC), headquartered in Mumbai (Maharashtra), is the nation’s premier nuclear research center. It has an immense infrastructure for various advanced research and development processes. BARC offers career opportunities to CS/IT candidates by recruiting them for the profile of Scientific Officers. The candidates are recruited after the successful completion of training in Orientation Course for Engineering Graduates & Science Postgraduates (OCES)/DAE Graduate Fellowship Scheme for Engineering Graduates & Physics Postgraduates (DGFS). Let’s take a look at eligibility criteria, selection process and other aspects of the job profile." }, { "code": null, "e": 3947, "s": 3793, "text": "Educational Eligibility: B.E. / B.Tech. / B.Sc. (Engineering) / 5 year Integrated M.Tech in Computer Science discipline with atleast 60% aggregate marks." }, { "code": null, "e": 4094, "s": 3947, "text": "Age Limit: The age of the candidate must be a maximum of 26 years as of the year of recruitment (Relaxation in age limit for reserved categories)." }, { "code": null, "e": 4460, "s": 4094, "text": "Selection Process: The selection to OCES / DGFS is done through the Screening Round followed by the Selection Interview and Medical Fitness round. The screening of the candidates for the selection interview is done in two ways – either by an Online Screening Test or through GATE score. Candidates can choose any one or both of the mentioned screening alternatives." }, { "code": null, "e": 4618, "s": 4460, "text": "Pay Scale: Candidates appointed as a Scientific Officer ‘C’ receive a basic pay of Rs. 56,100/- per month along with various allowances such as HRA, DA, etc." }, { "code": null, "e": 5297, "s": 4618, "text": "Oil and Natural Gas Corporation (ONGC), headquartered in New Delhi, India, is a multinational Crude Oil and Gas Corporation. ONGC produces nearly 70% of the nation’s crude oil and holds the ‘Maharatna’ status. The company is having around 34, 000 employees with a revenue of approx. Rs. 876,487 crore (as of 2019). ONGC offers one of the best career opportunities (at E-1 Level) to CS/IT candidates by recruiting them for the profile of Programming Officers. The recruited candidates can be posted anywhere in India or other countries as per the requirements of the organization. Let’s take a look at eligibility criteria, selection process and other aspects of the job profile." }, { "code": null, "e": 5507, "s": 5297, "text": "Educational Eligibility: B.E. / B.Tech. in Computer Science / Information Technology discipline with at least 60% marks. The Postgraduates in Computer Applications (MCA) and Computer Science are also eligible." }, { "code": null, "e": 5654, "s": 5507, "text": "Age Limit: The age of the candidate must be a maximum of 30 years as of the year of recruitment (Relaxation in age limit for reserved categories)." }, { "code": null, "e": 5794, "s": 5654, "text": "Selection Process: The selection of the candidates is done on the basis of valid GATE scorecard followed by the Personal Interview process." }, { "code": null, "e": 6032, "s": 5794, "text": "Pay Scale: Candidates recruited as a Programming Officer receive a basic salary of Rs. 60,000 – 1,80,000 per month along with an annual increment of 3% and various allowances such as Dearness Allowance, HRA, Performance Related Pay, etc." }, { "code": null, "e": 6734, "s": 6032, "text": "Power System Operation Corporation (POSOCO) is an enterprise that manages the power system operations and comes under the Government of India. POSOCO is responsible for the efficient and steady functioning of the integrated operations of the Grid and it also operates 5 Regional Load Despatch Centres along with a National Load Despatch Centre. POSOCO offers career opportunities in the disciplines of Computer Science by recruiting for the profile of Executive Trainees. The selected candidates are liable to be posted anywhere in India and other countries as per the requirements of the organization. Let’s take a look at eligibility criteria, selection process and other aspects of the job profile." }, { "code": null, "e": 6876, "s": 6734, "text": "Educational Eligibility: B.E. / B.Tech. / B.Sc (Engineering) in Computer Science / Information Technology discipline with at least 65% marks." }, { "code": null, "e": 7023, "s": 6876, "text": "Age Limit: The age of the candidate must be a maximum of 28 years as of the year of recruitment (Relaxation in age limit for reserved categories)." }, { "code": null, "e": 7176, "s": 7023, "text": "Selection Process: The selection of the candidates is done on the basis of valid GATE scorecard followed by the Group Discussion and Personal Interview." }, { "code": null, "e": 7428, "s": 7176, "text": "Pay Scale: Candidates recruited as an Executive Trainee in Power System Operation Corporation Ltd. receive a basic salary of Rs. 60,000 – 1,80,000 per month along with various allowances such as Performance Related Pay, Group Insurance, Gratuity, etc." }, { "code": null, "e": 7975, "s": 7428, "text": "Defense Research and Development Organisation (DRDO), headquartered in Delhi (India), is the nation’s premier military research and development organization that comes under the Government of India. Having around 30,000 working professionals (including 5000 scientists), DRDO is empowering the nation for nearly the last 60 years. DRDO offers career opportunities for CS/IT candidates by recruiting for the profile of Junior Research Fellow (JRF). Let’s take a look at eligibility criteria, selection process and other aspects of the job profile." }, { "code": null, "e": 8167, "s": 7975, "text": "Educational Eligibility: B.E. / B.Tech. in Computer Science discipline with valid NET / SLET/ GATE Score or M.E. / M.Tech. in Computer Science discipline passed with the first-class division." }, { "code": null, "e": 8314, "s": 8167, "text": "Age Limit: The age of the candidate must be a maximum of 28 years as of the year of recruitment (Relaxation in age limit for reserved categories)." }, { "code": null, "e": 8454, "s": 8314, "text": "Selection Process: The selection of the candidates is done on the basis of valid GATE scorecard followed by the Written Test and Interview." }, { "code": null, "e": 8621, "s": 8454, "text": "Pay Scale: Candidates recruited as a Junior Research Fellow in DRDO receive a basic salary of Rs. 31,000 per month along with various allowances such as HRA, DA, etc." }, { "code": null, "e": 8908, "s": 8621, "text": "Now, if you are a CS/IT candidate and want to make a career in Indian PSUs then you can consider the above-mentioned organizations. However, regardless of the job profile, it is your hard work and determination that leads you to the success point. So, work hard and achieve your goals!!" }, { "code": null, "e": 8923, "s": 8908, "text": "Career-Advices" }, { "code": null, "e": 8931, "s": 8923, "text": "GATE CS" }, { "code": null, "e": 8937, "s": 8931, "text": "GBlog" } ]
Hadoop – Reducer in Map-Reduce
21 Feb, 2022 Map-Reduce is a programming model that is mainly divided into two phases i.e. Map Phase and Reduce Phase. It is designed for processing the data in parallel which is divided on various machines(nodes). The Hadoop Java programs are consist of Mapper class and Reducer class along with the driver class. Reducer is the second part of the Map-Reduce programming model. The Mapper produces the output in the form of key-value pairs which works as input for the Reducer. But before sending this intermediate key-value pairs directly to the Reducer some process will be done which shuffle and sort the key-value pairs according to its key values, which means the value of the key is the main decisive factor for sorting. The output generated by the Reducer will be the final output which is then stored on HDFS(Hadoop Distributed File System). Reducer mainly performs some computation operation like addition, filtration, and aggregation. By default, the number of reducers utilized for process the output of the Mapper is 1 which is configurable and can be changed by the user according to the requirement. Let’s understand the Reducer in Map-Reduce: Here, in the above image, we can observe that there are multiple Mapper which are generating the key-value pairs as output. The output of each mapper is sent to the sorter which will sort the key-value pairs according to its key value. Shuffling also takes place during the sorting process and the output will be sent to the Reducer part and final output is produced. Let’s take an example to understand the working of Reducer. Suppose we have the data of a college faculty of all departments stored in a CSV file. In case we want to find the sum of salaries of faculty according to their department then we can make their dept. title as key and salaries as value. The Reducer will perform the summation operation on this dataset and produce the desired output. The number of Reducers in Map-Reduce task also affects below features: Framework overhead increases.Cost of failure ReducesIncrease load balancing. Framework overhead increases. Cost of failure Reduces Increase load balancing. One thing we also need to remember is that there will always be a one to one mapping between Reducers and the keys. Once the whole Reducer process is done the output is stored at the part file(default name) on HDFS(Hadoop Distributed File System). In the output directory on HDFS, The Map-Reduce always makes a _SUCCESS file and part-r-00000 file. The number of part files depends on the number of reducers in case we have 5 Reducers then the number of the part file will be from part-r-00000 to part-r-00004. By default, these files have the name of part-a-bbbbb type. It can be changed manually all we need to do is to change the below property in our driver code of Map-Reduce. // Here we are changing output file name from part-r-00000 to GeeksForGeeks job.getConfiguration().set("mapreduce.output.basename", "GeeksForGeeks") The Reducer Of Map-Reduce is consist of mainly 3 processes/phases: Shuffle: Shuffling helps to carry data from the Mapper to the required Reducer. With the help of HTTP, the framework calls for applicable partition of the output in all Mappers.Sort: In this phase, the output of the mapper that is actually the key-value pairs will be sorted on the basis of its key value.Reduce: Once shuffling and sorting will be done the Reducer combines the obtained result and perform the computation operation as per the requirement. OutputCollector.collect() property is used for writing the output to the HDFS. Keep remembering that the output of the Reducer will not be sorted. Shuffle: Shuffling helps to carry data from the Mapper to the required Reducer. With the help of HTTP, the framework calls for applicable partition of the output in all Mappers. Sort: In this phase, the output of the mapper that is actually the key-value pairs will be sorted on the basis of its key value. Reduce: Once shuffling and sorting will be done the Reducer combines the obtained result and perform the computation operation as per the requirement. OutputCollector.collect() property is used for writing the output to the HDFS. Keep remembering that the output of the Reducer will not be sorted. Note: Shuffling and Sorting both execute in parallel. Setting Number Of Reducers In Map-Reduce: With Command Line: While executing our Map-Reduce program we can manually change the number of Reducer with controller mapred.reduce.tasks. With JobConf instance: In our driver class, we can specify the number of reducers using the instance of job.setNumReduceTasks(int). For example job.setNumReduceTasks(2), Here we have 2 Reducers. we can also make Reducers to 0 in case we need only a Map job. With Command Line: While executing our Map-Reduce program we can manually change the number of Reducer with controller mapred.reduce.tasks. With JobConf instance: In our driver class, we can specify the number of reducers using the instance of job.setNumReduceTasks(int). For example job.setNumReduceTasks(2), Here we have 2 Reducers. we can also make Reducers to 0 in case we need only a Map job. // Ideally The number of Reducers in a Map-Reduce must be set to: 0.95 or 1.75 multiplied by (<no. of nodes> * <no. of maximum containers per node>) sagar0719kumar MapReduce Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2022" }, { "code": null, "e": 495, "s": 28, "text": "Map-Reduce is a programming model that is mainly divided into two phases i.e. Map Phase and Reduce Phase. It is designed for processing the data in parallel which is divided on various machines(nodes). The Hadoop Java programs are consist of Mapper class and Reducer class along with the driver class. Reducer is the second part of the Map-Reduce programming model. The Mapper produces the output in the form of key-value pairs which works as input for the Reducer. " }, { "code": null, "e": 1131, "s": 495, "text": "But before sending this intermediate key-value pairs directly to the Reducer some process will be done which shuffle and sort the key-value pairs according to its key values, which means the value of the key is the main decisive factor for sorting. The output generated by the Reducer will be the final output which is then stored on HDFS(Hadoop Distributed File System). Reducer mainly performs some computation operation like addition, filtration, and aggregation. By default, the number of reducers utilized for process the output of the Mapper is 1 which is configurable and can be changed by the user according to the requirement." }, { "code": null, "e": 1175, "s": 1131, "text": "Let’s understand the Reducer in Map-Reduce:" }, { "code": null, "e": 1544, "s": 1175, "text": "Here, in the above image, we can observe that there are multiple Mapper which are generating the key-value pairs as output. The output of each mapper is sent to the sorter which will sort the key-value pairs according to its key value. Shuffling also takes place during the sorting process and the output will be sent to the Reducer part and final output is produced. " }, { "code": null, "e": 1939, "s": 1544, "text": "Let’s take an example to understand the working of Reducer. Suppose we have the data of a college faculty of all departments stored in a CSV file. In case we want to find the sum of salaries of faculty according to their department then we can make their dept. title as key and salaries as value. The Reducer will perform the summation operation on this dataset and produce the desired output. " }, { "code": null, "e": 2010, "s": 1939, "text": "The number of Reducers in Map-Reduce task also affects below features:" }, { "code": null, "e": 2087, "s": 2010, "text": "Framework overhead increases.Cost of failure ReducesIncrease load balancing." }, { "code": null, "e": 2117, "s": 2087, "text": "Framework overhead increases." }, { "code": null, "e": 2141, "s": 2117, "text": "Cost of failure Reduces" }, { "code": null, "e": 2166, "s": 2141, "text": "Increase load balancing." }, { "code": null, "e": 2847, "s": 2166, "text": "One thing we also need to remember is that there will always be a one to one mapping between Reducers and the keys. Once the whole Reducer process is done the output is stored at the part file(default name) on HDFS(Hadoop Distributed File System). In the output directory on HDFS, The Map-Reduce always makes a _SUCCESS file and part-r-00000 file. The number of part files depends on the number of reducers in case we have 5 Reducers then the number of the part file will be from part-r-00000 to part-r-00004. By default, these files have the name of part-a-bbbbb type. It can be changed manually all we need to do is to change the below property in our driver code of Map-Reduce." }, { "code": null, "e": 2996, "s": 2847, "text": "// Here we are changing output file name from part-r-00000 to GeeksForGeeks\njob.getConfiguration().set(\"mapreduce.output.basename\", \"GeeksForGeeks\")" }, { "code": null, "e": 3064, "s": 2996, "text": "The Reducer Of Map-Reduce is consist of mainly 3 processes/phases:" }, { "code": null, "e": 3667, "s": 3064, "text": "Shuffle: Shuffling helps to carry data from the Mapper to the required Reducer. With the help of HTTP, the framework calls for applicable partition of the output in all Mappers.Sort: In this phase, the output of the mapper that is actually the key-value pairs will be sorted on the basis of its key value.Reduce: Once shuffling and sorting will be done the Reducer combines the obtained result and perform the computation operation as per the requirement. OutputCollector.collect() property is used for writing the output to the HDFS. Keep remembering that the output of the Reducer will not be sorted." }, { "code": null, "e": 3845, "s": 3667, "text": "Shuffle: Shuffling helps to carry data from the Mapper to the required Reducer. With the help of HTTP, the framework calls for applicable partition of the output in all Mappers." }, { "code": null, "e": 3974, "s": 3845, "text": "Sort: In this phase, the output of the mapper that is actually the key-value pairs will be sorted on the basis of its key value." }, { "code": null, "e": 4272, "s": 3974, "text": "Reduce: Once shuffling and sorting will be done the Reducer combines the obtained result and perform the computation operation as per the requirement. OutputCollector.collect() property is used for writing the output to the HDFS. Keep remembering that the output of the Reducer will not be sorted." }, { "code": null, "e": 4326, "s": 4272, "text": "Note: Shuffling and Sorting both execute in parallel." }, { "code": null, "e": 4368, "s": 4326, "text": "Setting Number Of Reducers In Map-Reduce:" }, { "code": null, "e": 4768, "s": 4368, "text": "With Command Line: While executing our Map-Reduce program we can manually change the number of Reducer with controller mapred.reduce.tasks. With JobConf instance: In our driver class, we can specify the number of reducers using the instance of job.setNumReduceTasks(int). For example job.setNumReduceTasks(2), Here we have 2 Reducers. we can also make Reducers to 0 in case we need only a Map job." }, { "code": null, "e": 4911, "s": 4768, "text": "With Command Line: While executing our Map-Reduce program we can manually change the number of Reducer with controller mapred.reduce.tasks. " }, { "code": null, "e": 5169, "s": 4911, "text": "With JobConf instance: In our driver class, we can specify the number of reducers using the instance of job.setNumReduceTasks(int). For example job.setNumReduceTasks(2), Here we have 2 Reducers. we can also make Reducers to 0 in case we need only a Map job." }, { "code": null, "e": 5319, "s": 5169, "text": "// Ideally The number of Reducers in a Map-Reduce must be set to:\n0.95 or 1.75 multiplied by (<no. of nodes> * <no. of maximum containers per node>)" }, { "code": null, "e": 5334, "s": 5319, "text": "sagar0719kumar" }, { "code": null, "e": 5344, "s": 5334, "text": "MapReduce" }, { "code": null, "e": 5351, "s": 5344, "text": "Hadoop" }, { "code": null, "e": 5358, "s": 5351, "text": "Hadoop" } ]
How to get the new image URL after refreshing the image using JavaScript ?
13 Jun, 2022 The browser cache relies on the image URL to decide whether the image is the same or not and whether to use the stored version. It means if we change something within the URL and then attempt to reload the image, the cache will no longer be able to change that it is the same resource. The cache will fetch it again from the server. Approach: To change the URL without affecting the image, you can change the parameter that can be attached to the end of the URL. The parameter needs to be unique. We can use a timestamp, the URL will always be unique. To refresh the image in JavaScript, we can simply select the img element and modify its src attribute to be that of the target image, along with the timestamp parameter to ensure it does not access it from the cache. Example: HTML <!DOCTYPE html><html> <head> <title>Refresh Image</title></head> <body> <!-- Display the image --> <img id="gfgimage" src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-20.png" width="500" /> <script> // Create a timestamp var timestamp = new Date().getTime(); // Get the image element var image = document.getElementById("gfgimage"); // Adding the timestamp parameter to image src image.src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-20.png?t=" + timestamp; console.log(image.src); </script> </body> </html> Output: Now, even if the image is replaced with a new image it will load the new image. In general, this may have some performance issues as it won’t be using the image from the cache and will have to use the image from the server always. HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. sanjyotpanure JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 385, "s": 52, "text": "The browser cache relies on the image URL to decide whether the image is the same or not and whether to use the stored version. It means if we change something within the URL and then attempt to reload the image, the cache will no longer be able to change that it is the same resource. The cache will fetch it again from the server." }, { "code": null, "e": 604, "s": 385, "text": "Approach: To change the URL without affecting the image, you can change the parameter that can be attached to the end of the URL. The parameter needs to be unique. We can use a timestamp, the URL will always be unique." }, { "code": null, "e": 821, "s": 604, "text": "To refresh the image in JavaScript, we can simply select the img element and modify its src attribute to be that of the target image, along with the timestamp parameter to ensure it does not access it from the cache." }, { "code": null, "e": 830, "s": 821, "text": "Example:" }, { "code": null, "e": 835, "s": 830, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Refresh Image</title></head> <body> <!-- Display the image --> <img id=\"gfgimage\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-20.png\" width=\"500\" /> <script> // Create a timestamp var timestamp = new Date().getTime(); // Get the image element var image = document.getElementById(\"gfgimage\"); // Adding the timestamp parameter to image src image.src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-20.png?t=\" + timestamp; console.log(image.src); </script> </body> </html>", "e": 1463, "s": 835, "text": null }, { "code": null, "e": 1471, "s": 1463, "text": "Output:" }, { "code": null, "e": 1704, "s": 1473, "text": "Now, even if the image is replaced with a new image it will load the new image. In general, this may have some performance issues as it won’t be using the image from the cache and will have to use the image from the server always." }, { "code": null, "e": 1903, "s": 1704, "text": "HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 2122, "s": 1903, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 2136, "s": 2122, "text": "sanjyotpanure" }, { "code": null, "e": 2152, "s": 2136, "text": "JavaScript-Misc" }, { "code": null, "e": 2159, "s": 2152, "text": "Picked" }, { "code": null, "e": 2163, "s": 2159, "text": "CSS" }, { "code": null, "e": 2168, "s": 2163, "text": "HTML" }, { "code": null, "e": 2179, "s": 2168, "text": "JavaScript" }, { "code": null, "e": 2196, "s": 2179, "text": "Web Technologies" }, { "code": null, "e": 2223, "s": 2196, "text": "Web technologies Questions" }, { "code": null, "e": 2228, "s": 2223, "text": "HTML" } ]
Method Class | getGenericReturnType() Method in Java
21 Aug, 2021 The getGenericReturnType() method of java.lang.reflect.Method class returns a Type object that represent the return type, declared in method at time of coding. Hence, getGenericReturnType() method returns the return type of method object. If a formal return type is a parameterized type, the Type object returned for it must accurately reflect the actual type parameters used in the source code. For example, for method public T getValue(){}, if the type T is substituted with a parameterized type (i.e., List), then getGenericReturnType() will return “java.util.List<java.lang.String>” as return type. Syntax: public Type getGenericReturnType() Return Value: It returns a Type object that represent the formal return type of the method object. Exception: This method throws following exceptions: GenericSignatureFormatError – if the generic method signature is not same as the format specified in The JVM Specification. TypeNotPresentException – if return type refers to a non-existent type declaration. MalformedParameterizedTypeException – if the underlying return type refers to a parameterized type that cannot be instantiated for any reason. Examples: Code: public class demo{ public T getValue(){} } Explanation: In the above method when we going to apply getGenericReturnType() method it is going to return T as a generic return type. Code: public class demo{ public List getValue(){} } Explanation: In the above method when we going to apply getGenericReturnType() method it is going to return java.util.List<java.lang.String> as a generic return type Below programs illustrates getGenericReturnType() method of Method class Program 1: Print Return type of Method Object by applying getGenericReturnType() on a method. Java // Program to apply getGenericReturnType() method// of Method Class.import java.lang.reflect.Method;import java.lang.reflect.Type; public class GFG { // Main method public static void main(String[] args) { try { // create class object Class classobj = demoForReturnParam.class; // get Method Object Method[] methods = classobj.getMethods(); // iterate through methods for (Method method : methods) { // taking only method defined in the demo class if (method.getName().equals("setValue") || method.getName().equals("getValue") || method.getName().equals("setManyValues")) { // apply getGenericReturnType() method Type returnParam = method.getGenericReturnType(); // print return Types of method Object System.out.println("\nMethod Name : " + method.getName()); System.out.println("Return Type Details: " + returnParam); } } } catch (Exception e) { e.printStackTrace(); } }} // a simple classclass demoForReturnParam { // method returning int value public int setValue() { System.out.println("setValue"); return 24; } // method returning string value public String getValue() { System.out.println("getValue"); return "getValue"; } // method returning nothing public void setManyValues(int value1, String value3) { System.out.println("setManyValues"); }} Method Name : setManyValues Return Type Details: void Method Name : getValue Return Type Details: class java.lang.String Method Name : setValue Return Type Details: int Program 2: Giving a Return parameter type as input to check whether method object have same return type or not. Java // Program to show how to apply// getGenericReturnType() method of Method Classimport java.lang.reflect.Method;import java.lang.reflect.Type; public class GFG { // Main method public static void main(String[] args) { try { // create class object Class classobj = DemoForReturnParam.class; Method[] methods = classobj.getMethods(); // check whether setManyValues() method // contains string parameter or not for (Method method : methods) { if (method.getName().equals("setValue")) { boolean flag = containsReturnParameter(method, (Type)java.lang.String.class); System.out.println("setValue()" + " contains int return type: " + flag); } } // check whether setManyValues() method // contains int parameter or not for (Method method : methods) { if (method.getName().equals("setManyValues")) { boolean flag = containsReturnParameter(method, (Type) int.class); System.out.println("setManyValues()" + " contains int return type: " + flag); } } } catch (Exception e) { e.printStackTrace(); } } // check whether method object // have same return type or not private static boolean containsReturnParameter(Method method, Type parameterName) { // get return type using getGenericReturnType() Type returnParameter = method.getGenericReturnType(); // check contains return parameter or not if (returnParameter == parameterName) { return true; } return false; }} // a simple classclass DemoForReturnParam { // method returning int value public void setValue() { System.out.println("setValue"); } // method returning nothing public int setManyValues(int value1, String value3) { System.out.println("setManyValues"); return 21; }} setValue() contains int return type: false setManyValues() contains int return type: true Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getGenericReturnType– gulshankumarar231 Java-Functions Java-lang package java-lang-reflect-package Java-Method Class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Aug, 2021" }, { "code": null, "e": 267, "s": 28, "text": "The getGenericReturnType() method of java.lang.reflect.Method class returns a Type object that represent the return type, declared in method at time of coding. Hence, getGenericReturnType() method returns the return type of method object." }, { "code": null, "e": 631, "s": 267, "text": "If a formal return type is a parameterized type, the Type object returned for it must accurately reflect the actual type parameters used in the source code. For example, for method public T getValue(){}, if the type T is substituted with a parameterized type (i.e., List), then getGenericReturnType() will return “java.util.List<java.lang.String>” as return type." }, { "code": null, "e": 640, "s": 631, "text": "Syntax: " }, { "code": null, "e": 675, "s": 640, "text": "public Type getGenericReturnType()" }, { "code": null, "e": 774, "s": 675, "text": "Return Value: It returns a Type object that represent the formal return type of the method object." }, { "code": null, "e": 827, "s": 774, "text": "Exception: This method throws following exceptions: " }, { "code": null, "e": 951, "s": 827, "text": "GenericSignatureFormatError – if the generic method signature is not same as the format specified in The JVM Specification." }, { "code": null, "e": 1036, "s": 951, "text": "TypeNotPresentException – if return type refers to a non-existent type declaration. " }, { "code": null, "e": 1179, "s": 1036, "text": "MalformedParameterizedTypeException – if the underlying return type refers to a parameterized type that cannot be instantiated for any reason." }, { "code": null, "e": 1191, "s": 1179, "text": "Examples: " }, { "code": null, "e": 1605, "s": 1191, "text": "Code:\npublic class demo{\n public T getValue(){}\n}\nExplanation:\nIn the above method when we going to apply getGenericReturnType() method\nit is going to return T as a generic return type.\n\nCode:\npublic class demo{\n public List getValue(){}\n}\nExplanation:\nIn the above method when we going to apply getGenericReturnType() method\nit is going to return java.util.List<java.lang.String> as a generic return type" }, { "code": null, "e": 1679, "s": 1605, "text": "Below programs illustrates getGenericReturnType() method of Method class " }, { "code": null, "e": 1774, "s": 1679, "text": "Program 1: Print Return type of Method Object by applying getGenericReturnType() on a method. " }, { "code": null, "e": 1779, "s": 1774, "text": "Java" }, { "code": "// Program to apply getGenericReturnType() method// of Method Class.import java.lang.reflect.Method;import java.lang.reflect.Type; public class GFG { // Main method public static void main(String[] args) { try { // create class object Class classobj = demoForReturnParam.class; // get Method Object Method[] methods = classobj.getMethods(); // iterate through methods for (Method method : methods) { // taking only method defined in the demo class if (method.getName().equals(\"setValue\") || method.getName().equals(\"getValue\") || method.getName().equals(\"setManyValues\")) { // apply getGenericReturnType() method Type returnParam = method.getGenericReturnType(); // print return Types of method Object System.out.println(\"\\nMethod Name : \" + method.getName()); System.out.println(\"Return Type Details: \" + returnParam); } } } catch (Exception e) { e.printStackTrace(); } }} // a simple classclass demoForReturnParam { // method returning int value public int setValue() { System.out.println(\"setValue\"); return 24; } // method returning string value public String getValue() { System.out.println(\"getValue\"); return \"getValue\"; } // method returning nothing public void setManyValues(int value1, String value3) { System.out.println(\"setManyValues\"); }}", "e": 3523, "s": 1779, "text": null }, { "code": null, "e": 3694, "s": 3523, "text": "Method Name : setManyValues\nReturn Type Details: void\n\nMethod Name : getValue\nReturn Type Details: class java.lang.String\n\nMethod Name : setValue\nReturn Type Details: int" }, { "code": null, "e": 3808, "s": 3696, "text": "Program 2: Giving a Return parameter type as input to check whether method object have same return type or not." }, { "code": null, "e": 3813, "s": 3808, "text": "Java" }, { "code": "// Program to show how to apply// getGenericReturnType() method of Method Classimport java.lang.reflect.Method;import java.lang.reflect.Type; public class GFG { // Main method public static void main(String[] args) { try { // create class object Class classobj = DemoForReturnParam.class; Method[] methods = classobj.getMethods(); // check whether setManyValues() method // contains string parameter or not for (Method method : methods) { if (method.getName().equals(\"setValue\")) { boolean flag = containsReturnParameter(method, (Type)java.lang.String.class); System.out.println(\"setValue()\" + \" contains int return type: \" + flag); } } // check whether setManyValues() method // contains int parameter or not for (Method method : methods) { if (method.getName().equals(\"setManyValues\")) { boolean flag = containsReturnParameter(method, (Type) int.class); System.out.println(\"setManyValues()\" + \" contains int return type: \" + flag); } } } catch (Exception e) { e.printStackTrace(); } } // check whether method object // have same return type or not private static boolean containsReturnParameter(Method method, Type parameterName) { // get return type using getGenericReturnType() Type returnParameter = method.getGenericReturnType(); // check contains return parameter or not if (returnParameter == parameterName) { return true; } return false; }} // a simple classclass DemoForReturnParam { // method returning int value public void setValue() { System.out.println(\"setValue\"); } // method returning nothing public int setManyValues(int value1, String value3) { System.out.println(\"setManyValues\"); return 21; }}", "e": 6135, "s": 3813, "text": null }, { "code": null, "e": 6225, "s": 6135, "text": "setValue() contains int return type: false\nsetManyValues() contains int return type: true" }, { "code": null, "e": 6333, "s": 6227, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getGenericReturnType– " }, { "code": null, "e": 6351, "s": 6333, "text": "gulshankumarar231" }, { "code": null, "e": 6366, "s": 6351, "text": "Java-Functions" }, { "code": null, "e": 6384, "s": 6366, "text": "Java-lang package" }, { "code": null, "e": 6410, "s": 6384, "text": "java-lang-reflect-package" }, { "code": null, "e": 6428, "s": 6410, "text": "Java-Method Class" }, { "code": null, "e": 6433, "s": 6428, "text": "Java" }, { "code": null, "e": 6438, "s": 6433, "text": "Java" } ]
PyQt5 – Create translucent Push Button
22 Apr, 2020 In this article we will see how to create translucent button, here translucent refer as button which are not completely opaque. In order to do this, we have to change the alpha level of push button, alpha level is the opaque factor greater the value of alpha more the object is opaque, but unlike main window we can’t use setWindowOpacity method, therefore in order to change the alpha value we will use setStyleSheet method. Below is the difference between normal button and translucent button. Syntax : button.setStyleSheet(“color : rgba(0, 0, 0, 100)”) Argument : It takes string as argument. Here Rgba refer to red, green, blue and alpha level, they all vary from 0 to 255. Action performed : It will set the alpha level of push button Code : # importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton("CLICK", self) # setting geometry of button button.setGeometry(200, 150, 100, 40) # setting alpha level button.setStyleSheet("color : rgba(0, 0, 0, 100)") # adding action to a button button.clicked.connect(self.clickme) # action method def clickme(self): # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 156, "s": 28, "text": "In this article we will see how to create translucent button, here translucent refer as button which are not completely opaque." }, { "code": null, "e": 454, "s": 156, "text": "In order to do this, we have to change the alpha level of push button, alpha level is the opaque factor greater the value of alpha more the object is opaque, but unlike main window we can’t use setWindowOpacity method, therefore in order to change the alpha value we will use setStyleSheet method." }, { "code": null, "e": 524, "s": 454, "text": "Below is the difference between normal button and translucent button." }, { "code": null, "e": 586, "s": 526, "text": "Syntax : button.setStyleSheet(“color : rgba(0, 0, 0, 100)”)" }, { "code": null, "e": 708, "s": 586, "text": "Argument : It takes string as argument. Here Rgba refer to red, green, blue and alpha level, they all vary from 0 to 255." }, { "code": null, "e": 770, "s": 708, "text": "Action performed : It will set the alpha level of push button" }, { "code": null, "e": 777, "s": 770, "text": "Code :" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton(\"CLICK\", self) # setting geometry of button button.setGeometry(200, 150, 100, 40) # setting alpha level button.setStyleSheet(\"color : rgba(0, 0, 0, 100)\") # adding action to a button button.clicked.connect(self.clickme) # action method def clickme(self): # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1832, "s": 777, "text": null }, { "code": null, "e": 1841, "s": 1832, "text": "Output :" }, { "code": null, "e": 1852, "s": 1841, "text": "Python-gui" }, { "code": null, "e": 1864, "s": 1852, "text": "Python-PyQt" }, { "code": null, "e": 1871, "s": 1864, "text": "Python" } ]
Minimax Algorithm in Game Theory | Set 1 (Introduction)
13 Jun, 2022 Minimax is a kind of backtracking algorithm that is used in decision making and game theory to find the optimal move for a player, assuming that your opponent also plays optimally. It is widely used in two player turn-based games such as Tic-Tac-Toe, Backgammon, Mancala, Chess, etc.In Minimax the two players are called maximizer and minimizer. The maximizer tries to get the highest score possible while the minimizer tries to do the opposite and get the lowest score possible.Every board state has a value associated with it. In a given state if the maximizer has upper hand then, the score of the board will tend to be some positive value. If the minimizer has the upper hand in that board state then it will tend to be some negative value. The values of the board are calculated by some heuristics which are unique for every type of game. Example: Consider a game which has 4 final states and paths to reach final state are from root to 4 leaves of a perfect binary tree as shown below. Assume you are the maximizing player and you get the first chance to move, i.e., you are at the root and your opponent at next level. Which move you would make as a maximizing player considering that your opponent also plays optimally? Since this is a backtracking based algorithm, it tries all possible moves, then backtracks and makes a decision. Maximizer goes LEFT: It is now the minimizers turn. The minimizer now has a choice between 3 and 5. Being the minimizer it will definitely choose the least among both, that is 3 Maximizer goes RIGHT: It is now the minimizers turn. The minimizer now has a choice between 2 and 9. He will choose 2 as it is the least among the two values. Being the maximizer you would choose the larger value that is 3. Hence the optimal move for the maximizer is to go LEFT and the optimal value is 3. Now the game tree looks like below : The above tree shows two possible scores when maximizer makes left and right moves. Note: Even though there is a value of 9 on the right subtree, the minimizer will never pick that. We must always assume that our opponent plays optimally. Below is the implementation for the same. C++ Java C# Python3 Javascript // A simple C++ program to find// maximum score that// maximizing player can get.#include<bits/stdc++.h>using namespace std; // Returns the optimal value a maximizer can obtain.// depth is current depth in game tree.// nodeIndex is index of current node in scores[].// isMax is true if current move is// of maximizer, else false// scores[] stores leaves of Game tree.// h is maximum height of Game treeint minimax(int depth, int nodeIndex, bool isMax, int scores[], int h){ // Terminating condition. i.e // leaf node is reached if (depth == h) return scores[nodeIndex]; // If current move is maximizer, // find the maximum attainable // value if (isMax) return max(minimax(depth+1, nodeIndex*2, false, scores, h), minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); // Else (If current move is Minimizer), find the minimum // attainable value else return min(minimax(depth+1, nodeIndex*2, true, scores, h), minimax(depth+1, nodeIndex*2 + 1, true, scores, h));} // A utility function to find Log n in base 2int log2(int n){ return (n==1)? 0 : 1 + log2(n/2);} // Driver codeint main(){ // The number of elements in scores must be // a power of 2. int scores[] = {3, 5, 2, 9, 12, 5, 23, 23}; int n = sizeof(scores)/sizeof(scores[0]); int h = log2(n); int res = minimax(0, 0, true, scores, h); cout << "The optimal value is : " << res << endl; return 0;} // A simple java program to find maximum score that// maximizing player can get. import java.io.*; class GFG { // Returns the optimal value a maximizer can obtain.// depth is current depth in game tree.// nodeIndex is index of current node in scores[].// isMax is true if current move is of maximizer, else false// scores[] stores leaves of Game tree.// h is maximum height of Game tree static int minimax(int depth, int nodeIndex, boolean isMax, int scores[], int h){ // Terminating condition. i.e leaf node is reached if (depth == h) return scores[nodeIndex]; // If current move is maximizer, find the maximum attainable // value if (isMax) return Math.max(minimax(depth+1, nodeIndex*2, false, scores, h), minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); // Else (If current move is Minimizer), find the minimum // attainable value else return Math.min(minimax(depth+1, nodeIndex*2, true, scores, h), minimax(depth+1, nodeIndex*2 + 1, true, scores, h));} // A utility function to find Log n in base 2 static int log2(int n){return (n==1)? 0 : 1 + log2(n/2);} // Driver code public static void main (String[] args) { // The number of elements in scores must be // a power of 2. int scores[] = {3, 5, 2, 9, 12, 5, 23, 23}; int n = scores.length; int h = log2(n); int res = minimax(0, 0, true, scores, h); System.out.println( "The optimal value is : " +res); }} // This code is contributed by vt_m // A simple C# program to find maximum score that// maximizing player can get.using System; public class GFG{ // Returns the optimal value a maximizer can obtain.// depth is current depth in game tree.// nodeIndex is index of current node in scores[].// isMax is true if current move is of maximizer, else false// scores[] stores leaves of Game tree.// h is maximum height of Game treestatic int minimax(int depth, int nodeIndex, bool isMax, int []scores, int h){ // Terminating condition. i.e leaf node is reached if (depth == h) return scores[nodeIndex]; // If current move is maximizer, find the maximum attainable // value if (isMax) return Math.Max(minimax(depth+1, nodeIndex*2, false, scores, h), minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); // Else (If current move is Minimizer), find the minimum // attainable value else return Math.Min(minimax(depth+1, nodeIndex*2, true, scores, h), minimax(depth+1, nodeIndex*2 + 1, true, scores, h));} // A utility function to find Log n in base 2static int log2(int n){ return (n==1)? 0 : 1 + log2(n/2);} // Driver codestatic public void Main (){ // The number of elements in scores must be // a power of 2. int []scores = {3, 5, 2, 9, 12, 5, 23, 23}; int n = scores.Length; int h = log2(n); int res = minimax(0, 0, true, scores, h); Console.WriteLine( "The optimal value is : " +res); }} // This code is contributed by ajit. # A simple Python3 program to find# maximum score that# maximizing player can getimport math def minimax (curDepth, nodeIndex, maxTurn, scores, targetDepth): # base case : targetDepth reached if (curDepth == targetDepth): return scores[nodeIndex] if (maxTurn): return max(minimax(curDepth + 1, nodeIndex * 2, False, scores, targetDepth), minimax(curDepth + 1, nodeIndex * 2 + 1, False, scores, targetDepth)) else: return min(minimax(curDepth + 1, nodeIndex * 2, True, scores, targetDepth), minimax(curDepth + 1, nodeIndex * 2 + 1, True, scores, targetDepth)) # Driver codescores = [3, 5, 2, 9, 12, 5, 23, 23] treeDepth = math.log(len(scores), 2) print("The optimal value is : ", end = "")print(minimax(0, 0, True, scores, treeDepth)) # This code is contributed# by rootshadow <script> // Javascript program to find maximum score that// maximizing player can get. // Returns the optimal value a maximizer can obtain.// depth is current depth in game tree.// nodeIndex is index of current node in scores[].// isMax is true if current move is of maximizer, else false// scores[] stores leaves of Game tree.// h is maximum height of Game tree function minimax(depth, nodeIndex, isMax, scores, h){ // Terminating condition. i.e leaf node is reached if (depth == h) return scores[nodeIndex]; // If current move is maximizer, find the maximum attainable // value if (isMax) return Math.max(minimax(depth+1, nodeIndex*2, false, scores, h), minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); // Else (If current move is Minimizer), find the minimum // attainable value else return Math.min(minimax(depth+1, nodeIndex*2, true, scores, h), minimax(depth+1, nodeIndex*2 + 1, true, scores, h));} // A utility function to find Log n in base 2 function log2(n){return (n==1)? 0 : 1 + log2(n/2);} // Driver Code // The number of elements in scores must be // a power of 2. let scores = [3, 5, 2, 9, 12, 5, 23, 23]; let n = scores.length; let h = log2(n); let res = minimax(0, 0, true, scores, h); document.write( "The optimal value is : " +res); </script> Output: The optimal value is: 12 Time complexity : O(b^d) b is the branching factor and d is count of depth or ply of graph or tree. Space Complexity : O(bd) where b is branching factor into d is maximum depth of tree similar to DFS. The idea of this article is to introduce Minimax with a simple example. In the above example, there are only two choices for a player. In general, there can be more choices. In that case, we need to recur for all possible moves and find the maximum/minimum. For example, in Tic-Tac-Toe, the first player can make 9 possible moves. In the above example, the scores (leaves of Game Tree) are given to us. For a typical game, we need to derive these values We will soon be covering Tic Tac Toe with Minimax algorithm.This article is contributed by Akshay L. Aradhya. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rootshadow AlexSocheathSon jit_t souravghosh0416 abusaleh devendrasalunke Game Theory Game Theory Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 898, "s": 54, "text": "Minimax is a kind of backtracking algorithm that is used in decision making and game theory to find the optimal move for a player, assuming that your opponent also plays optimally. It is widely used in two player turn-based games such as Tic-Tac-Toe, Backgammon, Mancala, Chess, etc.In Minimax the two players are called maximizer and minimizer. The maximizer tries to get the highest score possible while the minimizer tries to do the opposite and get the lowest score possible.Every board state has a value associated with it. In a given state if the maximizer has upper hand then, the score of the board will tend to be some positive value. If the minimizer has the upper hand in that board state then it will tend to be some negative value. The values of the board are calculated by some heuristics which are unique for every type of game." }, { "code": null, "e": 1282, "s": 898, "text": "Example: Consider a game which has 4 final states and paths to reach final state are from root to 4 leaves of a perfect binary tree as shown below. Assume you are the maximizing player and you get the first chance to move, i.e., you are at the root and your opponent at next level. Which move you would make as a maximizing player considering that your opponent also plays optimally?" }, { "code": null, "e": 1396, "s": 1282, "text": "Since this is a backtracking based algorithm, it tries all possible moves, then backtracks and makes a decision. " }, { "code": null, "e": 1574, "s": 1396, "text": "Maximizer goes LEFT: It is now the minimizers turn. The minimizer now has a choice between 3 and 5. Being the minimizer it will definitely choose the least among both, that is 3" }, { "code": null, "e": 1733, "s": 1574, "text": "Maximizer goes RIGHT: It is now the minimizers turn. The minimizer now has a choice between 2 and 9. He will choose 2 as it is the least among the two values." }, { "code": null, "e": 1881, "s": 1733, "text": "Being the maximizer you would choose the larger value that is 3. Hence the optimal move for the maximizer is to go LEFT and the optimal value is 3." }, { "code": null, "e": 1918, "s": 1881, "text": "Now the game tree looks like below :" }, { "code": null, "e": 2002, "s": 1918, "text": "The above tree shows two possible scores when maximizer makes left and right moves." }, { "code": null, "e": 2157, "s": 2002, "text": "Note: Even though there is a value of 9 on the right subtree, the minimizer will never pick that. We must always assume that our opponent plays optimally." }, { "code": null, "e": 2200, "s": 2157, "text": "Below is the implementation for the same. " }, { "code": null, "e": 2204, "s": 2200, "text": "C++" }, { "code": null, "e": 2209, "s": 2204, "text": "Java" }, { "code": null, "e": 2212, "s": 2209, "text": "C#" }, { "code": null, "e": 2220, "s": 2212, "text": "Python3" }, { "code": null, "e": 2231, "s": 2220, "text": "Javascript" }, { "code": "// A simple C++ program to find// maximum score that// maximizing player can get.#include<bits/stdc++.h>using namespace std; // Returns the optimal value a maximizer can obtain.// depth is current depth in game tree.// nodeIndex is index of current node in scores[].// isMax is true if current move is// of maximizer, else false// scores[] stores leaves of Game tree.// h is maximum height of Game treeint minimax(int depth, int nodeIndex, bool isMax, int scores[], int h){ // Terminating condition. i.e // leaf node is reached if (depth == h) return scores[nodeIndex]; // If current move is maximizer, // find the maximum attainable // value if (isMax) return max(minimax(depth+1, nodeIndex*2, false, scores, h), minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); // Else (If current move is Minimizer), find the minimum // attainable value else return min(minimax(depth+1, nodeIndex*2, true, scores, h), minimax(depth+1, nodeIndex*2 + 1, true, scores, h));} // A utility function to find Log n in base 2int log2(int n){ return (n==1)? 0 : 1 + log2(n/2);} // Driver codeint main(){ // The number of elements in scores must be // a power of 2. int scores[] = {3, 5, 2, 9, 12, 5, 23, 23}; int n = sizeof(scores)/sizeof(scores[0]); int h = log2(n); int res = minimax(0, 0, true, scores, h); cout << \"The optimal value is : \" << res << endl; return 0;}", "e": 3695, "s": 2231, "text": null }, { "code": "// A simple java program to find maximum score that// maximizing player can get. import java.io.*; class GFG { // Returns the optimal value a maximizer can obtain.// depth is current depth in game tree.// nodeIndex is index of current node in scores[].// isMax is true if current move is of maximizer, else false// scores[] stores leaves of Game tree.// h is maximum height of Game tree static int minimax(int depth, int nodeIndex, boolean isMax, int scores[], int h){ // Terminating condition. i.e leaf node is reached if (depth == h) return scores[nodeIndex]; // If current move is maximizer, find the maximum attainable // value if (isMax) return Math.max(minimax(depth+1, nodeIndex*2, false, scores, h), minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); // Else (If current move is Minimizer), find the minimum // attainable value else return Math.min(minimax(depth+1, nodeIndex*2, true, scores, h), minimax(depth+1, nodeIndex*2 + 1, true, scores, h));} // A utility function to find Log n in base 2 static int log2(int n){return (n==1)? 0 : 1 + log2(n/2);} // Driver code public static void main (String[] args) { // The number of elements in scores must be // a power of 2. int scores[] = {3, 5, 2, 9, 12, 5, 23, 23}; int n = scores.length; int h = log2(n); int res = minimax(0, 0, true, scores, h); System.out.println( \"The optimal value is : \" +res); }} // This code is contributed by vt_m", "e": 5223, "s": 3695, "text": null }, { "code": "// A simple C# program to find maximum score that// maximizing player can get.using System; public class GFG{ // Returns the optimal value a maximizer can obtain.// depth is current depth in game tree.// nodeIndex is index of current node in scores[].// isMax is true if current move is of maximizer, else false// scores[] stores leaves of Game tree.// h is maximum height of Game treestatic int minimax(int depth, int nodeIndex, bool isMax, int []scores, int h){ // Terminating condition. i.e leaf node is reached if (depth == h) return scores[nodeIndex]; // If current move is maximizer, find the maximum attainable // value if (isMax) return Math.Max(minimax(depth+1, nodeIndex*2, false, scores, h), minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); // Else (If current move is Minimizer), find the minimum // attainable value else return Math.Min(minimax(depth+1, nodeIndex*2, true, scores, h), minimax(depth+1, nodeIndex*2 + 1, true, scores, h));} // A utility function to find Log n in base 2static int log2(int n){ return (n==1)? 0 : 1 + log2(n/2);} // Driver codestatic public void Main (){ // The number of elements in scores must be // a power of 2. int []scores = {3, 5, 2, 9, 12, 5, 23, 23}; int n = scores.Length; int h = log2(n); int res = minimax(0, 0, true, scores, h); Console.WriteLine( \"The optimal value is : \" +res); }} // This code is contributed by ajit.", "e": 6714, "s": 5223, "text": null }, { "code": "# A simple Python3 program to find# maximum score that# maximizing player can getimport math def minimax (curDepth, nodeIndex, maxTurn, scores, targetDepth): # base case : targetDepth reached if (curDepth == targetDepth): return scores[nodeIndex] if (maxTurn): return max(minimax(curDepth + 1, nodeIndex * 2, False, scores, targetDepth), minimax(curDepth + 1, nodeIndex * 2 + 1, False, scores, targetDepth)) else: return min(minimax(curDepth + 1, nodeIndex * 2, True, scores, targetDepth), minimax(curDepth + 1, nodeIndex * 2 + 1, True, scores, targetDepth)) # Driver codescores = [3, 5, 2, 9, 12, 5, 23, 23] treeDepth = math.log(len(scores), 2) print(\"The optimal value is : \", end = \"\")print(minimax(0, 0, True, scores, treeDepth)) # This code is contributed# by rootshadow", "e": 7676, "s": 6714, "text": null }, { "code": "<script> // Javascript program to find maximum score that// maximizing player can get. // Returns the optimal value a maximizer can obtain.// depth is current depth in game tree.// nodeIndex is index of current node in scores[].// isMax is true if current move is of maximizer, else false// scores[] stores leaves of Game tree.// h is maximum height of Game tree function minimax(depth, nodeIndex, isMax, scores, h){ // Terminating condition. i.e leaf node is reached if (depth == h) return scores[nodeIndex]; // If current move is maximizer, find the maximum attainable // value if (isMax) return Math.max(minimax(depth+1, nodeIndex*2, false, scores, h), minimax(depth+1, nodeIndex*2 + 1, false, scores, h)); // Else (If current move is Minimizer), find the minimum // attainable value else return Math.min(minimax(depth+1, nodeIndex*2, true, scores, h), minimax(depth+1, nodeIndex*2 + 1, true, scores, h));} // A utility function to find Log n in base 2 function log2(n){return (n==1)? 0 : 1 + log2(n/2);} // Driver Code // The number of elements in scores must be // a power of 2. let scores = [3, 5, 2, 9, 12, 5, 23, 23]; let n = scores.length; let h = log2(n); let res = minimax(0, 0, true, scores, h); document.write( \"The optimal value is : \" +res); </script>", "e": 9082, "s": 7676, "text": null }, { "code": null, "e": 9091, "s": 9082, "text": "Output: " }, { "code": null, "e": 9117, "s": 9091, "text": "The optimal value is: 12" }, { "code": null, "e": 9217, "s": 9117, "text": "Time complexity : O(b^d) b is the branching factor and d is count of depth or ply of graph or tree." }, { "code": null, "e": 9318, "s": 9217, "text": "Space Complexity : O(bd) where b is branching factor into d is maximum depth of tree similar to DFS." }, { "code": null, "e": 9391, "s": 9318, "text": "The idea of this article is to introduce Minimax with a simple example. " }, { "code": null, "e": 9650, "s": 9391, "text": "In the above example, there are only two choices for a player. In general, there can be more choices. In that case, we need to recur for all possible moves and find the maximum/minimum. For example, in Tic-Tac-Toe, the first player can make 9 possible moves." }, { "code": null, "e": 9773, "s": 9650, "text": "In the above example, the scores (leaves of Game Tree) are given to us. For a typical game, we need to derive these values" }, { "code": null, "e": 10229, "s": 9773, "text": "We will soon be covering Tic Tac Toe with Minimax algorithm.This article is contributed by Akshay L. Aradhya. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 10240, "s": 10229, "text": "rootshadow" }, { "code": null, "e": 10256, "s": 10240, "text": "AlexSocheathSon" }, { "code": null, "e": 10262, "s": 10256, "text": "jit_t" }, { "code": null, "e": 10278, "s": 10262, "text": "souravghosh0416" }, { "code": null, "e": 10287, "s": 10278, "text": "abusaleh" }, { "code": null, "e": 10303, "s": 10287, "text": "devendrasalunke" }, { "code": null, "e": 10315, "s": 10303, "text": "Game Theory" }, { "code": null, "e": 10327, "s": 10315, "text": "Game Theory" } ]
Chained Exceptions in C#
Chained Exceptions are a chain of try-catch statements that handle exceptions. To create a chain of exceptions i.e. chained exceptions − Set the first try-catch − static void Main(string[] args) { try { One(); } catch (Exception e) { Console.WriteLine(e); } } Now try-catch under method One() − static void One() { try { Two(); } catch (Exception e) { throw new Exception("First exception!", e); } } The method Two() also continues chained exception. static void Two() { try { Three(); } catch (Exception e) { throw new Exception("Second Exception!", e); } } Now the next method. static void Three() { try { Last(); } catch (Exception e) { throw new Exception("Third Exception!", e); } } The takes us to the last. static void Last() { throw new Exception("Last exception!"); } On running the above, the exceptions would be handled like this − System.Exception: First exception! ---< System.Exception: Middle Exception! ---< System.Exception: Last exception! at Demo.Two () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0 --- End of inner exception stack trace --- at Demo.Two () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0 at Demo.One () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0 --- End of inner exception stack trace --- at Demo.One () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0 at Demo.Main (System.String[] args) [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0
[ { "code": null, "e": 1199, "s": 1062, "text": "Chained Exceptions are a chain of try-catch statements that handle exceptions. To create a chain of exceptions i.e. chained exceptions −" }, { "code": null, "e": 1225, "s": 1199, "text": "Set the first try-catch −" }, { "code": null, "e": 1343, "s": 1225, "text": "static void Main(string[] args) {\n try {\n One();\n } catch (Exception e) {\n Console.WriteLine(e);\n }\n}" }, { "code": null, "e": 1378, "s": 1343, "text": "Now try-catch under method One() −" }, { "code": null, "e": 1504, "s": 1378, "text": "static void One() {\n try {\n Two();\n } catch (Exception e) {\n throw new Exception(\"First exception!\", e);\n }\n}" }, { "code": null, "e": 1555, "s": 1504, "text": "The method Two() also continues chained exception." }, { "code": null, "e": 1684, "s": 1555, "text": "static void Two() {\n try {\n Three();\n } catch (Exception e) {\n throw new Exception(\"Second Exception!\", e);\n }\n}" }, { "code": null, "e": 1705, "s": 1684, "text": "Now the next method." }, { "code": null, "e": 1834, "s": 1705, "text": "static void Three() {\n try {\n Last();\n } catch (Exception e) {\n throw new Exception(\"Third Exception!\", e);\n }\n}" }, { "code": null, "e": 1860, "s": 1834, "text": "The takes us to the last." }, { "code": null, "e": 1926, "s": 1860, "text": "static void Last() {\n throw new Exception(\"Last exception!\");\n}" }, { "code": null, "e": 1992, "s": 1926, "text": "On running the above, the exceptions would be handled like this −" }, { "code": null, "e": 2539, "s": 1992, "text": "System.Exception: First exception! ---< System.Exception: Middle Exception! ---< System.Exception: Last exception!\nat Demo.Two () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0\n--- End of inner exception stack trace ---\nat Demo.Two () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0\nat Demo.One () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0\n--- End of inner exception stack trace ---\nat Demo.One () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0\nat Demo.Main (System.String[] args) [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0" } ]