title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Difference between <nav> and <menu> tag in HTML5
27 Apr, 2020 “<nav>” Tag: The <nav> tag is used to specify navigation links either within the same document or any other document which means it provides link to contents which are either on same or different page/document. Example: <!DOCTYPE html><html> <body> <h1>The nav element</h1> <p>The nav element defines navigation links:</p> <nav> <a href=”/home/”>HOME</a> | <a href=”/category/”>CATEGORY</a> | <a href=”/profile/”>PROFILE</a> | </nav></body> </html> Output: Example: <!DOCTYPE html> <html> <head> <title>nav tag</title> <style> nav { border:2px; background-color:#090; color:white; padding:8px; } a { color:white; font-size:25px; } .gfg { font-size:30px; color:#090; font-weight:bold; text-align:center; } .nav_tag { text-align:center; } </style> </head> <body> <div class = "gfg">GFG</div> <div class = "nav_tag">Nav Element Example</div> <nav> <a href = "https://www.geeksforgeeks.org/"> Home</a> | <a href = "https://www.geeksforgeeks.org/category/difference-between/"> Difference Between</a> | <a href = "https://www.geeksforgeeks.org/company-interview-corner/"> Interview</a> | <a href = "https://practice.geeksforgeeks.org/courses/"> Courses</a> | </nav> </body> </html> Output: <menu> Tag: The <menu> tag in HTML is used for creating menu lists. It defines a list of commands which can be used by the users to create listing form control, toolbar, context menus, and commands. The <menu> tag was removed from HTML and reintroduced in HTML5. It is not supported on the majority of platforms. Contents of “menu” tags: <menuitem> <li> <script> <hr> Example: <!DOCTYPE html><html> <head> <title>HTML menu Tag</title></head> <body> <p>menu tag</p> <menu> <ol> <li>menu list</li> <li>unordered list</li> <li>ordered list</li> </ol> </menu></body> </html> Output: Example: <!DOCTYPE html><html> <head> <title>html menu tag</title></head> <body> <div style="background:#090;border:2px solid #cccccc;padding: 10px;" contextmenu="testmenu"> <p> Right-click inside this box to view the context menu! </p> <menu type="context" id="testmenu"> <menuitem label="Refresh" onclick="window.location.reload();" icon="ico_reload.png"> </menuitem> <menuitem label="Email" onclick= "window.location='mailto:?body='+window.location.href;"> </menuitem> </menu> </div> <p> This example currently works in Mozilla Firefox web browser please use Mozilla Firefox to view this example. </p></body> </html> Output: HTML-Misc HTML-Tags Picked HTML Web Technologies Web technologies Questions Write From Home HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Apr, 2020" }, { "code": null, "e": 239, "s": 28, "text": "“<nav>” Tag: The <nav> tag is used to specify navigation links either within the same document or any other document which means it provides link to contents which are either on same or different page/document." }, { "code": null, "e": 248, "s": 239, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <body> <h1>The nav element</h1> <p>The nav element defines navigation links:</p> <nav> <a href=”/home/”>HOME</a> | <a href=”/category/”>CATEGORY</a> | <a href=”/profile/”>PROFILE</a> | </nav></body> </html>", "e": 512, "s": 248, "text": null }, { "code": null, "e": 520, "s": 512, "text": "Output:" }, { "code": null, "e": 529, "s": 520, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title>nav tag</title> <style> nav { border:2px; background-color:#090; color:white; padding:8px; } a { color:white; font-size:25px; } .gfg { font-size:30px; color:#090; font-weight:bold; text-align:center; } .nav_tag { text-align:center; } </style> </head> <body> <div class = \"gfg\">GFG</div> <div class = \"nav_tag\">Nav Element Example</div> <nav> <a href = \"https://www.geeksforgeeks.org/\"> Home</a> | <a href = \"https://www.geeksforgeeks.org/category/difference-between/\"> Difference Between</a> | <a href = \"https://www.geeksforgeeks.org/company-interview-corner/\"> Interview</a> | <a href = \"https://practice.geeksforgeeks.org/courses/\"> Courses</a> | </nav> </body> </html> ", "e": 1604, "s": 529, "text": null }, { "code": null, "e": 1612, "s": 1604, "text": "Output:" }, { "code": null, "e": 1925, "s": 1612, "text": "<menu> Tag: The <menu> tag in HTML is used for creating menu lists. It defines a list of commands which can be used by the users to create listing form control, toolbar, context menus, and commands. The <menu> tag was removed from HTML and reintroduced in HTML5. It is not supported on the majority of platforms." }, { "code": null, "e": 1950, "s": 1925, "text": "Contents of “menu” tags:" }, { "code": null, "e": 1961, "s": 1950, "text": "<menuitem>" }, { "code": null, "e": 1966, "s": 1961, "text": "<li>" }, { "code": null, "e": 1975, "s": 1966, "text": "<script>" }, { "code": null, "e": 1980, "s": 1975, "text": "<hr>" }, { "code": null, "e": 1989, "s": 1980, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML menu Tag</title></head> <body> <p>menu tag</p> <menu> <ol> <li>menu list</li> <li>unordered list</li> <li>ordered list</li> </ol> </menu></body> </html>", "e": 2245, "s": 1989, "text": null }, { "code": null, "e": 2253, "s": 2245, "text": "Output:" }, { "code": null, "e": 2262, "s": 2253, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>html menu tag</title></head> <body> <div style=\"background:#090;border:2px solid #cccccc;padding: 10px;\" contextmenu=\"testmenu\"> <p> Right-click inside this box to view the context menu! </p> <menu type=\"context\" id=\"testmenu\"> <menuitem label=\"Refresh\" onclick=\"window.location.reload();\" icon=\"ico_reload.png\"> </menuitem> <menuitem label=\"Email\" onclick= \"window.location='mailto:?body='+window.location.href;\"> </menuitem> </menu> </div> <p> This example currently works in Mozilla Firefox web browser please use Mozilla Firefox to view this example. </p></body> </html>", "e": 3083, "s": 2262, "text": null }, { "code": null, "e": 3091, "s": 3083, "text": "Output:" }, { "code": null, "e": 3101, "s": 3091, "text": "HTML-Misc" }, { "code": null, "e": 3111, "s": 3101, "text": "HTML-Tags" }, { "code": null, "e": 3118, "s": 3111, "text": "Picked" }, { "code": null, "e": 3123, "s": 3118, "text": "HTML" }, { "code": null, "e": 3140, "s": 3123, "text": "Web Technologies" }, { "code": null, "e": 3167, "s": 3140, "text": "Web technologies Questions" }, { "code": null, "e": 3183, "s": 3167, "text": "Write From Home" }, { "code": null, "e": 3188, "s": 3183, "text": "HTML" } ]
Java Program to Display all the Directories in a Directory
28 Jan, 2022 The directory is the organizing structure of the computer file system which is not only responsible for storing files but also to locate them on the memory. File organization structure is a hierarchical structure involving parent and child relationships just like what is there in tree data structures. It will vary from operating systems, rather the efficiency of the operating system is measured with the ease of file organization structure for the end-users. The following classes in Java are present there to list directory content java.nio.file.Files org.apache.commons.io.FileUtils java.io.File The hierarchical structure of Directory Prerequisite: File And Directory Commands Terminal Command used to compile any java code on the machineTerminal Command used to Run any java code on the machine Terminal Command used to compile any java code on the machine Terminal Command used to Run any java code on the machine java class_name.java // For Compilation java class_name // For Execution Approach: There are two standard approaches in accessing the directory in Java. Discussion over approaches is given below: Approach 1: Using the listFiles() method Approach 2: Using Brute-force attack Approach 1: listFiles() method to store all files in an array to print all the files present in the current folder. Here is the implementation for the same. Java // Java Program to Display all directories in a directory // Importing Classes/Filesimport java.io.*;// Importing specific File Class for directory accessimport java.io.File; class GFG { // Main Driver code public static void main(String[] args) { // Creating object of class File where // Dot represents the current directory File currentDir = new File("."); displayDirectory(currentDir); } // Function displaying all the directories // present in the directory public static void displayDirectory(File dir) { try { File[] files = dir.listFiles(); // For-each loop for iteration for (File file : files) { // Checking of file inside directory if (file.isDirectory()) { // Display directories inside directory System.out.println( "directory:" + file.getCanonicalPath()); displayDirectory(file); } // Simply get the path else { System.out.println( " file:" + file.getCanonicalPath()); } } } // if any exceptions occurs printStackTrace catch (IOException e) { e.printStackTrace(); } }} Output: Terminal displaying all the directories in a directory Approach 2: Now, here simply the Brute-force attack is taken into consideration that is to access the given directory and simply printing the directories/file present in the specified folder. Here is the implementation for the same. Java // Java Program to Display all directories in a directory // Importing Classes/Filesimport java.io.*; public class GFG { // Driver main method public static void main(String[] args) { /*For windows user write path in below format-: ("F:\\folder name \\ subfolder") */ // Creating new instance of File File file = new File("/Desktop"); // returns an array of all files String[] fileList = file.list(); for (String str : fileList) { System.out.println(str); } }} Output: This code accesses over network volume. Note: In the above example we have written the path for Linux user. For Windows users, you have to use double-backslash while specifying the path. It is because the \ character is used as an escape character in Java. Hence, the first backslash is used as an escape character for the second one. kashishsoda rkbhola5 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2022" }, { "code": null, "e": 490, "s": 28, "text": "The directory is the organizing structure of the computer file system which is not only responsible for storing files but also to locate them on the memory. File organization structure is a hierarchical structure involving parent and child relationships just like what is there in tree data structures. It will vary from operating systems, rather the efficiency of the operating system is measured with the ease of file organization structure for the end-users." }, { "code": null, "e": 564, "s": 490, "text": "The following classes in Java are present there to list directory content" }, { "code": null, "e": 584, "s": 564, "text": "java.nio.file.Files" }, { "code": null, "e": 616, "s": 584, "text": "org.apache.commons.io.FileUtils" }, { "code": null, "e": 629, "s": 616, "text": "java.io.File" }, { "code": null, "e": 669, "s": 629, "text": "The hierarchical structure of Directory" }, { "code": null, "e": 711, "s": 669, "text": "Prerequisite: File And Directory Commands" }, { "code": null, "e": 830, "s": 711, "text": "Terminal Command used to compile any java code on the machineTerminal Command used to Run any java code on the machine" }, { "code": null, "e": 892, "s": 830, "text": "Terminal Command used to compile any java code on the machine" }, { "code": null, "e": 950, "s": 892, "text": "Terminal Command used to Run any java code on the machine" }, { "code": null, "e": 1034, "s": 950, "text": "java class_name.java // For Compilation\njava class_name // For Execution " }, { "code": null, "e": 1160, "s": 1034, "text": "Approach: There are two standard approaches in accessing the directory in Java. Discussion over approaches is given below: " }, { "code": null, "e": 1201, "s": 1160, "text": "Approach 1: Using the listFiles() method" }, { "code": null, "e": 1238, "s": 1201, "text": "Approach 2: Using Brute-force attack" }, { "code": null, "e": 1354, "s": 1238, "text": "Approach 1: listFiles() method to store all files in an array to print all the files present in the current folder." }, { "code": null, "e": 1395, "s": 1354, "text": "Here is the implementation for the same." }, { "code": null, "e": 1400, "s": 1395, "text": "Java" }, { "code": "// Java Program to Display all directories in a directory // Importing Classes/Filesimport java.io.*;// Importing specific File Class for directory accessimport java.io.File; class GFG { // Main Driver code public static void main(String[] args) { // Creating object of class File where // Dot represents the current directory File currentDir = new File(\".\"); displayDirectory(currentDir); } // Function displaying all the directories // present in the directory public static void displayDirectory(File dir) { try { File[] files = dir.listFiles(); // For-each loop for iteration for (File file : files) { // Checking of file inside directory if (file.isDirectory()) { // Display directories inside directory System.out.println( \"directory:\" + file.getCanonicalPath()); displayDirectory(file); } // Simply get the path else { System.out.println( \" file:\" + file.getCanonicalPath()); } } } // if any exceptions occurs printStackTrace catch (IOException e) { e.printStackTrace(); } }}", "e": 2796, "s": 1400, "text": null }, { "code": null, "e": 2859, "s": 2796, "text": "Output: Terminal displaying all the directories in a directory" }, { "code": null, "e": 3092, "s": 2859, "text": "Approach 2: Now, here simply the Brute-force attack is taken into consideration that is to access the given directory and simply printing the directories/file present in the specified folder. Here is the implementation for the same." }, { "code": null, "e": 3097, "s": 3092, "text": "Java" }, { "code": "// Java Program to Display all directories in a directory // Importing Classes/Filesimport java.io.*; public class GFG { // Driver main method public static void main(String[] args) { /*For windows user write path in below format-: (\"F:\\\\folder name \\\\ subfolder\") */ // Creating new instance of File File file = new File(\"/Desktop\"); // returns an array of all files String[] fileList = file.list(); for (String str : fileList) { System.out.println(str); } }}", "e": 3657, "s": 3097, "text": null }, { "code": null, "e": 3665, "s": 3657, "text": "Output:" }, { "code": null, "e": 3705, "s": 3665, "text": "This code accesses over network volume." }, { "code": null, "e": 4000, "s": 3705, "text": "Note: In the above example we have written the path for Linux user. For Windows users, you have to use double-backslash while specifying the path. It is because the \\ character is used as an escape character in Java. Hence, the first backslash is used as an escape character for the second one." }, { "code": null, "e": 4012, "s": 4000, "text": "kashishsoda" }, { "code": null, "e": 4021, "s": 4012, "text": "rkbhola5" }, { "code": null, "e": 4026, "s": 4021, "text": "Java" }, { "code": null, "e": 4040, "s": 4026, "text": "Java Programs" }, { "code": null, "e": 4045, "s": 4040, "text": "Java" } ]
Python – Read CSV Column into List without header
25 Feb, 2021 Prerequisites: Reading and Writing data in CSV CSV files are parsed in python with the help of csv library. The csv library contains objects that are used to read, write and process data from and to CSV files. Sometimes, while working with large amounts of data, we want to omit a few rows or columns, so that minimum memory gets utilized. Let’s see how we can read a CSV file by skipping the headers. Import the csv module.Create a reader object (iterator) by passing file object in csv.reader() function.Call the next() function on this iterator object, which returns the first row of CSV.Store the headers in a separate variable.Iterate over remaining rows of the csv file and store them in another list.print this list to verify. Import the csv module. Create a reader object (iterator) by passing file object in csv.reader() function. Call the next() function on this iterator object, which returns the first row of CSV. Store the headers in a separate variable. Iterate over remaining rows of the csv file and store them in another list. print this list to verify. Example: The below code reads the Data.csv file. Below is the full implementation: Python3 import csv # reading data from a csv file 'Data.csv'with open('Data.csv', newline='') as file: reader = csv.reader(file, delimiter = ' ') # store the headers in a separate variable, # move the reader object to point on the next row headings = next(reader) # output list to store all rows Output = [] for row in reader: Output.append(row[:]) for row_num, rows in enumerate(Output): print('data in row number {} is {}'.format(row_num+1, rows)) print('headers were: ', headings) Output: Picked python-csv Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Feb, 2021" }, { "code": null, "e": 76, "s": 28, "text": "Prerequisites: Reading and Writing data in CSV " }, { "code": null, "e": 432, "s": 76, "text": "CSV files are parsed in python with the help of csv library. The csv library contains objects that are used to read, write and process data from and to CSV files. Sometimes, while working with large amounts of data, we want to omit a few rows or columns, so that minimum memory gets utilized. Let’s see how we can read a CSV file by skipping the headers." }, { "code": null, "e": 764, "s": 432, "text": "Import the csv module.Create a reader object (iterator) by passing file object in csv.reader() function.Call the next() function on this iterator object, which returns the first row of CSV.Store the headers in a separate variable.Iterate over remaining rows of the csv file and store them in another list.print this list to verify." }, { "code": null, "e": 787, "s": 764, "text": "Import the csv module." }, { "code": null, "e": 870, "s": 787, "text": "Create a reader object (iterator) by passing file object in csv.reader() function." }, { "code": null, "e": 956, "s": 870, "text": "Call the next() function on this iterator object, which returns the first row of CSV." }, { "code": null, "e": 998, "s": 956, "text": "Store the headers in a separate variable." }, { "code": null, "e": 1074, "s": 998, "text": "Iterate over remaining rows of the csv file and store them in another list." }, { "code": null, "e": 1101, "s": 1074, "text": "print this list to verify." }, { "code": null, "e": 1110, "s": 1101, "text": "Example:" }, { "code": null, "e": 1150, "s": 1110, "text": "The below code reads the Data.csv file." }, { "code": null, "e": 1184, "s": 1150, "text": "Below is the full implementation:" }, { "code": null, "e": 1192, "s": 1184, "text": "Python3" }, { "code": "import csv # reading data from a csv file 'Data.csv'with open('Data.csv', newline='') as file: reader = csv.reader(file, delimiter = ' ') # store the headers in a separate variable, # move the reader object to point on the next row headings = next(reader) # output list to store all rows Output = [] for row in reader: Output.append(row[:]) for row_num, rows in enumerate(Output): print('data in row number {} is {}'.format(row_num+1, rows)) print('headers were: ', headings)", "e": 1718, "s": 1192, "text": null }, { "code": null, "e": 1726, "s": 1718, "text": "Output:" }, { "code": null, "e": 1733, "s": 1726, "text": "Picked" }, { "code": null, "e": 1744, "s": 1733, "text": "python-csv" }, { "code": null, "e": 1768, "s": 1744, "text": "Technical Scripter 2020" }, { "code": null, "e": 1775, "s": 1768, "text": "Python" }, { "code": null, "e": 1794, "s": 1775, "text": "Technical Scripter" } ]
Get the full URL in PHP
30 Nov, 2021 In this article, we will see how to get the complete URL of currently running pages using PHP, along with understanding their implementation through the examples. $_SERVER is a super global variable in PHP that contains the details related to the header, paths, and script locations. The status of HTTPS will be saved in the Global variable $_SERVER[‘HTTPS’]. So, using the $_SERVER[‘HTTPS’] in isset() function, that is used to check whether it exists or not. This will also tell us whether HTTPS is enabled or not. Check the value of $_SERVER[‘HTTPS’], if it is “on”, then HTTPS is enabled and we have to append “https” to the URL. Approach: There are a few steps to get the complete URL of the currently running page which are given below: Create a PHP variable that will store the URL in string format. Check whether the HTTPS is enabled by the server. If it is, append “https” to the URL string. If HTTPS is not enabled, append “http” to the URL string. Append the regular symbol, i.e. “://” to the URL. Append the HTTP_HOST(The host to which we have requested, e.g. www.google.com, www.yourdomain.com, etc...) name of the server. Append the REQUEST_URI(The resource which we have requested, e.g. /index.php, etc...) to the URL string. Note: Use isset() function to check whether HTTPS is enabled or not. The isset() function is used to check a variable exists or not.Example 1: This example illustrates getting the url of the current page. PHP <?php // Program to display URL of current page. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') $link = "https"; else $link = "http"; // Here append the common URL characters. $link .= "://"; // Append the host(domain name, ip) to the URL. $link .= $_SERVER['HTTP_HOST']; // Append the requested resource location to the URL $link .= $_SERVER['REQUEST_URI']; // Print the link echo $link;?> Output: https://ide.geeksforgeeks.org/ Example 2: Getting the url of the webpage using $_SERVER[‘HTTP_HOST’] that will return the host header from the current request. PHP <?php // Program to display current page URL. $link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $link;?> Output: https://ide.geeksforgeeks.org/ The output of the above code is https://ide.geeksforgeeks.org/ instead of https://ide.geeksforgeeks.org/index.php. In order to fix this problem, need to replace, $_SERVER[‘REQUEST_URI’] with $_SERVER[‘PHP_SELF’]. Program 3: This example is displaying the currently executing PHP file URL. PHP <?php // Program to display complete URL if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') $link = "https"; else $link = "http"; // Here append the common URL // characters. $link .= "://"; // Append the host(domain name, // ip) to the URL. $link .= $_SERVER['HTTP_HOST']; // Append the requested resource // location to the URL $link .= $_SERVER['PHP_SELF']; // Display the link echo $link;?> Output: https://ide.geeksforgeeks.org/index.php Program 4: This example describes getting the complete url of the webpage. PHP <?php // Program to display complete URL $link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; // Display the complete URL echo $link;?> Output: https://ide.geeksforgeeks.org/index.php PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. bhaskargeeksforgeeks PHP-Questions Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime 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": 52, "s": 24, "text": "\n30 Nov, 2021" }, { "code": null, "e": 686, "s": 52, "text": "In this article, we will see how to get the complete URL of currently running pages using PHP, along with understanding their implementation through the examples. $_SERVER is a super global variable in PHP that contains the details related to the header, paths, and script locations. The status of HTTPS will be saved in the Global variable $_SERVER[‘HTTPS’]. So, using the $_SERVER[‘HTTPS’] in isset() function, that is used to check whether it exists or not. This will also tell us whether HTTPS is enabled or not. Check the value of $_SERVER[‘HTTPS’], if it is “on”, then HTTPS is enabled and we have to append “https” to the URL." }, { "code": null, "e": 795, "s": 686, "text": "Approach: There are a few steps to get the complete URL of the currently running page which are given below:" }, { "code": null, "e": 859, "s": 795, "text": "Create a PHP variable that will store the URL in string format." }, { "code": null, "e": 1011, "s": 859, "text": "Check whether the HTTPS is enabled by the server. If it is, append “https” to the URL string. If HTTPS is not enabled, append “http” to the URL string." }, { "code": null, "e": 1061, "s": 1011, "text": "Append the regular symbol, i.e. “://” to the URL." }, { "code": null, "e": 1188, "s": 1061, "text": "Append the HTTP_HOST(The host to which we have requested, e.g. www.google.com, www.yourdomain.com, etc...) name of the server." }, { "code": null, "e": 1293, "s": 1188, "text": "Append the REQUEST_URI(The resource which we have requested, e.g. /index.php, etc...) to the URL string." }, { "code": null, "e": 1498, "s": 1293, "text": "Note: Use isset() function to check whether HTTPS is enabled or not. The isset() function is used to check a variable exists or not.Example 1: This example illustrates getting the url of the current page." }, { "code": null, "e": 1502, "s": 1498, "text": "PHP" }, { "code": "<?php // Program to display URL of current page. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') $link = \"https\"; else $link = \"http\"; // Here append the common URL characters. $link .= \"://\"; // Append the host(domain name, ip) to the URL. $link .= $_SERVER['HTTP_HOST']; // Append the requested resource location to the URL $link .= $_SERVER['REQUEST_URI']; // Print the link echo $link;?>", "e": 1970, "s": 1502, "text": null }, { "code": null, "e": 1978, "s": 1970, "text": "Output:" }, { "code": null, "e": 2009, "s": 1978, "text": "https://ide.geeksforgeeks.org/" }, { "code": null, "e": 2138, "s": 2009, "text": "Example 2: Getting the url of the webpage using $_SERVER[‘HTTP_HOST’] that will return the host header from the current request." }, { "code": null, "e": 2142, "s": 2138, "text": "PHP" }, { "code": "<?php // Program to display current page URL. $link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? \"https\" : \"http\") . \"://\" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $link;?>", "e": 2402, "s": 2142, "text": null }, { "code": null, "e": 2410, "s": 2402, "text": "Output:" }, { "code": null, "e": 2441, "s": 2410, "text": "https://ide.geeksforgeeks.org/" }, { "code": null, "e": 2654, "s": 2441, "text": "The output of the above code is https://ide.geeksforgeeks.org/ instead of https://ide.geeksforgeeks.org/index.php. In order to fix this problem, need to replace, $_SERVER[‘REQUEST_URI’] with $_SERVER[‘PHP_SELF’]." }, { "code": null, "e": 2730, "s": 2654, "text": "Program 3: This example is displaying the currently executing PHP file URL." }, { "code": null, "e": 2734, "s": 2730, "text": "PHP" }, { "code": "<?php // Program to display complete URL if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') $link = \"https\"; else $link = \"http\"; // Here append the common URL // characters. $link .= \"://\"; // Append the host(domain name, // ip) to the URL. $link .= $_SERVER['HTTP_HOST']; // Append the requested resource // location to the URL $link .= $_SERVER['PHP_SELF']; // Display the link echo $link;?>", "e": 3168, "s": 2734, "text": null }, { "code": null, "e": 3176, "s": 3168, "text": "Output:" }, { "code": null, "e": 3216, "s": 3176, "text": "https://ide.geeksforgeeks.org/index.php" }, { "code": null, "e": 3291, "s": 3216, "text": "Program 4: This example describes getting the complete url of the webpage." }, { "code": null, "e": 3295, "s": 3291, "text": "PHP" }, { "code": "<?php // Program to display complete URL $link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? \"https\" : \"http\") . \"://\" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; // Display the complete URL echo $link;?>", "e": 3555, "s": 3295, "text": null }, { "code": null, "e": 3563, "s": 3555, "text": "Output:" }, { "code": null, "e": 3603, "s": 3563, "text": "https://ide.geeksforgeeks.org/index.php" }, { "code": null, "e": 3772, "s": 3603, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 3793, "s": 3772, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 3807, "s": 3793, "text": "PHP-Questions" }, { "code": null, "e": 3814, "s": 3807, "text": "Picked" }, { "code": null, "e": 3818, "s": 3814, "text": "PHP" }, { "code": null, "e": 3835, "s": 3818, "text": "Web Technologies" }, { "code": null, "e": 3839, "s": 3835, "text": "PHP" }, { "code": null, "e": 3937, "s": 3839, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3987, "s": 3937, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 4027, "s": 3987, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 4088, "s": 4027, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 4138, "s": 4088, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 4183, "s": 4138, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 4245, "s": 4183, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4278, "s": 4245, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4339, "s": 4278, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4389, "s": 4339, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Simple Calculator using TCP in Java
28 Jun, 2021 Prerequisite: Socket Programming in JavaNetworking just doesn’t conclude with a one-way communication between the client and server. For example consider a time telling server which listens to request of the clients and respond with the current time to the client. Real-time applications usually follow a request-response model for communication. The client usually sends the request object to the server which after processing the request, sends the response back to the client. In simple terms, the client requests for a particular resource available on the server and server responds it resource if it can verify the request. For example, when enter is pressed after entering the desired url, a request is sent to corresponding server which then replies by sending the response in form of a webpage which the browsers are capable of displaying.In this article, a simple calculator application is implemented wherein the client will send requests to server in form of simple arithmetic equations and server will respond back with the answer to the equation. Client-Side Programming The steps involved on client side are as follows- Open the socket connectionCommunication: In the communication part, there is a slight change. The difference with the previous article lies in the usage of both the input and output streams to send equations and receive the results to and from the server respectively. DataInputStream and DataOutputStream are used instead of basic InputStream and OutputStream to make it machine independent. Following constructors are used –public DataInputStream(InputStream in)Syntax: public DataInputStream(InputStream in) Parameters: in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.public DataOutputStream(InputStream in)Syntax: public DataOutputStream(OutputStream out) Parameters: out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.After creating the input and output streams, we use the readUTF and writeUTF of the created streams methods to receive and send the message respectively.public final String readUTF()throws IOExceptionReads the string encoded using UTF8 encoding. Throws: IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs public final String writeUTF()throws IOExceptionWrites the string encoded using UTF8 encoding. Throws: IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs Closing the connection. Open the socket connection Communication: In the communication part, there is a slight change. The difference with the previous article lies in the usage of both the input and output streams to send equations and receive the results to and from the server respectively. DataInputStream and DataOutputStream are used instead of basic InputStream and OutputStream to make it machine independent. Following constructors are used –public DataInputStream(InputStream in)Syntax: public DataInputStream(InputStream in) Parameters: in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream.public DataOutputStream(InputStream in)Syntax: public DataOutputStream(OutputStream out) Parameters: out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream.After creating the input and output streams, we use the readUTF and writeUTF of the created streams methods to receive and send the message respectively.public final String readUTF()throws IOExceptionReads the string encoded using UTF8 encoding. Throws: IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs public final String writeUTF()throws IOExceptionWrites the string encoded using UTF8 encoding. Throws: IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs public DataInputStream(InputStream in)Syntax: public DataInputStream(InputStream in) Parameters: in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream. Syntax: public DataInputStream(InputStream in) Parameters: in - The underlying InputStream. Creates a DataInputStream that uses the specified underlying InputStream. public DataOutputStream(InputStream in)Syntax: public DataOutputStream(OutputStream out) Parameters: out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream. Syntax: public DataOutputStream(OutputStream out) Parameters: out - The underlying OutputStream. Creates a DataOutputStream that uses the specified underlying OutputStream. After creating the input and output streams, we use the readUTF and writeUTF of the created streams methods to receive and send the message respectively. public final String readUTF()throws IOExceptionReads the string encoded using UTF8 encoding. Throws: IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs Reads the string encoded using UTF8 encoding. Throws: IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs public final String writeUTF()throws IOExceptionWrites the string encoded using UTF8 encoding. Throws: IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs Writes the string encoded using UTF8 encoding. Throws: IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs Closing the connection. Client Side Implementation // Java program to illustrate Client Side Programming// for Simple Calculator using TCPimport java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.InetAddress;import java.net.Socket;import java.net.UnknownHostException;import java.util.Scanner; public class Calc_Client{ public static void main(String[] args) throws IOException { InetAddress ip = InetAddress.getLocalHost(); int port = 4444; Scanner sc = new Scanner(System.in); // Step 1: Open the socket connection. Socket s = new Socket(ip, port); // Step 2: Communication-get the input and output stream DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); while (true) { // Enter the equation in the form- // "operand1 operation operand2" System.out.print("Enter the equation in the form: "); System.out.println("'operand operator operand'"); String inp = sc.nextLine(); if (inp.equals("bye")) break; // send the equation to server dos.writeUTF(inp); // wait till request is processed and sent back to client String ans = dis.readUTF(); System.out.println("Answer=" + ans); } }} Output Enter the equation in the form: 'operand operator operand' 5 * 6 Answer=30 Enter the equation in the form: 'operand operator operand' 5 + 6 Answer=11 Enter the equation in the form: 'operand operator operand' 9 / 3 Answer=3 Server-Side Programming Steps involved on the server side are as follows- Establish a socket connection.Process the equations coming from client: In server side also we open both the inputStream and outputStream. After receiving the equation, we process it and returns the result back to client by writing on the outputStream of the socket.Close the connection. Establish a socket connection. Process the equations coming from client: In server side also we open both the inputStream and outputStream. After receiving the equation, we process it and returns the result back to client by writing on the outputStream of the socket. Close the connection. Server Side Implementation // Java program to illustrate Server Side Programming// for Simple Calculator using TCPimport java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import java.util.StringTokenizer; public class Calc_Server{ public static void main(String args[]) throws IOException { // Step 1: Establish the socket connection. ServerSocket ss = new ServerSocket(4444); Socket s = ss.accept(); // Step 2: Processing the request. DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); while (true) { // wait for input String input = dis.readUTF(); if(input.equals("bye")) break; System.out.println("Equation received:-" + input); int result; // Use StringTokenizer to break the equation into operand and // operation StringTokenizer st = new StringTokenizer(input); int oprnd1 = Integer.parseInt(st.nextToken()); String operation = st.nextToken(); int oprnd2 = Integer.parseInt(st.nextToken()); // perform the required operation. if (operation.equals("+")) { result = oprnd1 + oprnd2; } else if (operation.equals("-")) { result = oprnd1 - oprnd2; } else if (operation.equals("*")) { result = oprnd1 * oprnd2; } else { result = oprnd1 / oprnd2; } System.out.println("Sending the result..."); // send the result back to the client. dos.writeUTF(Integer.toString(result)); } }} Output: Equation received:-5 * 6 Sending the result... Equation received:-5 + 6 Sending the result... Equation received:-9 / 3 Sending the result... Note: In order to test the above programs on the system, please make sure that you run the server program first and then the client one. Make sure you are in the client console and from there enter the equation in the format-“operand1 operator operand2” and press Enter. Answer to the requested equation will be shown in the client console only. Finally to terminate the communication, type “bye” (without quotes) and hit enter. Related Article:Simple Calculator using UDP in Java This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai Java-Networking Java 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 Multidimensional Arrays in Java Singleton Class in Java Set in Java Initializing a List in Java Stack Class in Java Introduction to Java
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": null, "e": 401, "s": 54, "text": "Prerequisite: Socket Programming in JavaNetworking just doesn’t conclude with a one-way communication between the client and server. For example consider a time telling server which listens to request of the clients and respond with the current time to the client. Real-time applications usually follow a request-response model for communication." }, { "code": null, "e": 1114, "s": 401, "text": "The client usually sends the request object to the server which after processing the request, sends the response back to the client. In simple terms, the client requests for a particular resource available on the server and server responds it resource if it can verify the request. For example, when enter is pressed after entering the desired url, a request is sent to corresponding server which then replies by sending the response in form of a webpage which the browsers are capable of displaying.In this article, a simple calculator application is implemented wherein the client will send requests to server in form of simple arithmetic equations and server will respond back with the answer to the equation." }, { "code": null, "e": 1138, "s": 1114, "text": "Client-Side Programming" }, { "code": null, "e": 1188, "s": 1138, "text": "The steps involved on client side are as follows-" }, { "code": null, "e": 2689, "s": 1188, "text": "Open the socket connectionCommunication: In the communication part, there is a slight change. The difference with the previous article lies in the usage of both the input and output streams to send equations and receive the results to and from the server respectively. DataInputStream and DataOutputStream are used instead of basic InputStream and OutputStream to make it machine independent. Following constructors are used –public DataInputStream(InputStream in)Syntax: public DataInputStream(InputStream in)\nParameters:\nin - The underlying InputStream.\nCreates a DataInputStream that uses the specified underlying InputStream.public DataOutputStream(InputStream in)Syntax: public DataOutputStream(OutputStream out)\nParameters:\nout - The underlying OutputStream.\nCreates a DataOutputStream that uses the specified underlying OutputStream.After creating the input and output streams, we use the readUTF and writeUTF of the created streams methods to receive and send the message respectively.public final String readUTF()throws IOExceptionReads the string encoded using UTF8 encoding.\nThrows:\nIOException - the stream has been closed and the contained input stream \ndoes not support reading after close,\nor another I/O error occurs\npublic final String writeUTF()throws IOExceptionWrites the string encoded using UTF8 encoding.\nThrows:\nIOException - the stream has been closed and the contained input stream \ndoes not support reading after close,\nor another I/O error occurs\nClosing the connection." }, { "code": null, "e": 2716, "s": 2689, "text": "Open the socket connection" }, { "code": null, "e": 4168, "s": 2716, "text": "Communication: In the communication part, there is a slight change. The difference with the previous article lies in the usage of both the input and output streams to send equations and receive the results to and from the server respectively. DataInputStream and DataOutputStream are used instead of basic InputStream and OutputStream to make it machine independent. Following constructors are used –public DataInputStream(InputStream in)Syntax: public DataInputStream(InputStream in)\nParameters:\nin - The underlying InputStream.\nCreates a DataInputStream that uses the specified underlying InputStream.public DataOutputStream(InputStream in)Syntax: public DataOutputStream(OutputStream out)\nParameters:\nout - The underlying OutputStream.\nCreates a DataOutputStream that uses the specified underlying OutputStream.After creating the input and output streams, we use the readUTF and writeUTF of the created streams methods to receive and send the message respectively.public final String readUTF()throws IOExceptionReads the string encoded using UTF8 encoding.\nThrows:\nIOException - the stream has been closed and the contained input stream \ndoes not support reading after close,\nor another I/O error occurs\npublic final String writeUTF()throws IOExceptionWrites the string encoded using UTF8 encoding.\nThrows:\nIOException - the stream has been closed and the contained input stream \ndoes not support reading after close,\nor another I/O error occurs\n" }, { "code": null, "e": 4372, "s": 4168, "text": "public DataInputStream(InputStream in)Syntax: public DataInputStream(InputStream in)\nParameters:\nin - The underlying InputStream.\nCreates a DataInputStream that uses the specified underlying InputStream." }, { "code": null, "e": 4538, "s": 4372, "text": "Syntax: public DataInputStream(InputStream in)\nParameters:\nin - The underlying InputStream.\nCreates a DataInputStream that uses the specified underlying InputStream." }, { "code": null, "e": 4750, "s": 4538, "text": "public DataOutputStream(InputStream in)Syntax: public DataOutputStream(OutputStream out)\nParameters:\nout - The underlying OutputStream.\nCreates a DataOutputStream that uses the specified underlying OutputStream." }, { "code": null, "e": 4923, "s": 4750, "text": "Syntax: public DataOutputStream(OutputStream out)\nParameters:\nout - The underlying OutputStream.\nCreates a DataOutputStream that uses the specified underlying OutputStream." }, { "code": null, "e": 5077, "s": 4923, "text": "After creating the input and output streams, we use the readUTF and writeUTF of the created streams methods to receive and send the message respectively." }, { "code": null, "e": 5319, "s": 5077, "text": "public final String readUTF()throws IOExceptionReads the string encoded using UTF8 encoding.\nThrows:\nIOException - the stream has been closed and the contained input stream \ndoes not support reading after close,\nor another I/O error occurs\n" }, { "code": null, "e": 5514, "s": 5319, "text": "Reads the string encoded using UTF8 encoding.\nThrows:\nIOException - the stream has been closed and the contained input stream \ndoes not support reading after close,\nor another I/O error occurs\n" }, { "code": null, "e": 5758, "s": 5514, "text": "public final String writeUTF()throws IOExceptionWrites the string encoded using UTF8 encoding.\nThrows:\nIOException - the stream has been closed and the contained input stream \ndoes not support reading after close,\nor another I/O error occurs\n" }, { "code": null, "e": 5954, "s": 5758, "text": "Writes the string encoded using UTF8 encoding.\nThrows:\nIOException - the stream has been closed and the contained input stream \ndoes not support reading after close,\nor another I/O error occurs\n" }, { "code": null, "e": 5978, "s": 5954, "text": "Closing the connection." }, { "code": null, "e": 6005, "s": 5978, "text": "Client Side Implementation" }, { "code": "// Java program to illustrate Client Side Programming// for Simple Calculator using TCPimport java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.InetAddress;import java.net.Socket;import java.net.UnknownHostException;import java.util.Scanner; public class Calc_Client{ public static void main(String[] args) throws IOException { InetAddress ip = InetAddress.getLocalHost(); int port = 4444; Scanner sc = new Scanner(System.in); // Step 1: Open the socket connection. Socket s = new Socket(ip, port); // Step 2: Communication-get the input and output stream DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); while (true) { // Enter the equation in the form- // \"operand1 operation operand2\" System.out.print(\"Enter the equation in the form: \"); System.out.println(\"'operand operator operand'\"); String inp = sc.nextLine(); if (inp.equals(\"bye\")) break; // send the equation to server dos.writeUTF(inp); // wait till request is processed and sent back to client String ans = dis.readUTF(); System.out.println(\"Answer=\" + ans); } }}", "e": 7399, "s": 6005, "text": null }, { "code": null, "e": 7406, "s": 7399, "text": "Output" }, { "code": null, "e": 7631, "s": 7406, "text": "Enter the equation in the form: 'operand operator operand'\n5 * 6\nAnswer=30\nEnter the equation in the form: 'operand operator operand'\n5 + 6\nAnswer=11\nEnter the equation in the form: 'operand operator operand'\n9 / 3\nAnswer=3\n" }, { "code": null, "e": 7655, "s": 7631, "text": "Server-Side Programming" }, { "code": null, "e": 7705, "s": 7655, "text": "Steps involved on the server side are as follows-" }, { "code": null, "e": 7993, "s": 7705, "text": "Establish a socket connection.Process the equations coming from client: In server side also we open both the inputStream and outputStream. After receiving the equation, we process it and returns the result back to client by writing on the outputStream of the socket.Close the connection." }, { "code": null, "e": 8024, "s": 7993, "text": "Establish a socket connection." }, { "code": null, "e": 8261, "s": 8024, "text": "Process the equations coming from client: In server side also we open both the inputStream and outputStream. After receiving the equation, we process it and returns the result back to client by writing on the outputStream of the socket." }, { "code": null, "e": 8283, "s": 8261, "text": "Close the connection." }, { "code": null, "e": 8310, "s": 8283, "text": "Server Side Implementation" }, { "code": "// Java program to illustrate Server Side Programming// for Simple Calculator using TCPimport java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import java.util.StringTokenizer; public class Calc_Server{ public static void main(String args[]) throws IOException { // Step 1: Establish the socket connection. ServerSocket ss = new ServerSocket(4444); Socket s = ss.accept(); // Step 2: Processing the request. DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); while (true) { // wait for input String input = dis.readUTF(); if(input.equals(\"bye\")) break; System.out.println(\"Equation received:-\" + input); int result; // Use StringTokenizer to break the equation into operand and // operation StringTokenizer st = new StringTokenizer(input); int oprnd1 = Integer.parseInt(st.nextToken()); String operation = st.nextToken(); int oprnd2 = Integer.parseInt(st.nextToken()); // perform the required operation. if (operation.equals(\"+\")) { result = oprnd1 + oprnd2; } else if (operation.equals(\"-\")) { result = oprnd1 - oprnd2; } else if (operation.equals(\"*\")) { result = oprnd1 * oprnd2; } else { result = oprnd1 / oprnd2; } System.out.println(\"Sending the result...\"); // send the result back to the client. dos.writeUTF(Integer.toString(result)); } }}", "e": 10188, "s": 8310, "text": null }, { "code": null, "e": 10196, "s": 10188, "text": "Output:" }, { "code": null, "e": 10338, "s": 10196, "text": "Equation received:-5 * 6\nSending the result...\nEquation received:-5 + 6\nSending the result...\nEquation received:-9 / 3\nSending the result...\n" }, { "code": null, "e": 10767, "s": 10338, "text": "Note: In order to test the above programs on the system, please make sure that you run the server program first and then the client one. Make sure you are in the client console and from there enter the equation in the format-“operand1 operator operand2” and press Enter. Answer to the requested equation will be shown in the client console only. Finally to terminate the communication, type “bye” (without quotes) and hit enter." }, { "code": null, "e": 10819, "s": 10767, "text": "Related Article:Simple Calculator using UDP in Java" }, { "code": null, "e": 11118, "s": 10819, "text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 11243, "s": 11118, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 11256, "s": 11243, "text": "Akanksha_Rai" }, { "code": null, "e": 11272, "s": 11256, "text": "Java-Networking" }, { "code": null, "e": 11277, "s": 11272, "text": "Java" }, { "code": null, "e": 11282, "s": 11277, "text": "Java" }, { "code": null, "e": 11380, "s": 11282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11399, "s": 11380, "text": "Interfaces in Java" }, { "code": null, "e": 11417, "s": 11399, "text": "ArrayList in Java" }, { "code": null, "e": 11437, "s": 11417, "text": "Collections in Java" }, { "code": null, "e": 11452, "s": 11437, "text": "Stream In Java" }, { "code": null, "e": 11484, "s": 11452, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 11508, "s": 11484, "text": "Singleton Class in Java" }, { "code": null, "e": 11520, "s": 11508, "text": "Set in Java" }, { "code": null, "e": 11548, "s": 11520, "text": "Initializing a List in Java" }, { "code": null, "e": 11568, "s": 11548, "text": "Stack Class in Java" } ]
Python | Pandas Series.skew()
05 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.skew() function return unbiased skew over requested axis Normalized by N-1. Skewness is asymmetry in a statistical distribution, in which the curve appears distorted or skewed either to the left or to the right. Syntax: Series.skew(axis=None, skipna=None, level=None, numeric_only=None, **kwargs) Parameter :axis : Axis for the function to be applied on.skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.numeric_only : Include only float, int, boolean columns.**kwargs : Additional keyword arguments to be passed to the function. Returns : skew : scalar or Series (if level specified) Example #1 : Use Series.skew() function to find the skewness in the data of the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65]) # Print the seriesprint(sr) Output : Now we will use Series.skew() function to find the skewness in the data. # find skewnesssr.skew() Output : As we can see in the output, Series.skew() function has successfully calculated the skewness in the data of the given Series object. Example #2 : Use Series.skew() function to find the skewness in the data of the given Series object. We have some missing values in our series object, so skip those missing values. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None]) # Print the seriesprint(sr) Output : Now we will use Series.skew() function to find the skewness in the data. # find skewnesssr.skew(skipna = True) Output : As we can see in the output, Series.skew() function has successfully calculated the skewness in the data of the given Series object. Missing values has been skipped while calculating the skewness in the given data. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 511, "s": 285, "text": "Pandas Series.skew() function return unbiased skew over requested axis Normalized by N-1. Skewness is asymmetry in a statistical distribution, in which the curve appears distorted or skewed either to the left or to the right." }, { "code": null, "e": 596, "s": 511, "text": "Syntax: Series.skew(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)" }, { "code": null, "e": 946, "s": 596, "text": "Parameter :axis : Axis for the function to be applied on.skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.numeric_only : Include only float, int, boolean columns.**kwargs : Additional keyword arguments to be passed to the function." }, { "code": null, "e": 1001, "s": 946, "text": "Returns : skew : scalar or Series (if level specified)" }, { "code": null, "e": 1102, "s": 1001, "text": "Example #1 : Use Series.skew() function to find the skewness in the data of the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65]) # Print the seriesprint(sr)", "e": 1240, "s": 1102, "text": null }, { "code": null, "e": 1249, "s": 1240, "text": "Output :" }, { "code": null, "e": 1322, "s": 1249, "text": "Now we will use Series.skew() function to find the skewness in the data." }, { "code": "# find skewnesssr.skew()", "e": 1347, "s": 1322, "text": null }, { "code": null, "e": 1356, "s": 1347, "text": "Output :" }, { "code": null, "e": 1489, "s": 1356, "text": "As we can see in the output, Series.skew() function has successfully calculated the skewness in the data of the given Series object." }, { "code": null, "e": 1670, "s": 1489, "text": "Example #2 : Use Series.skew() function to find the skewness in the data of the given Series object. We have some missing values in our series object, so skip those missing values." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None]) # Print the seriesprint(sr)", "e": 1842, "s": 1670, "text": null }, { "code": null, "e": 1851, "s": 1842, "text": "Output :" }, { "code": null, "e": 1924, "s": 1851, "text": "Now we will use Series.skew() function to find the skewness in the data." }, { "code": "# find skewnesssr.skew(skipna = True)", "e": 1962, "s": 1924, "text": null }, { "code": null, "e": 1971, "s": 1962, "text": "Output :" }, { "code": null, "e": 2186, "s": 1971, "text": "As we can see in the output, Series.skew() function has successfully calculated the skewness in the data of the given Series object. Missing values has been skipped while calculating the skewness in the given data." }, { "code": null, "e": 2207, "s": 2186, "text": "Python pandas-series" }, { "code": null, "e": 2236, "s": 2207, "text": "Python pandas-series-methods" }, { "code": null, "e": 2250, "s": 2236, "text": "Python-pandas" }, { "code": null, "e": 2257, "s": 2250, "text": "Python" }, { "code": null, "e": 2355, "s": 2257, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2387, "s": 2355, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2414, "s": 2387, "text": "Python Classes and Objects" }, { "code": null, "e": 2435, "s": 2414, "text": "Python OOPs Concepts" }, { "code": null, "e": 2458, "s": 2435, "text": "Introduction To PYTHON" }, { "code": null, "e": 2489, "s": 2458, "text": "Python | os.path.join() method" }, { "code": null, "e": 2545, "s": 2489, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2587, "s": 2545, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2629, "s": 2587, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2668, "s": 2629, "text": "Python | Get unique values from a list" } ]
JavaFX | Rectangle2D Class
05 Nov, 2019 Rectangle2D class is a part of JavaFX. Rectangle2D class creates a rectangle with the given coordinates of the upper left corner of the rectangle and the width and height or it is defined by a location (minX, minY) and dimension (width x height). Constructors of the class: Rectangle2D(double minX, double minY, double width, double height): Creates a new Rectangle2D with specified width height and the coordinates of upper left corner of the Rectangle Commonly Used Methods: Below programs illustrate the use of Rectangle2D class: Java Program to create an object of Rectangle2D and display its details and whether it contains a point and check whether it intersects a rectangle or not: This program creates a Rectangle2D object named rectangle with minX, minY, height and width as parameters. The details of the Rectangle2D object is displayed using the display function. The display function displays the upper left coordinate of the rectangle and the bottom right corner of the rectangle and its width and height using the getMinX(), getMinY(), getMaxX(), getMaxY(), getHeight(), and getWidth() function. We will see whether the rectangle contains a point using the contains() function and also check whether it intersects the other rectangle using the intersects function and display the results.// Java Program to create an object of // Rectangle2D and display its details// and whether it contains a point and // whether it intersects a rectangle or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle = new Rectangle2D(100, 100, 100, 100); // display the rectangle display(rectangle); // Check whether the rectangle contains a point System.out.println("The rectangle contains point 150, 150 = " + rectangle.contains(new Point2D(150, 150))); System.out.println("The rectangle contains point 50, 50 = " + rectangle.contains(new Point2D(50, 50))); // Check Whether the rectangle // intersects another rectangle System.out.print("The rectangle intersects another rectangle " +"with width = 100, height = 100, minX = 50, & minY = 50: " + rectangle.intersects(50, 50, 100, 100)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display function public static void display(Rectangle2D rectangle) { // display the details of a rectangle System.out.println("Upper left point of the rectangle is = " + rectangle.getMinX() + ", " + rectangle.getMinY()); System.out.println("Lower right point of the rectangle is = " + rectangle.getMaxX() + ", " + rectangle.getMaxY()); System.out.println("Width and Height of the rectangle is = " + rectangle.getWidth() + ", " + rectangle.getHeight()); }}Output:Upper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0The rectangle contains point 150, 150 = trueThe rectangle contains point 50, 50 = falseThe rectangle intersects another rectangle with width = 100, height = 100, minX = 50, & minY = 50: trueJava Program to create two objects of Rectangle2D and display its details and check whether it intersects each other or not: This program creates two Rectangle2D objects named rectangle_1, and rectangle_2 with minX, minY, height, and width as parameters. The details of the Rectangle2D object is displayed using the display function. The display function displays the upper left coordinate of the rectangle and the bottom right corner of the rectangle and its width and height using the getMinX(), getMinY(), getMaxX(), getMaxY(), getHeight(), and getWidth() function. We will check whether it intersects the other rectangle or not using the intersects function and display the results.// Java Program to create two objects of// Rectangle2D and display its details and// check whether it intersects each other or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle_1 = new Rectangle2D(100, 100, 100, 100); Rectangle2D rectangle_2 = new Rectangle2D(100, 100, 100, 100); // display the rectangle details System.out.println("Rectangle_1 details"); display(rectangle_1); System.out.println(""); System.out.println("Rectangle_2 details"); display(rectangle_2); // display whether these two // rectangle intersects or not System.out.println("These two rectangles intersect = " + rectangle_1.intersects(rectangle_2)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display method public static void display(Rectangle2D r) { // display the details of a rectangle System.out.println("Upper left point of the rectangle is = " + r.getMinX() + ", " + r.getMinY()); System.out.println("Lower right point of the rectangle is = " + r.getMaxX() + ", " + r.getMaxY()); System.out.println("Width and Height of the rectangle is = " + r.getWidth() + ", " + r.getHeight()); }}Output:Rectangle_1 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0Rectangle_2 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0These two rectangles intersect = true Java Program to create an object of Rectangle2D and display its details and whether it contains a point and check whether it intersects a rectangle or not: This program creates a Rectangle2D object named rectangle with minX, minY, height and width as parameters. The details of the Rectangle2D object is displayed using the display function. The display function displays the upper left coordinate of the rectangle and the bottom right corner of the rectangle and its width and height using the getMinX(), getMinY(), getMaxX(), getMaxY(), getHeight(), and getWidth() function. We will see whether the rectangle contains a point using the contains() function and also check whether it intersects the other rectangle using the intersects function and display the results.// Java Program to create an object of // Rectangle2D and display its details// and whether it contains a point and // whether it intersects a rectangle or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle = new Rectangle2D(100, 100, 100, 100); // display the rectangle display(rectangle); // Check whether the rectangle contains a point System.out.println("The rectangle contains point 150, 150 = " + rectangle.contains(new Point2D(150, 150))); System.out.println("The rectangle contains point 50, 50 = " + rectangle.contains(new Point2D(50, 50))); // Check Whether the rectangle // intersects another rectangle System.out.print("The rectangle intersects another rectangle " +"with width = 100, height = 100, minX = 50, & minY = 50: " + rectangle.intersects(50, 50, 100, 100)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display function public static void display(Rectangle2D rectangle) { // display the details of a rectangle System.out.println("Upper left point of the rectangle is = " + rectangle.getMinX() + ", " + rectangle.getMinY()); System.out.println("Lower right point of the rectangle is = " + rectangle.getMaxX() + ", " + rectangle.getMaxY()); System.out.println("Width and Height of the rectangle is = " + rectangle.getWidth() + ", " + rectangle.getHeight()); }}Output:Upper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0The rectangle contains point 150, 150 = trueThe rectangle contains point 50, 50 = falseThe rectangle intersects another rectangle with width = 100, height = 100, minX = 50, & minY = 50: true // Java Program to create an object of // Rectangle2D and display its details// and whether it contains a point and // whether it intersects a rectangle or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle = new Rectangle2D(100, 100, 100, 100); // display the rectangle display(rectangle); // Check whether the rectangle contains a point System.out.println("The rectangle contains point 150, 150 = " + rectangle.contains(new Point2D(150, 150))); System.out.println("The rectangle contains point 50, 50 = " + rectangle.contains(new Point2D(50, 50))); // Check Whether the rectangle // intersects another rectangle System.out.print("The rectangle intersects another rectangle " +"with width = 100, height = 100, minX = 50, & minY = 50: " + rectangle.intersects(50, 50, 100, 100)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display function public static void display(Rectangle2D rectangle) { // display the details of a rectangle System.out.println("Upper left point of the rectangle is = " + rectangle.getMinX() + ", " + rectangle.getMinY()); System.out.println("Lower right point of the rectangle is = " + rectangle.getMaxX() + ", " + rectangle.getMaxY()); System.out.println("Width and Height of the rectangle is = " + rectangle.getWidth() + ", " + rectangle.getHeight()); }} Output: Upper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0The rectangle contains point 150, 150 = trueThe rectangle contains point 50, 50 = falseThe rectangle intersects another rectangle with width = 100, height = 100, minX = 50, & minY = 50: true Java Program to create two objects of Rectangle2D and display its details and check whether it intersects each other or not: This program creates two Rectangle2D objects named rectangle_1, and rectangle_2 with minX, minY, height, and width as parameters. The details of the Rectangle2D object is displayed using the display function. The display function displays the upper left coordinate of the rectangle and the bottom right corner of the rectangle and its width and height using the getMinX(), getMinY(), getMaxX(), getMaxY(), getHeight(), and getWidth() function. We will check whether it intersects the other rectangle or not using the intersects function and display the results.// Java Program to create two objects of// Rectangle2D and display its details and// check whether it intersects each other or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle_1 = new Rectangle2D(100, 100, 100, 100); Rectangle2D rectangle_2 = new Rectangle2D(100, 100, 100, 100); // display the rectangle details System.out.println("Rectangle_1 details"); display(rectangle_1); System.out.println(""); System.out.println("Rectangle_2 details"); display(rectangle_2); // display whether these two // rectangle intersects or not System.out.println("These two rectangles intersect = " + rectangle_1.intersects(rectangle_2)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display method public static void display(Rectangle2D r) { // display the details of a rectangle System.out.println("Upper left point of the rectangle is = " + r.getMinX() + ", " + r.getMinY()); System.out.println("Lower right point of the rectangle is = " + r.getMaxX() + ", " + r.getMaxY()); System.out.println("Width and Height of the rectangle is = " + r.getWidth() + ", " + r.getHeight()); }}Output:Rectangle_1 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0Rectangle_2 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0These two rectangles intersect = true // Java Program to create two objects of// Rectangle2D and display its details and// check whether it intersects each other or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle_1 = new Rectangle2D(100, 100, 100, 100); Rectangle2D rectangle_2 = new Rectangle2D(100, 100, 100, 100); // display the rectangle details System.out.println("Rectangle_1 details"); display(rectangle_1); System.out.println(""); System.out.println("Rectangle_2 details"); display(rectangle_2); // display whether these two // rectangle intersects or not System.out.println("These two rectangles intersect = " + rectangle_1.intersects(rectangle_2)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display method public static void display(Rectangle2D r) { // display the details of a rectangle System.out.println("Upper left point of the rectangle is = " + r.getMinX() + ", " + r.getMinY()); System.out.println("Lower right point of the rectangle is = " + r.getMaxX() + ", " + r.getMaxY()); System.out.println("Width and Height of the rectangle is = " + r.getWidth() + ", " + r.getHeight()); }} Output: Rectangle_1 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0 Rectangle_2 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0These two rectangles intersect = true Note: The above programs might not run in an online IDE. Please use an offline compiler. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/geometry/Rectangle2D.html ManasChhabra2 JavaFX 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": "\n05 Nov, 2019" }, { "code": null, "e": 275, "s": 28, "text": "Rectangle2D class is a part of JavaFX. Rectangle2D class creates a rectangle with the given coordinates of the upper left corner of the rectangle and the width and height or it is defined by a location (minX, minY) and dimension (width x height)." }, { "code": null, "e": 302, "s": 275, "text": "Constructors of the class:" }, { "code": null, "e": 482, "s": 302, "text": "Rectangle2D(double minX, double minY, double width, double height): Creates a new Rectangle2D with specified width height and the coordinates of upper left corner of the Rectangle" }, { "code": null, "e": 505, "s": 482, "text": "Commonly Used Methods:" }, { "code": null, "e": 561, "s": 505, "text": "Below programs illustrate the use of Rectangle2D class:" }, { "code": null, "e": 6588, "s": 561, "text": "Java Program to create an object of Rectangle2D and display its details and whether it contains a point and check whether it intersects a rectangle or not: This program creates a Rectangle2D object named rectangle with minX, minY, height and width as parameters. The details of the Rectangle2D object is displayed using the display function. The display function displays the upper left coordinate of the rectangle and the bottom right corner of the rectangle and its width and height using the getMinX(), getMinY(), getMaxX(), getMaxY(), getHeight(), and getWidth() function. We will see whether the rectangle contains a point using the contains() function and also check whether it intersects the other rectangle using the intersects function and display the results.// Java Program to create an object of // Rectangle2D and display its details// and whether it contains a point and // whether it intersects a rectangle or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle = new Rectangle2D(100, 100, 100, 100); // display the rectangle display(rectangle); // Check whether the rectangle contains a point System.out.println(\"The rectangle contains point 150, 150 = \" + rectangle.contains(new Point2D(150, 150))); System.out.println(\"The rectangle contains point 50, 50 = \" + rectangle.contains(new Point2D(50, 50))); // Check Whether the rectangle // intersects another rectangle System.out.print(\"The rectangle intersects another rectangle \" +\"with width = 100, height = 100, minX = 50, & minY = 50: \" + rectangle.intersects(50, 50, 100, 100)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display function public static void display(Rectangle2D rectangle) { // display the details of a rectangle System.out.println(\"Upper left point of the rectangle is = \" + rectangle.getMinX() + \", \" + rectangle.getMinY()); System.out.println(\"Lower right point of the rectangle is = \" + rectangle.getMaxX() + \", \" + rectangle.getMaxY()); System.out.println(\"Width and Height of the rectangle is = \" + rectangle.getWidth() + \", \" + rectangle.getHeight()); }}Output:Upper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0The rectangle contains point 150, 150 = trueThe rectangle contains point 50, 50 = falseThe rectangle intersects another rectangle with width = 100, height = 100, minX = 50, & minY = 50: trueJava Program to create two objects of Rectangle2D and display its details and check whether it intersects each other or not: This program creates two Rectangle2D objects named rectangle_1, and rectangle_2 with minX, minY, height, and width as parameters. The details of the Rectangle2D object is displayed using the display function. The display function displays the upper left coordinate of the rectangle and the bottom right corner of the rectangle and its width and height using the getMinX(), getMinY(), getMaxX(), getMaxY(), getHeight(), and getWidth() function. We will check whether it intersects the other rectangle or not using the intersects function and display the results.// Java Program to create two objects of// Rectangle2D and display its details and// check whether it intersects each other or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle_1 = new Rectangle2D(100, 100, 100, 100); Rectangle2D rectangle_2 = new Rectangle2D(100, 100, 100, 100); // display the rectangle details System.out.println(\"Rectangle_1 details\"); display(rectangle_1); System.out.println(\"\"); System.out.println(\"Rectangle_2 details\"); display(rectangle_2); // display whether these two // rectangle intersects or not System.out.println(\"These two rectangles intersect = \" + rectangle_1.intersects(rectangle_2)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display method public static void display(Rectangle2D r) { // display the details of a rectangle System.out.println(\"Upper left point of the rectangle is = \" + r.getMinX() + \", \" + r.getMinY()); System.out.println(\"Lower right point of the rectangle is = \" + r.getMaxX() + \", \" + r.getMaxY()); System.out.println(\"Width and Height of the rectangle is = \" + r.getWidth() + \", \" + r.getHeight()); }}Output:Rectangle_1 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0Rectangle_2 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0These two rectangles intersect = true" }, { "code": null, "e": 9656, "s": 6588, "text": "Java Program to create an object of Rectangle2D and display its details and whether it contains a point and check whether it intersects a rectangle or not: This program creates a Rectangle2D object named rectangle with minX, minY, height and width as parameters. The details of the Rectangle2D object is displayed using the display function. The display function displays the upper left coordinate of the rectangle and the bottom right corner of the rectangle and its width and height using the getMinX(), getMinY(), getMaxX(), getMaxY(), getHeight(), and getWidth() function. We will see whether the rectangle contains a point using the contains() function and also check whether it intersects the other rectangle using the intersects function and display the results.// Java Program to create an object of // Rectangle2D and display its details// and whether it contains a point and // whether it intersects a rectangle or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle = new Rectangle2D(100, 100, 100, 100); // display the rectangle display(rectangle); // Check whether the rectangle contains a point System.out.println(\"The rectangle contains point 150, 150 = \" + rectangle.contains(new Point2D(150, 150))); System.out.println(\"The rectangle contains point 50, 50 = \" + rectangle.contains(new Point2D(50, 50))); // Check Whether the rectangle // intersects another rectangle System.out.print(\"The rectangle intersects another rectangle \" +\"with width = 100, height = 100, minX = 50, & minY = 50: \" + rectangle.intersects(50, 50, 100, 100)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display function public static void display(Rectangle2D rectangle) { // display the details of a rectangle System.out.println(\"Upper left point of the rectangle is = \" + rectangle.getMinX() + \", \" + rectangle.getMinY()); System.out.println(\"Lower right point of the rectangle is = \" + rectangle.getMaxX() + \", \" + rectangle.getMaxY()); System.out.println(\"Width and Height of the rectangle is = \" + rectangle.getWidth() + \", \" + rectangle.getHeight()); }}Output:Upper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0The rectangle contains point 150, 150 = trueThe rectangle contains point 50, 50 = falseThe rectangle intersects another rectangle with width = 100, height = 100, minX = 50, & minY = 50: true" }, { "code": "// Java Program to create an object of // Rectangle2D and display its details// and whether it contains a point and // whether it intersects a rectangle or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle = new Rectangle2D(100, 100, 100, 100); // display the rectangle display(rectangle); // Check whether the rectangle contains a point System.out.println(\"The rectangle contains point 150, 150 = \" + rectangle.contains(new Point2D(150, 150))); System.out.println(\"The rectangle contains point 50, 50 = \" + rectangle.contains(new Point2D(50, 50))); // Check Whether the rectangle // intersects another rectangle System.out.print(\"The rectangle intersects another rectangle \" +\"with width = 100, height = 100, minX = 50, & minY = 50: \" + rectangle.intersects(50, 50, 100, 100)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display function public static void display(Rectangle2D rectangle) { // display the details of a rectangle System.out.println(\"Upper left point of the rectangle is = \" + rectangle.getMinX() + \", \" + rectangle.getMinY()); System.out.println(\"Lower right point of the rectangle is = \" + rectangle.getMaxX() + \", \" + rectangle.getMaxY()); System.out.println(\"Width and Height of the rectangle is = \" + rectangle.getWidth() + \", \" + rectangle.getHeight()); }}", "e": 11604, "s": 9656, "text": null }, { "code": null, "e": 11612, "s": 11604, "text": "Output:" }, { "code": null, "e": 11957, "s": 11612, "text": "Upper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0The rectangle contains point 150, 150 = trueThe rectangle contains point 50, 50 = falseThe rectangle intersects another rectangle with width = 100, height = 100, minX = 50, & minY = 50: true" }, { "code": null, "e": 14917, "s": 11957, "text": "Java Program to create two objects of Rectangle2D and display its details and check whether it intersects each other or not: This program creates two Rectangle2D objects named rectangle_1, and rectangle_2 with minX, minY, height, and width as parameters. The details of the Rectangle2D object is displayed using the display function. The display function displays the upper left coordinate of the rectangle and the bottom right corner of the rectangle and its width and height using the getMinX(), getMinY(), getMaxX(), getMaxY(), getHeight(), and getWidth() function. We will check whether it intersects the other rectangle or not using the intersects function and display the results.// Java Program to create two objects of// Rectangle2D and display its details and// check whether it intersects each other or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle_1 = new Rectangle2D(100, 100, 100, 100); Rectangle2D rectangle_2 = new Rectangle2D(100, 100, 100, 100); // display the rectangle details System.out.println(\"Rectangle_1 details\"); display(rectangle_1); System.out.println(\"\"); System.out.println(\"Rectangle_2 details\"); display(rectangle_2); // display whether these two // rectangle intersects or not System.out.println(\"These two rectangles intersect = \" + rectangle_1.intersects(rectangle_2)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display method public static void display(Rectangle2D r) { // display the details of a rectangle System.out.println(\"Upper left point of the rectangle is = \" + r.getMinX() + \", \" + r.getMinY()); System.out.println(\"Lower right point of the rectangle is = \" + r.getMaxX() + \", \" + r.getMaxY()); System.out.println(\"Width and Height of the rectangle is = \" + r.getWidth() + \", \" + r.getHeight()); }}Output:Rectangle_1 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0Rectangle_2 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0These two rectangles intersect = true" }, { "code": "// Java Program to create two objects of// Rectangle2D and display its details and// check whether it intersects each other or notimport javafx.geometry.*;import java.util.*; class Rectangle_1 { // Main Method public static void main(String args[]) { try { // rectangle object Rectangle2D rectangle_1 = new Rectangle2D(100, 100, 100, 100); Rectangle2D rectangle_2 = new Rectangle2D(100, 100, 100, 100); // display the rectangle details System.out.println(\"Rectangle_1 details\"); display(rectangle_1); System.out.println(\"\"); System.out.println(\"Rectangle_2 details\"); display(rectangle_2); // display whether these two // rectangle intersects or not System.out.println(\"These two rectangles intersect = \" + rectangle_1.intersects(rectangle_2)); } catch (Exception e) { System.err.println(e.getMessage()); } } // display method public static void display(Rectangle2D r) { // display the details of a rectangle System.out.println(\"Upper left point of the rectangle is = \" + r.getMinX() + \", \" + r.getMinY()); System.out.println(\"Lower right point of the rectangle is = \" + r.getMaxX() + \", \" + r.getMaxY()); System.out.println(\"Width and Height of the rectangle is = \" + r.getWidth() + \", \" + r.getHeight()); }}", "e": 16801, "s": 14917, "text": null }, { "code": null, "e": 16809, "s": 16801, "text": "Output:" }, { "code": null, "e": 16983, "s": 16809, "text": "Rectangle_1 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0" }, { "code": null, "e": 17194, "s": 16983, "text": "Rectangle_2 detailsUpper left point of the rectangle is = 100.0, 100.0Lower right point of the rectangle is = 200.0, 200.0Width and Height of the rectangle is = 100.0, 100.0These two rectangles intersect = true" }, { "code": null, "e": 17283, "s": 17194, "text": "Note: The above programs might not run in an online IDE. Please use an offline compiler." }, { "code": null, "e": 17371, "s": 17283, "text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/geometry/Rectangle2D.html" }, { "code": null, "e": 17385, "s": 17371, "text": "ManasChhabra2" }, { "code": null, "e": 17392, "s": 17385, "text": "JavaFX" }, { "code": null, "e": 17397, "s": 17392, "text": "Java" }, { "code": null, "e": 17402, "s": 17397, "text": "Java" }, { "code": null, "e": 17500, "s": 17402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17515, "s": 17500, "text": "Stream In Java" }, { "code": null, "e": 17536, "s": 17515, "text": "Introduction to Java" }, { "code": null, "e": 17557, "s": 17536, "text": "Constructors in Java" }, { "code": null, "e": 17576, "s": 17557, "text": "Exceptions in Java" }, { "code": null, "e": 17593, "s": 17576, "text": "Generics in Java" }, { "code": null, "e": 17623, "s": 17593, "text": "Functional Interfaces in Java" }, { "code": null, "e": 17649, "s": 17623, "text": "Java Programming Examples" }, { "code": null, "e": 17665, "s": 17649, "text": "Strings in Java" }, { "code": null, "e": 17702, "s": 17665, "text": "Differences between JDK, JRE and JVM" } ]
Program to find the next prime number
27 Jul, 2021 Given an integer N. The task is to find the next prime number i.e. the smallest prime number greater than N. Examples: Input: N = 10 Output: 11 11 is the smallest prime number greater than 10. Input: N = 0 Output: 2 Approach: First of all, take a boolean variable found and initialize it to false.Now, until that variable not equals to true, increment N by 1 in each iteration and check whether it is prime or not.If it is prime then print it and change value of found variable to True. otherwise, iterate the loop until you will get the next prime number. First of all, take a boolean variable found and initialize it to false. Now, until that variable not equals to true, increment N by 1 in each iteration and check whether it is prime or not. If it is prime then print it and change value of found variable to True. otherwise, iterate the loop until you will get the next prime number. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if n// is prime else returns falsebool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true;} // Function to return the smallest// prime number greater than Nint nextPrime(int N){ // Base case if (N <= 1) return 2; int prime = N; bool found = false; // Loop continuously until isPrime returns // true for a number greater than n while (!found) { prime++; if (isPrime(prime)) found = true; } return prime;} // Driver codeint main(){ int N = 3; cout << nextPrime(N); return 0;} // Java implementation of the approachclass GFG{ // Function that returns true if n // is prime else returns false static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Function to return the smallest // prime number greater than N static int nextPrime(int N) { // Base case if (N <= 1) return 2; int prime = N; boolean found = false; // Loop continuously until isPrime returns // true for a number greater than n while (!found) { prime++; if (isPrime(prime)) found = true; } return prime; } // Driver code public static void main (String[] args) { int N = 3; System.out.println(nextPrime(N)); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approachimport math # Function that returns True if n# is prime else returns Falsedef isPrime(n): # Corner cases if(n <= 1): return False if(n <= 3): return True # This is checked so that we can skip # middle five numbers in below loop if(n % 2 == 0 or n % 3 == 0): return False for i in range(5,int(math.sqrt(n) + 1), 6): if(n % i == 0 or n % (i + 2) == 0): return False return True # Function to return the smallest# prime number greater than Ndef nextPrime(N): # Base case if (N <= 1): return 2 prime = N found = False # Loop continuously until isPrime returns # True for a number greater than n while(not found): prime = prime + 1 if(isPrime(prime) == True): found = True return prime # Driver codeN = 3print(nextPrime(N)) # This code is contributed by Sanjit_Prasad // C# implementation of the approachusing System; class GFG{ // Function that returns true if n // is prime else returns false static bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Function to return the smallest // prime number greater than N static int nextPrime(int N) { // Base case if (N <= 1) return 2; int prime = N; bool found = false; // Loop continuously until isPrime // returns true for a number // greater than n while (!found) { prime++; if (isPrime(prime)) found = true; } return prime; } // Driver code public static void Main (String[] args) { int N = 3; Console.WriteLine(nextPrime(N)); }} // This code is contributed by 29AjayKumar <script> // Javascript implementation of the approach // Function that returns true if n// is prime else returns falsefunction isPrime(n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (let i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true;} // Function to return the smallest// prime number greater than N function nextPrime(N){ // Base case if (N <= 1) return 2; let prime = N; let found = false; // Loop continuously until isPrime returns // true for a number greater than n while (!found) { prime++; if (isPrime(prime)) found = true; } return prime;} // Driver code let N = 3; document.write(nextPrime(N)); // This code is contributed by Mayank Tyagi </script> 5 gp6 Sanjit_Prasad ankthon 29AjayKumar mayanktyagi1709 sooda367 Prime Number Mathematical Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Find minimum number of coins that make a given value Minimum number of jumps to reach end Algorithm to solve Rubik's Cube The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion Modulo Operator (%) in C/C++ with Examples Modulo 10^9+7 (1000000007) Program for factorial of a number
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jul, 2021" }, { "code": null, "e": 161, "s": 52, "text": "Given an integer N. The task is to find the next prime number i.e. the smallest prime number greater than N." }, { "code": null, "e": 172, "s": 161, "text": "Examples: " }, { "code": null, "e": 246, "s": 172, "text": "Input: N = 10 Output: 11 11 is the smallest prime number greater than 10." }, { "code": null, "e": 270, "s": 246, "text": "Input: N = 0 Output: 2 " }, { "code": null, "e": 282, "s": 270, "text": "Approach: " }, { "code": null, "e": 613, "s": 282, "text": "First of all, take a boolean variable found and initialize it to false.Now, until that variable not equals to true, increment N by 1 in each iteration and check whether it is prime or not.If it is prime then print it and change value of found variable to True. otherwise, iterate the loop until you will get the next prime number." }, { "code": null, "e": 685, "s": 613, "text": "First of all, take a boolean variable found and initialize it to false." }, { "code": null, "e": 803, "s": 685, "text": "Now, until that variable not equals to true, increment N by 1 in each iteration and check whether it is prime or not." }, { "code": null, "e": 946, "s": 803, "text": "If it is prime then print it and change value of found variable to True. otherwise, iterate the loop until you will get the next prime number." }, { "code": null, "e": 999, "s": 946, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1003, "s": 999, "text": "C++" }, { "code": null, "e": 1008, "s": 1003, "text": "Java" }, { "code": null, "e": 1016, "s": 1008, "text": "Python3" }, { "code": null, "e": 1019, "s": 1016, "text": "C#" }, { "code": null, "e": 1030, "s": 1019, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if n// is prime else returns falsebool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true;} // Function to return the smallest// prime number greater than Nint nextPrime(int N){ // Base case if (N <= 1) return 2; int prime = N; bool found = false; // Loop continuously until isPrime returns // true for a number greater than n while (!found) { prime++; if (isPrime(prime)) found = true; } return prime;} // Driver codeint main(){ int N = 3; cout << nextPrime(N); return 0;}", "e": 1977, "s": 1030, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function that returns true if n // is prime else returns false static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Function to return the smallest // prime number greater than N static int nextPrime(int N) { // Base case if (N <= 1) return 2; int prime = N; boolean found = false; // Loop continuously until isPrime returns // true for a number greater than n while (!found) { prime++; if (isPrime(prime)) found = true; } return prime; } // Driver code public static void main (String[] args) { int N = 3; System.out.println(nextPrime(N)); }} // This code is contributed by AnkitRai01", "e": 3208, "s": 1977, "text": null }, { "code": "# Python3 implementation of the approachimport math # Function that returns True if n# is prime else returns Falsedef isPrime(n): # Corner cases if(n <= 1): return False if(n <= 3): return True # This is checked so that we can skip # middle five numbers in below loop if(n % 2 == 0 or n % 3 == 0): return False for i in range(5,int(math.sqrt(n) + 1), 6): if(n % i == 0 or n % (i + 2) == 0): return False return True # Function to return the smallest# prime number greater than Ndef nextPrime(N): # Base case if (N <= 1): return 2 prime = N found = False # Loop continuously until isPrime returns # True for a number greater than n while(not found): prime = prime + 1 if(isPrime(prime) == True): found = True return prime # Driver codeN = 3print(nextPrime(N)) # This code is contributed by Sanjit_Prasad", "e": 4155, "s": 3208, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true if n // is prime else returns false static bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Function to return the smallest // prime number greater than N static int nextPrime(int N) { // Base case if (N <= 1) return 2; int prime = N; bool found = false; // Loop continuously until isPrime // returns true for a number // greater than n while (!found) { prime++; if (isPrime(prime)) found = true; } return prime; } // Driver code public static void Main (String[] args) { int N = 3; Console.WriteLine(nextPrime(N)); }} // This code is contributed by 29AjayKumar", "e": 5427, "s": 4155, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function that returns true if n// is prime else returns falsefunction isPrime(n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (let i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true;} // Function to return the smallest// prime number greater than N function nextPrime(N){ // Base case if (N <= 1) return 2; let prime = N; let found = false; // Loop continuously until isPrime returns // true for a number greater than n while (!found) { prime++; if (isPrime(prime)) found = true; } return prime;} // Driver code let N = 3; document.write(nextPrime(N)); // This code is contributed by Mayank Tyagi </script>", "e": 6384, "s": 5427, "text": null }, { "code": null, "e": 6386, "s": 6384, "text": "5" }, { "code": null, "e": 6392, "s": 6388, "text": "gp6" }, { "code": null, "e": 6406, "s": 6392, "text": "Sanjit_Prasad" }, { "code": null, "e": 6414, "s": 6406, "text": "ankthon" }, { "code": null, "e": 6426, "s": 6414, "text": "29AjayKumar" }, { "code": null, "e": 6442, "s": 6426, "text": "mayanktyagi1709" }, { "code": null, "e": 6451, "s": 6442, "text": "sooda367" }, { "code": null, "e": 6464, "s": 6451, "text": "Prime Number" }, { "code": null, "e": 6477, "s": 6464, "text": "Mathematical" }, { "code": null, "e": 6490, "s": 6477, "text": "Mathematical" }, { "code": null, "e": 6503, "s": 6490, "text": "Prime Number" }, { "code": null, "e": 6601, "s": 6503, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6625, "s": 6601, "text": "Merge two sorted arrays" }, { "code": null, "e": 6646, "s": 6625, "text": "Operators in C / C++" }, { "code": null, "e": 6699, "s": 6646, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 6736, "s": 6699, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 6768, "s": 6736, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 6811, "s": 6768, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 6852, "s": 6811, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 6895, "s": 6852, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 6922, "s": 6895, "text": "Modulo 10^9+7 (1000000007)" } ]
Smallest integer which has n factors or more
23 Jun, 2022 Given n, find the smallest integer which has n factors or more. It may be assumed that the result is less than 1000001. Examples: Input : n = 3 Output : 4 Explanation: 4 has factors 1, 2 and 4. Input : n = 2 Output : 2 Explanation: 2 has one factor 1 and 2. There are many methods to calculate the number of factors, but the efficient one can be found hereSimple Approach: A simple approach will be to run a loop to find out the factors of a number. One for finding out the factors of a number in O(x) is to run a loop from 1 to x and see all numbers that divide x. Time Complexity: O(x) for every number x that we try until we find the answer or reach the limit. Efficient Approach: We can find out factors in sqrt(x)for every iteration. Time Complexity: O(sqrt(x)) for every number x that we try until we find the answer or reach the limit. The Best Approach will be to traverse for every number and calculate the number of factors. Then check if the count is equal to or more than n then we get our desired smallest integer with n or more factors. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // c++ program to print the smallest// integer with n factors or more#include <bits/stdc++.h>using namespace std; const int MAX = 1000001; // array to store prime factorsint factor[MAX] = { 0 }; // function to generate all prime factors// of numbers from 1 to 10^6void generatePrimeFactors(){ factor[1] = 1; // Initializes all the positions // with their value. for (int i = 2; i < MAX; i++) factor[i] = i; // Initializes all multiples of 2 with 2 for (int i = 4; i < MAX; i += 2) factor[i] = 2; // A modified version of Sieve of // Eratosthenes to store the smallest // prime factor that divides every number. for (int i = 3; i * i < MAX; i++) { // check if it has no prime factor. if (factor[i] == i) { // Initializes of j starting from i*i for (int j = i * i; j < MAX; j += i) { // if it has no prime factor // before, then stores the // smallest prime divisor if (factor[j] == j) factor[j] = i; } } }} // function to calculate number of factorsint calculateNoOFactors(int n){ if (n == 1) return 1; int ans = 1; // stores the smallest prime number // that divides n int dup = factor[n]; // stores the count of number of times // a prime number divides n. int c = 1; // reduces to the next number after prime // factorization of n int j = n / factor[n]; // false when prime factorization is done while (j != 1) { // if the same prime number is dividing n, // then we increase the count if (factor[j] == dup) c += 1; /* if its a new prime factor that is factorizing n, then we again set c=1 and change dup to the new prime factor, and apply the formula explained above. */ else { dup = factor[j]; ans = ans * (c + 1); c = 1; } // prime factorizes a number j = j / factor[j]; } // for the last prime factor ans = ans * (c + 1); return ans;} // function to find the smallest integer// with n factors or more.int smallest(int n){ for (int i = 1;; i++) // check if no of factors is more // than n or not if (calculateNoOFactors(i) >= n) return i;} // Driver program to test above functionint main(){ // generate prime factors of number // upto 10^6 generatePrimeFactors(); int n = 4; cout << smallest(n); return 0;} // Java program to print the smallest// integer with n factors or moreimport java.util.*;import java.lang.*; public class GfG{ private static final int MAX = 1000001; // array to store prime factors private static final int[] factor = new int [MAX]; // function to generate all prime factors // of numbers from 1 to 10^6 public static void generatePrimeFactors() { factor[1] = 1; // Initializes all the positions // with their value. for (int i = 2; i < MAX; i++) factor[i] = i; // Initializes all multiples of 2 with 2 for (int i = 4; i < MAX; i += 2) factor[i] = 2; // A modified version of Sieve of // Eratosthenes to store the smallest // prime factor that divides every number. for (int i = 3; i * i < MAX; i++) { // check if it has no prime factor. if (factor[i] == i) { // Initializes of j starting from i*i for (int j = i * i; j < MAX; j += i) { // if it has no prime factor // before, then stores the // smallest prime divisor if (factor[j] == j) factor[j] = i; } } } } // function to calculate number of factors public static int calculateNoOFactors(int n) { if (n == 1) return 1; int ans = 1; // stores the smallest prime number // that divides n int dup = factor[n]; // stores the count of number of times // a prime number divides n. int c = 1; // reduces to the next number after prime // factorization of n int j = n / factor[n]; // false when prime factorization is done while (j != 1) { // if the same prime number is dividing n, // then we increase the count if (factor[j] == dup) c += 1; /* if its a new prime factor that is factorizing n, then we again set c=1 and change dup to the new prime factor, and apply the formula explained above. */ else { dup = factor[j]; ans = ans * (c + 1); c = 1; } // prime factorizes a number j = j / factor[j]; } // for the last prime factor ans = ans * (c + 1); return ans; } // function to find the smallest integer // with n factors or more. public static int smallest(int n) { for (int i = 1;; i++) // check if no of factors is more // than n or not if (calculateNoOFactors(i) >= n) return i; } // driver function public static void main(String args[]) { // generate prime factors of number // upto 10^6 generatePrimeFactors(); int n = 4; System.out.println(smallest(n)); }} /* This code is contributed by Sagar Shukla */ # Python3 program to print the# smallest integer with n# factors or moreMAX = 100001; # array to store# prime factorsfactor = [0] * MAX; # function to generate all# prime factors of numbers# from 1 to 10^6def generatePrimeFactors(): factor[1] = 1; # Initializes all the # positions with their value. for i in range(2, MAX): factor[i] = i; # Initializes all # multiples of 2 with 2 i = 4 while(i < MAX): factor[i] = 2; i += 2; # A modified version of # Sieve of Eratosthenes # to store the smallest # prime factor that # divides every number. i = 3; while(i * i < MAX): # check if it has # no prime factor. if (factor[i] == i): # Initializes of j # starting from i*i j = i * i; while(j < MAX): # if it has no prime factor # before, then stores the # smallest prime divisor if (factor[j] == j): factor[j] = i; j += i; i += 1; # function to calculate# number of factorsdef calculateNoOFactors(n): if (n == 1): return 1; ans = 1; # stores the smallest prime # number that divides n dup = factor[n]; # stores the count of # number of times a # prime number divides n. c = 1; # reduces to the next # number after prime # factorization of n j = int(n / factor[n]); # false when prime # factorization is done while (j != 1): # if the same prime number # is dividing n, then we # increase the count if (factor[j] == dup): c += 1; # if its a new prime factor # that is factorizing n, then # we again set c=1 and change # dup to the new prime factor, # and apply the formula # explained above. else: dup = factor[j]; ans = ans * (c + 1); c = 1; # prime factorizes a number j = int(j / factor[j]); # for the last prime factor ans = ans * (c + 1); return ans; # function to find the# smallest integer with# n factors or more.def smallest(n): i = 1; while(True): # check if no of # factors is more # than n or not if (calculateNoOFactors(i) >= n): return i; i += 1; # Driver Code # generate prime factors# of number upto 10^6generatePrimeFactors(); n = 4;print(smallest(n)); # This code is contributed by mits // C# program to print the smallest// integer with n factors or moreusing System; class GfG { private static int MAX = 1000001; // array to store prime factors private static int []factor = new int [MAX]; // function to generate all prime // factorsof numbers from 1 to 10^6 public static void generatePrimeFactors() { factor[1] = 1; // Initializes all the positions // with their value. for (int i = 2; i < MAX; i++) factor[i] = i; // Initializes all multiples of 2 with 2 for (int i = 4; i < MAX; i += 2) factor[i] = 2; // A modified version of Sieve of // Eratosthenes to store the smallest // prime factor that divides every number. for (int i = 3; i * i < MAX; i++) { // check if it has no prime factor. if (factor[i] == i) { // Initializes of j starting from i*i for (int j = i * i; j < MAX; j += i) { // if it has no prime factor // before, then stores the // smallest prime divisor if (factor[j] == j) factor[j] = i; } } } } // function to calculate number of factors public static int calculateNoOFactors(int n) { if (n == 1) return 1; int ans = 1; // stores the smallest prime number // that divides n int dup = factor[n]; // stores the count of number of times // a prime number divides n. int c = 1; // reduces to the next number after prime // factorization of n int j = n / factor[n]; // false when prime factorization is done while (j != 1) { // if the same prime number is dividing n, // then we increase the count if (factor[j] == dup) c += 1; // if its a new prime factor that is // factorizing n, then we again set c=1 // and change dup to the new prime factor, // and apply the formula explained above. else { dup = factor[j]; ans = ans * (c + 1); c = 1; } // prime factorizes a number j = j / factor[j]; } // for the last prime factor ans = ans * (c + 1); return ans; } // function to find the smallest integer // with n factors or more. public static int smallest(int n) { for (int i = 1; ; i++) // check if no of factors is more // than n or not if (calculateNoOFactors(i) >= n) return i; } // Driver Code public static void Main() { // generate prime factors of // number upto 10^6 generatePrimeFactors(); int n = 4; Console.Write(smallest(n)); }} // This code is contributed by Nitin Mittal. <?php// PHP program to print the// smallest integer with n// factors or more $MAX = 100001; // array to store// prime factors$factor = array_fill(0, $MAX, 0); // function to generate all// prime factors of numbers// from 1 to 10^6function generatePrimeFactors(){ global $MAX; global $factor; $factor[1] = 1; // Initializes all the // positions with their value. for ($i = 2; $i < $MAX; $i++) $factor[$i] = $i; // Initializes all // multiples of 2 with 2 for ($i = 4; $i < $MAX; $i += 2) $factor[$i] = 2; // A modified version of // Sieve of Eratosthenes // to store the smallest // prime factor that // divides every number. for ($i = 3; $i * $i < $MAX; $i++) { // check if it has // no prime factor. if ($factor[$i] == $i) { // Initializes of j // starting from i*i for ($j = $i * $i; $j < $MAX; $j += $i) { // if it has no prime factor // before, then stores the // smallest prime divisor if ($factor[$j] == $j) $factor[$j] = $i; } } }} // function to calculate// number of factorsfunction calculateNoOFactors($n){ global $factor; if ($n == 1) return 1; $ans = 1; // stores the smallest prime // number that divides n $dup = $factor[$n]; // stores the count of // number of times a // prime number divides n. $c = 1; // reduces to the next // number after prime // factorization of n $j = (int)($n / $factor[$n]); // false when prime // factorization is done while ($j != 1) { // if the same prime number // is dividing n, then we // increase the count if ($factor[$j] == $dup) $c += 1; /* if its a new prime factor that is factorizing n, then we again set c=1 and change dup to the new prime factor, and apply the formula explained above. */ else { $dup = $factor[$j]; $ans = $ans * ($c + 1); $c = 1; } // prime factorizes a number $j = (int)($j / $factor[$j]); } // for the last prime factor $ans = $ans * ($c + 1); return $ans;} // function to find the// smallest integer with// n factors or more.function smallest($n){ for ($i = 1;; $i++) // check if no of // factors is more // than n or not if (calculateNoOFactors($i) >= $n) return $i;} // Driver Code // generate prime factors// of number upto 10^6generatePrimeFactors(); $n = 4;echo smallest($n); // This code is contributed by mits?> <script>// javascript program to print the smallest// integer with n factors or more var MAX = 1000001; // array to store prime factors var factor = Array(MAX).fill(0); // function to generate all prime factors // of numbers from 1 to 10^6 function generatePrimeFactors() { factor[1] = 1; // Initializes all the positions // with their value. for (i = 2; i < MAX; i++) factor[i] = i; // Initializes all multiples of 2 with 2 for (i = 4; i < MAX; i += 2) factor[i] = 2; // A modified version of Sieve of // Eratosthenes to store the smallest // prime factor that divides every number. for (i = 3; i * i < MAX; i++) { // check if it has no prime factor. if (factor[i] == i) { // Initializes of j starting from i*i for (j = i * i; j < MAX; j += i) { // if it has no prime factor // before, then stores the // smallest prime divisor if (factor[j] == j) factor[j] = i; } } } } // function to calculate number of factors function calculateNoOFactors(n) { if (n == 1) return 1; var ans = 1; // stores the smallest prime number // that divides n var dup = factor[n]; // stores the count of number of times // a prime number divides n. var c = 1; // reduces to the next number after prime // factorization of n var j = n / factor[n]; // false when prime factorization is done while (j != 1) { // if the same prime number is dividing n, // then we increase the count if (factor[j] == dup) c += 1; /* * if its a new prime factor that is factorizing n, then we again set c=1 and * change dup to the new prime factor, and apply the formula explained above. */ else { dup = factor[j]; ans = ans * (c + 1); c = 1; } // prime factorizes a number j = j / factor[j]; } // for the last prime factor ans = ans * (c + 1); return ans; } // function to find the smallest integer // with n factors or more. function smallest(n) { for (i = 1;; i++) // check if no of factors is more // than n or not if (calculateNoOFactors(i) >= n) return i; } // driver function // generate prime factors of number // upto 10^6 generatePrimeFactors(); var n = 4; document.write(smallest(n)); // This code is contributed by todaysgaurav</script> Output: 6 Time Complexity: O(1000001) Auxiliary Space: O(1000001), size of this array is used Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal Mithun Kumar todaysgaurav Kirti_Mangal codewithmini divisors sieve Mathematical Mathematical sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Merge two sorted arrays with O(1) extra space Segment Tree | Set 1 (Sum of given range) Fizz Buzz Implementation Check if a number is Palindrome Count ways to reach the n'th stair Product of Array except itself Find Union and Intersection of two unsorted arrays Median of two sorted arrays of same size
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 172, "s": 52, "text": "Given n, find the smallest integer which has n factors or more. It may be assumed that the result is less than 1000001." }, { "code": null, "e": 184, "s": 172, "text": "Examples: " }, { "code": null, "e": 315, "s": 184, "text": "Input : n = 3\nOutput : 4\nExplanation: 4 has factors 1, 2 and 4.\n\nInput : n = 2 \nOutput : 2\nExplanation: 2 has one factor 1 and 2. " }, { "code": null, "e": 721, "s": 315, "text": "There are many methods to calculate the number of factors, but the efficient one can be found hereSimple Approach: A simple approach will be to run a loop to find out the factors of a number. One for finding out the factors of a number in O(x) is to run a loop from 1 to x and see all numbers that divide x. Time Complexity: O(x) for every number x that we try until we find the answer or reach the limit." }, { "code": null, "e": 900, "s": 721, "text": "Efficient Approach: We can find out factors in sqrt(x)for every iteration. Time Complexity: O(sqrt(x)) for every number x that we try until we find the answer or reach the limit." }, { "code": null, "e": 1160, "s": 900, "text": "The Best Approach will be to traverse for every number and calculate the number of factors. Then check if the count is equal to or more than n then we get our desired smallest integer with n or more factors. Below is the implementation of the above approach: " }, { "code": null, "e": 1164, "s": 1160, "text": "C++" }, { "code": null, "e": 1169, "s": 1164, "text": "Java" }, { "code": null, "e": 1177, "s": 1169, "text": "Python3" }, { "code": null, "e": 1180, "s": 1177, "text": "C#" }, { "code": null, "e": 1184, "s": 1180, "text": "PHP" }, { "code": null, "e": 1195, "s": 1184, "text": "Javascript" }, { "code": "// c++ program to print the smallest// integer with n factors or more#include <bits/stdc++.h>using namespace std; const int MAX = 1000001; // array to store prime factorsint factor[MAX] = { 0 }; // function to generate all prime factors// of numbers from 1 to 10^6void generatePrimeFactors(){ factor[1] = 1; // Initializes all the positions // with their value. for (int i = 2; i < MAX; i++) factor[i] = i; // Initializes all multiples of 2 with 2 for (int i = 4; i < MAX; i += 2) factor[i] = 2; // A modified version of Sieve of // Eratosthenes to store the smallest // prime factor that divides every number. for (int i = 3; i * i < MAX; i++) { // check if it has no prime factor. if (factor[i] == i) { // Initializes of j starting from i*i for (int j = i * i; j < MAX; j += i) { // if it has no prime factor // before, then stores the // smallest prime divisor if (factor[j] == j) factor[j] = i; } } }} // function to calculate number of factorsint calculateNoOFactors(int n){ if (n == 1) return 1; int ans = 1; // stores the smallest prime number // that divides n int dup = factor[n]; // stores the count of number of times // a prime number divides n. int c = 1; // reduces to the next number after prime // factorization of n int j = n / factor[n]; // false when prime factorization is done while (j != 1) { // if the same prime number is dividing n, // then we increase the count if (factor[j] == dup) c += 1; /* if its a new prime factor that is factorizing n, then we again set c=1 and change dup to the new prime factor, and apply the formula explained above. */ else { dup = factor[j]; ans = ans * (c + 1); c = 1; } // prime factorizes a number j = j / factor[j]; } // for the last prime factor ans = ans * (c + 1); return ans;} // function to find the smallest integer// with n factors or more.int smallest(int n){ for (int i = 1;; i++) // check if no of factors is more // than n or not if (calculateNoOFactors(i) >= n) return i;} // Driver program to test above functionint main(){ // generate prime factors of number // upto 10^6 generatePrimeFactors(); int n = 4; cout << smallest(n); return 0;}", "e": 3747, "s": 1195, "text": null }, { "code": "// Java program to print the smallest// integer with n factors or moreimport java.util.*;import java.lang.*; public class GfG{ private static final int MAX = 1000001; // array to store prime factors private static final int[] factor = new int [MAX]; // function to generate all prime factors // of numbers from 1 to 10^6 public static void generatePrimeFactors() { factor[1] = 1; // Initializes all the positions // with their value. for (int i = 2; i < MAX; i++) factor[i] = i; // Initializes all multiples of 2 with 2 for (int i = 4; i < MAX; i += 2) factor[i] = 2; // A modified version of Sieve of // Eratosthenes to store the smallest // prime factor that divides every number. for (int i = 3; i * i < MAX; i++) { // check if it has no prime factor. if (factor[i] == i) { // Initializes of j starting from i*i for (int j = i * i; j < MAX; j += i) { // if it has no prime factor // before, then stores the // smallest prime divisor if (factor[j] == j) factor[j] = i; } } } } // function to calculate number of factors public static int calculateNoOFactors(int n) { if (n == 1) return 1; int ans = 1; // stores the smallest prime number // that divides n int dup = factor[n]; // stores the count of number of times // a prime number divides n. int c = 1; // reduces to the next number after prime // factorization of n int j = n / factor[n]; // false when prime factorization is done while (j != 1) { // if the same prime number is dividing n, // then we increase the count if (factor[j] == dup) c += 1; /* if its a new prime factor that is factorizing n, then we again set c=1 and change dup to the new prime factor, and apply the formula explained above. */ else { dup = factor[j]; ans = ans * (c + 1); c = 1; } // prime factorizes a number j = j / factor[j]; } // for the last prime factor ans = ans * (c + 1); return ans; } // function to find the smallest integer // with n factors or more. public static int smallest(int n) { for (int i = 1;; i++) // check if no of factors is more // than n or not if (calculateNoOFactors(i) >= n) return i; } // driver function public static void main(String args[]) { // generate prime factors of number // upto 10^6 generatePrimeFactors(); int n = 4; System.out.println(smallest(n)); }} /* This code is contributed by Sagar Shukla */", "e": 6794, "s": 3747, "text": null }, { "code": "# Python3 program to print the# smallest integer with n# factors or moreMAX = 100001; # array to store# prime factorsfactor = [0] * MAX; # function to generate all# prime factors of numbers# from 1 to 10^6def generatePrimeFactors(): factor[1] = 1; # Initializes all the # positions with their value. for i in range(2, MAX): factor[i] = i; # Initializes all # multiples of 2 with 2 i = 4 while(i < MAX): factor[i] = 2; i += 2; # A modified version of # Sieve of Eratosthenes # to store the smallest # prime factor that # divides every number. i = 3; while(i * i < MAX): # check if it has # no prime factor. if (factor[i] == i): # Initializes of j # starting from i*i j = i * i; while(j < MAX): # if it has no prime factor # before, then stores the # smallest prime divisor if (factor[j] == j): factor[j] = i; j += i; i += 1; # function to calculate# number of factorsdef calculateNoOFactors(n): if (n == 1): return 1; ans = 1; # stores the smallest prime # number that divides n dup = factor[n]; # stores the count of # number of times a # prime number divides n. c = 1; # reduces to the next # number after prime # factorization of n j = int(n / factor[n]); # false when prime # factorization is done while (j != 1): # if the same prime number # is dividing n, then we # increase the count if (factor[j] == dup): c += 1; # if its a new prime factor # that is factorizing n, then # we again set c=1 and change # dup to the new prime factor, # and apply the formula # explained above. else: dup = factor[j]; ans = ans * (c + 1); c = 1; # prime factorizes a number j = int(j / factor[j]); # for the last prime factor ans = ans * (c + 1); return ans; # function to find the# smallest integer with# n factors or more.def smallest(n): i = 1; while(True): # check if no of # factors is more # than n or not if (calculateNoOFactors(i) >= n): return i; i += 1; # Driver Code # generate prime factors# of number upto 10^6generatePrimeFactors(); n = 4;print(smallest(n)); # This code is contributed by mits", "e": 9303, "s": 6794, "text": null }, { "code": "// C# program to print the smallest// integer with n factors or moreusing System; class GfG { private static int MAX = 1000001; // array to store prime factors private static int []factor = new int [MAX]; // function to generate all prime // factorsof numbers from 1 to 10^6 public static void generatePrimeFactors() { factor[1] = 1; // Initializes all the positions // with their value. for (int i = 2; i < MAX; i++) factor[i] = i; // Initializes all multiples of 2 with 2 for (int i = 4; i < MAX; i += 2) factor[i] = 2; // A modified version of Sieve of // Eratosthenes to store the smallest // prime factor that divides every number. for (int i = 3; i * i < MAX; i++) { // check if it has no prime factor. if (factor[i] == i) { // Initializes of j starting from i*i for (int j = i * i; j < MAX; j += i) { // if it has no prime factor // before, then stores the // smallest prime divisor if (factor[j] == j) factor[j] = i; } } } } // function to calculate number of factors public static int calculateNoOFactors(int n) { if (n == 1) return 1; int ans = 1; // stores the smallest prime number // that divides n int dup = factor[n]; // stores the count of number of times // a prime number divides n. int c = 1; // reduces to the next number after prime // factorization of n int j = n / factor[n]; // false when prime factorization is done while (j != 1) { // if the same prime number is dividing n, // then we increase the count if (factor[j] == dup) c += 1; // if its a new prime factor that is // factorizing n, then we again set c=1 // and change dup to the new prime factor, // and apply the formula explained above. else { dup = factor[j]; ans = ans * (c + 1); c = 1; } // prime factorizes a number j = j / factor[j]; } // for the last prime factor ans = ans * (c + 1); return ans; } // function to find the smallest integer // with n factors or more. public static int smallest(int n) { for (int i = 1; ; i++) // check if no of factors is more // than n or not if (calculateNoOFactors(i) >= n) return i; } // Driver Code public static void Main() { // generate prime factors of // number upto 10^6 generatePrimeFactors(); int n = 4; Console.Write(smallest(n)); }} // This code is contributed by Nitin Mittal.", "e": 12311, "s": 9303, "text": null }, { "code": "<?php// PHP program to print the// smallest integer with n// factors or more $MAX = 100001; // array to store// prime factors$factor = array_fill(0, $MAX, 0); // function to generate all// prime factors of numbers// from 1 to 10^6function generatePrimeFactors(){ global $MAX; global $factor; $factor[1] = 1; // Initializes all the // positions with their value. for ($i = 2; $i < $MAX; $i++) $factor[$i] = $i; // Initializes all // multiples of 2 with 2 for ($i = 4; $i < $MAX; $i += 2) $factor[$i] = 2; // A modified version of // Sieve of Eratosthenes // to store the smallest // prime factor that // divides every number. for ($i = 3; $i * $i < $MAX; $i++) { // check if it has // no prime factor. if ($factor[$i] == $i) { // Initializes of j // starting from i*i for ($j = $i * $i; $j < $MAX; $j += $i) { // if it has no prime factor // before, then stores the // smallest prime divisor if ($factor[$j] == $j) $factor[$j] = $i; } } }} // function to calculate// number of factorsfunction calculateNoOFactors($n){ global $factor; if ($n == 1) return 1; $ans = 1; // stores the smallest prime // number that divides n $dup = $factor[$n]; // stores the count of // number of times a // prime number divides n. $c = 1; // reduces to the next // number after prime // factorization of n $j = (int)($n / $factor[$n]); // false when prime // factorization is done while ($j != 1) { // if the same prime number // is dividing n, then we // increase the count if ($factor[$j] == $dup) $c += 1; /* if its a new prime factor that is factorizing n, then we again set c=1 and change dup to the new prime factor, and apply the formula explained above. */ else { $dup = $factor[$j]; $ans = $ans * ($c + 1); $c = 1; } // prime factorizes a number $j = (int)($j / $factor[$j]); } // for the last prime factor $ans = $ans * ($c + 1); return $ans;} // function to find the// smallest integer with// n factors or more.function smallest($n){ for ($i = 1;; $i++) // check if no of // factors is more // than n or not if (calculateNoOFactors($i) >= $n) return $i;} // Driver Code // generate prime factors// of number upto 10^6generatePrimeFactors(); $n = 4;echo smallest($n); // This code is contributed by mits?>", "e": 15038, "s": 12311, "text": null }, { "code": "<script>// javascript program to print the smallest// integer with n factors or more var MAX = 1000001; // array to store prime factors var factor = Array(MAX).fill(0); // function to generate all prime factors // of numbers from 1 to 10^6 function generatePrimeFactors() { factor[1] = 1; // Initializes all the positions // with their value. for (i = 2; i < MAX; i++) factor[i] = i; // Initializes all multiples of 2 with 2 for (i = 4; i < MAX; i += 2) factor[i] = 2; // A modified version of Sieve of // Eratosthenes to store the smallest // prime factor that divides every number. for (i = 3; i * i < MAX; i++) { // check if it has no prime factor. if (factor[i] == i) { // Initializes of j starting from i*i for (j = i * i; j < MAX; j += i) { // if it has no prime factor // before, then stores the // smallest prime divisor if (factor[j] == j) factor[j] = i; } } } } // function to calculate number of factors function calculateNoOFactors(n) { if (n == 1) return 1; var ans = 1; // stores the smallest prime number // that divides n var dup = factor[n]; // stores the count of number of times // a prime number divides n. var c = 1; // reduces to the next number after prime // factorization of n var j = n / factor[n]; // false when prime factorization is done while (j != 1) { // if the same prime number is dividing n, // then we increase the count if (factor[j] == dup) c += 1; /* * if its a new prime factor that is factorizing n, then we again set c=1 and * change dup to the new prime factor, and apply the formula explained above. */ else { dup = factor[j]; ans = ans * (c + 1); c = 1; } // prime factorizes a number j = j / factor[j]; } // for the last prime factor ans = ans * (c + 1); return ans; } // function to find the smallest integer // with n factors or more. function smallest(n) { for (i = 1;; i++) // check if no of factors is more // than n or not if (calculateNoOFactors(i) >= n) return i; } // driver function // generate prime factors of number // upto 10^6 generatePrimeFactors(); var n = 4; document.write(smallest(n)); // This code is contributed by todaysgaurav</script>", "e": 17897, "s": 15038, "text": null }, { "code": null, "e": 17907, "s": 17897, "text": "Output: " }, { "code": null, "e": 17909, "s": 17907, "text": "6" }, { "code": null, "e": 17937, "s": 17909, "text": "Time Complexity: O(1000001)" }, { "code": null, "e": 17993, "s": 17937, "text": "Auxiliary Space: O(1000001), size of this array is used" }, { "code": null, "e": 18260, "s": 17993, "text": "Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 18273, "s": 18260, "text": "nitin mittal" }, { "code": null, "e": 18286, "s": 18273, "text": "Mithun Kumar" }, { "code": null, "e": 18299, "s": 18286, "text": "todaysgaurav" }, { "code": null, "e": 18312, "s": 18299, "text": "Kirti_Mangal" }, { "code": null, "e": 18325, "s": 18312, "text": "codewithmini" }, { "code": null, "e": 18334, "s": 18325, "text": "divisors" }, { "code": null, "e": 18340, "s": 18334, "text": "sieve" }, { "code": null, "e": 18353, "s": 18340, "text": "Mathematical" }, { "code": null, "e": 18366, "s": 18353, "text": "Mathematical" }, { "code": null, "e": 18372, "s": 18366, "text": "sieve" }, { "code": null, "e": 18470, "s": 18372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18502, "s": 18470, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 18546, "s": 18502, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 18592, "s": 18546, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 18634, "s": 18592, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 18659, "s": 18634, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 18691, "s": 18659, "text": "Check if a number is Palindrome" }, { "code": null, "e": 18726, "s": 18691, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 18757, "s": 18726, "text": "Product of Array except itself" }, { "code": null, "e": 18808, "s": 18757, "text": "Find Union and Intersection of two unsorted arrays" } ]
JavaFX | FileChooser Class
04 Oct, 2021 FileChooser class is a part of JavaFX. It is used to invoke file open dialogs for selecting a single file (showOpenDialog), file open dialogs for selecting multiple files (showOpenMultipleDialog) and file save dialogs (showSaveDialog). FileChooser class inherits Object class. Constructor of the class are : FileChooser() : Creates a new FileChooser dialog. Commonly Used Methods: Below programs illustrate the use of FileChooser Class: 1. Java Program to create fileChooser and add it to the stage: In this program we will create a file chooser named file_chooser. Then create a Label named label and two Buttons named button and button1. We will create two EventHandler to handle the events when the button or button1 pressed. When the button is pressed, an open file chooser dialog appears and the selected file is shown as text in the label and when button1 is pressed, a save file chooser appears and the selected file is shown as text in the label. Add the label and the button to Vbox and add the VBox to the Scene and add the scene to the stage, and call the show() function to display the final results. Java // Java Program to create fileChooser// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.geometry.*;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import java.io.*;import javafx.stage.FileChooser; public class FileChooser_1 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle("FileChooser"); // create a File chooser FileChooser fil_chooser = new FileChooser(); // create a Label Label label = new Label("no files selected"); // create a Button Button button = new Button("Show open dialog"); // create an Event Handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // get the file selected File file = fil_chooser.showOpenDialog(stage); if (file != null) { label.setText(file.getAbsolutePath() + " selected"); } } }; button.setOnAction(event); // create a Button Button button1 = new Button("Show save dialog"); // create an Event Handler EventHandler<ActionEvent> event1 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // get the file selected File file = fil_chooser.showSaveDialog(stage); if (file != null) { label.setText(file.getAbsolutePath() + " selected"); } } }; button1.setOnAction(event1); // create a VBox VBox vbox = new VBox(30, label, button, button1); // set Alignment vbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(vbox, 800, 500); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}} Output: 2. Java Program to create FileChooser, set title, initial File and add it to the stage: In this program we will create a file chooser named fil_chooser . Then create a Label named label and two Buttons named button and button1. Set the title and initial directory of file chooser using the setTitle() and setInitialDirectory() function. Now create two EventHandler to handle the events when the button or button1 pressed. When the button is pressed, an open file chooser dialog appears and the selected file is shown as text in the label and when button1 is pressed, a save file chooser appears and the selected file is shown as text in the label. Add the label and the button to Vbox and add the VBox to the Scene and add the scene to the stage, and call the show() function to display the final results. Java // Java Program to create FileChooser// & set title, initial File// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.geometry.*;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import java.io.*;import javafx.stage.FileChooser; public class FileChooser_2 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle("FileChooser"); // create a File chooser FileChooser fil_chooser = new FileChooser(); // set title fil_chooser.setTitle("Select File"); // set initial File fil_chooser.setInitialDirectory(new File("e:\\")); // create a Label Label label = new Label("no files selected"); // create a Button Button button = new Button("Show open dialog"); // create an Event Handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // get the file selected File file = fil_chooser.showOpenDialog(stage); if (file != null) { label.setText(file.getAbsolutePath() + " selected"); } } }; button.setOnAction(event); // create a Button Button button1 = new Button("Show save dialog"); // create an Event Handler EventHandler<ActionEvent> event1 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // get the file selected File file = fil_chooser.showSaveDialog(stage); if (file != null) { label.setText(file.getAbsolutePath() + " selected"); } } }; button1.setOnAction(event1); // create a VBox VBox vbox = new VBox(30, label, button, button1); // set Alignment vbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(vbox, 800, 500); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}} Output: Note: The above programs might not run in an online IDE please use an offline compiler. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/stage/FileChooser.html simranarora5sos JavaFX 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 Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Oct, 2021" }, { "code": null, "e": 305, "s": 28, "text": "FileChooser class is a part of JavaFX. It is used to invoke file open dialogs for selecting a single file (showOpenDialog), file open dialogs for selecting multiple files (showOpenMultipleDialog) and file save dialogs (showSaveDialog). FileChooser class inherits Object class." }, { "code": null, "e": 337, "s": 305, "text": "Constructor of the class are : " }, { "code": null, "e": 387, "s": 337, "text": "FileChooser() : Creates a new FileChooser dialog." }, { "code": null, "e": 411, "s": 387, "text": "Commonly Used Methods: " }, { "code": null, "e": 467, "s": 411, "text": "Below programs illustrate the use of FileChooser Class:" }, { "code": null, "e": 1143, "s": 467, "text": "1. Java Program to create fileChooser and add it to the stage: In this program we will create a file chooser named file_chooser. Then create a Label named label and two Buttons named button and button1. We will create two EventHandler to handle the events when the button or button1 pressed. When the button is pressed, an open file chooser dialog appears and the selected file is shown as text in the label and when button1 is pressed, a save file chooser appears and the selected file is shown as text in the label. Add the label and the button to Vbox and add the VBox to the Scene and add the scene to the stage, and call the show() function to display the final results." }, { "code": null, "e": 1148, "s": 1143, "text": "Java" }, { "code": "// Java Program to create fileChooser// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.geometry.*;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import java.io.*;import javafx.stage.FileChooser; public class FileChooser_1 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle(\"FileChooser\"); // create a File chooser FileChooser fil_chooser = new FileChooser(); // create a Label Label label = new Label(\"no files selected\"); // create a Button Button button = new Button(\"Show open dialog\"); // create an Event Handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // get the file selected File file = fil_chooser.showOpenDialog(stage); if (file != null) { label.setText(file.getAbsolutePath() + \" selected\"); } } }; button.setOnAction(event); // create a Button Button button1 = new Button(\"Show save dialog\"); // create an Event Handler EventHandler<ActionEvent> event1 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // get the file selected File file = fil_chooser.showSaveDialog(stage); if (file != null) { label.setText(file.getAbsolutePath() + \" selected\"); } } }; button1.setOnAction(event1); // create a VBox VBox vbox = new VBox(30, label, button, button1); // set Alignment vbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(vbox, 800, 500); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}", "e": 3695, "s": 1148, "text": null }, { "code": null, "e": 3703, "s": 3695, "text": "Output:" }, { "code": null, "e": 4509, "s": 3703, "text": "2. Java Program to create FileChooser, set title, initial File and add it to the stage: In this program we will create a file chooser named fil_chooser . Then create a Label named label and two Buttons named button and button1. Set the title and initial directory of file chooser using the setTitle() and setInitialDirectory() function. Now create two EventHandler to handle the events when the button or button1 pressed. When the button is pressed, an open file chooser dialog appears and the selected file is shown as text in the label and when button1 is pressed, a save file chooser appears and the selected file is shown as text in the label. Add the label and the button to Vbox and add the VBox to the Scene and add the scene to the stage, and call the show() function to display the final results." }, { "code": null, "e": 4514, "s": 4509, "text": "Java" }, { "code": "// Java Program to create FileChooser// & set title, initial File// and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.geometry.*;import javafx.scene.paint.*;import javafx.scene.canvas.*;import javafx.scene.text.*;import javafx.scene.Group;import javafx.scene.shape.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import java.io.*;import javafx.stage.FileChooser; public class FileChooser_2 extends Application { // launch the applicationpublic void start(Stage stage){ try { // set title for the stage stage.setTitle(\"FileChooser\"); // create a File chooser FileChooser fil_chooser = new FileChooser(); // set title fil_chooser.setTitle(\"Select File\"); // set initial File fil_chooser.setInitialDirectory(new File(\"e:\\\\\")); // create a Label Label label = new Label(\"no files selected\"); // create a Button Button button = new Button(\"Show open dialog\"); // create an Event Handler EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // get the file selected File file = fil_chooser.showOpenDialog(stage); if (file != null) { label.setText(file.getAbsolutePath() + \" selected\"); } } }; button.setOnAction(event); // create a Button Button button1 = new Button(\"Show save dialog\"); // create an Event Handler EventHandler<ActionEvent> event1 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // get the file selected File file = fil_chooser.showSaveDialog(stage); if (file != null) { label.setText(file.getAbsolutePath() + \" selected\"); } } }; button1.setOnAction(event1); // create a VBox VBox vbox = new VBox(30, label, button, button1); // set Alignment vbox.setAlignment(Pos.CENTER); // create a scene Scene scene = new Scene(vbox, 800, 500); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); }} // Main Methodpublic static void main(String args[]){ // launch the application launch(args);}}", "e": 7218, "s": 4514, "text": null }, { "code": null, "e": 7226, "s": 7218, "text": "Output:" }, { "code": null, "e": 7314, "s": 7226, "text": "Note: The above programs might not run in an online IDE please use an offline compiler." }, { "code": null, "e": 7400, "s": 7314, "text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/stage/FileChooser.html " }, { "code": null, "e": 7416, "s": 7400, "text": "simranarora5sos" }, { "code": null, "e": 7423, "s": 7416, "text": "JavaFX" }, { "code": null, "e": 7428, "s": 7423, "text": "Java" }, { "code": null, "e": 7433, "s": 7428, "text": "Java" }, { "code": null, "e": 7531, "s": 7433, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7582, "s": 7531, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 7613, "s": 7582, "text": "How to iterate any Map in Java" }, { "code": null, "e": 7632, "s": 7613, "text": "Interfaces in Java" }, { "code": null, "e": 7662, "s": 7632, "text": "HashMap in Java with Examples" }, { "code": null, "e": 7677, "s": 7662, "text": "Stream In Java" }, { "code": null, "e": 7697, "s": 7677, "text": "Collections in Java" }, { "code": null, "e": 7721, "s": 7697, "text": "Singleton Class in Java" }, { "code": null, "e": 7753, "s": 7721, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7765, "s": 7753, "text": "Set in Java" } ]
Frequency of a substring in a string
09 Dec, 2021 Given an input string and a substring. Find the frequency of occurrences of a substring in a given string. Examples: Input : man (pattern) dhimanman (string) Output : 2 Input : nn (pattern) Banana (String) Output : 0 Input : man (pattern) dhimanman (string) Output : 2 Input : aa (pattern) aaaaa (String) Output : 4 A simple solution is to match characters one by one. And whenever we see a complete match, we increment count. Below is simple solution based on Naive pattern searching. C++ Java Python3 C# PHP Javascript // Simple C++ program to count occurrences// of pat in txt.#include<bits/stdc++.h>using namespace std; int countFreq(string &pat, string &txt){ int M = pat.length(); int N = txt.length(); int res = 0; /* A loop to slide pat[] one by one */ for (int i = 0; i <= N - M; i++) { /* For current index i, check for pattern match */ int j; for (j = 0; j < M; j++) if (txt[i+j] != pat[j]) break; // if pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) { res++; } } return res;} /* Driver program to test above function */int main(){ string txt = "dhimanman"; string pat = "man"; cout << countFreq(pat, txt); return 0;} // Simple Java program to count occurrences// of pat in txt. class GFG { static int countFreq(String pat, String txt) { int M = pat.length(); int N = txt.length(); int res = 0; /* A loop to slide pat[] one by one */ for (int i = 0; i <= N - M; i++) { /* For current index i, check for pattern match */ int j; for (j = 0; j < M; j++) { if (txt.charAt(i + j) != pat.charAt(j)) { break; } } // if pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) { res++; j = 0; } } return res; } /* Driver program to test above function */ static public void main(String[] args) { String txt = "dhimanman"; String pat = "man"; System.out.println(countFreq(pat, txt)); }} // This code is contributed by 29AjayKumar # Simple python program to count# occurrences of pat in txt.def countFreq(pat, txt): M = len(pat) N = len(txt) res = 0 # A loop to slide pat[] one by one for i in range(N - M + 1): # For current index i, check # for pattern match j = 0 while j < M: if (txt[i + j] != pat[j]): break j += 1 if (j == M): res += 1 j = 0 return res # Driver Codeif __name__ == '__main__': txt = "dhimanman" pat = "man" print(countFreq(pat, txt)) # This code is contributed# by PrinciRaj1992 // Simple C# program to count occurrences// of pat in txt.using System;public class GFG { static int countFreq(String pat, String txt) { int M = pat.Length; int N = txt.Length; int res = 0; /* A loop to slide pat[] one by one */ for (int i = 0; i <= N - M; i++) { /* For current index i, check for pattern match */ int j; for (j = 0; j < M; j++) { if (txt[i + j] != pat[j]) { break; } } // if pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) { res++; j = 0; } } return res; } /* Driver program to test above function */ static public void Main() { String txt = "dhimanman"; String pat = "man"; Console.Write(countFreq(pat, txt)); }} // This code is contributed by 29AjayKumar <?php// Simple PHP program to count occurrences// of pat in txt. function countFreq($pat, $txt){ $M = strlen($pat); $N = strlen($txt); $res = 0; /* A loop to slide pat[] one by one */ for ($i = 0; $i <= $N - $M; $i++) { /* For current index i, check for pattern match */ for ($j = 0; $j < $M; $j++) if ($txt[$i+$j] != $pat[$j]) break; // if pat[0...M-1] = txt[i, i+1, ...i+M-1] if ($j == $M) { $res++; $j = 0; } } return $res;} // Driver Code$txt = "dhimanman";$pat = "man";echo countFreq($pat, $txt); // This code is contributed// by Akanksha Rai <script> // JavaScript program to count occurrences// of pat in txt.let mod = 100000007; function countFreq(pat, txt){ let M = pat.length; let N = txt.length; let res = 0; // A loop to slide pat[] one by one for(let i = 0; i <= N - M; i++) { // For current index i, check for // pattern match let j; for(j = 0; j < M; j++) { if (txt[i + j] != pat[j]) { break; } } // If pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) { res++; j = 0; } } return res; } // Driver Codelet txt = "dhimanman"; let pat = "man"; document.write(countFreq(pat, txt)); // This code is contributed by code_hunt </script> 2 Time Complexity: O(M * N) Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. An efficient solution is to use KMP algorithm. C++ Java Python3 C# Javascript // C++ program to count occurrences// of pattern in a text.#include <iostream>using namespace std; void computeLPSArray(string pat, int M, int lps[]){ // Length of the previous longest // prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // The loop calculates lps[i] for // i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not // increment i here } else // if (len == 0) { lps[i] = len; i++; } } }} int KMPSearch(string pat, string txt){ int M = pat.length(); int N = txt.length(); // Create lps[] that will hold the longest // prefix suffix values for pattern int lps[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] int res = 0; int next_i = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { // When we find pattern first time, // we iterate again to check if there // exists more pattern j = lps[j - 1]; res++; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] // characters, they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } return res;} // Driver codeint main(){ string txt = "geeksforgeeks"; string pat = "eeks"; int ans = KMPSearch(pat, txt); cout << ans; return 0;} // This code is contributed by akhilsaini // Java program to count occurrences of pattern// in a text.class KMP_String_Matching{ int KMPSearch(String pat, String txt) { int M = pat.length(); int N = txt.length(); // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat,M,lps); int i = 0; // index for txt[] int res = 0; int next_i = 0; while (i < N) { if (pat.charAt(j) == txt.charAt(i)) { j++; i++; } if (j == M) { // When we find pattern first time, // we iterate again to check if there // exists more pattern j = lps[j-1]; res++; // We start i to check for more than once // appearance of pattern, we will reset i // to previous start+1 if (lps[j]!=0) i = ++next_i; j = 0; } // mismatch after j matches else if (i < N && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j-1]; else i = i+1; } } return res; } void computeLPSArray(String pat, int M, int lps[]) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len-1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver program to test above function public static void main(String args[]) { String txt = "geeksforgeeks"; String pat = "eeks"; int ans = new KMP_String_Matching().KMPSearch(pat,txt); System.out.println(ans); }} # Python3 program to count occurrences of# pattern in a text.def KMPSearch(pat, txt): M = len(pat) N = len(txt) # Create lps[] that will hold the longest # prefix suffix values for pattern lps = [None] * M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] # array) computeLPSArray(pat, M, lps) i = 0 # index for txt[] res = 0 next_i = 0 while (i < N): if pat[j] == txt[i]: j = j + 1 i = i + 1 if j == M: # When we find pattern first time, # we iterate again to check if there # exists more pattern j = lps[j - 1] res = res + 1 # We start i to check for more than once # appearance of pattern, we will reset i # to previous start+1 if lps[j] != 0: next_i = next_i + 1 i = next_i j = 0 # Mismatch after j matches elif ((i < N) and (pat[j] != txt[i])): # Do not match lps[0..lps[j-1]] # characters, they will match anyway if (j != 0): j = lps[j - 1] else: i = i + 1 return res def computeLPSArray(pat, M, lps): # Length of the previous longest # prefix suffix len = 0 i = 1 lps[0] = 0 # lps[0] is always 0 # The loop calculates lps[i] for # i = 1 to M-1 while (i < M): if pat[i] == pat[len]: len = len + 1 lps[i] = len i = i + 1 else: # (pat[i] != pat[len]) # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if len != 0: len = lps[len - 1] # Also, note that we do not increment # i here else: # if (len == 0) lps[i] = len i = i + 1 # Driver codeif __name__ == "__main__": txt = "geeksforgeeks" pat = "eeks" ans = KMPSearch(pat, txt) print(ans) # This code is contributed by akhilsaini // C# program to count occurrences of pattern// in a text.using System; public class KMP_String_Matching{ int KMPSearch(String pat, String txt) { int M = pat.Length; int N = txt.Length; // create lps[] that will hold the longest // prefix suffix values for pattern int []lps = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat,M,lps); int i = 0; // index for txt[] int res = 0; int next_i = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { // When we find pattern first time, // we iterate again to check if there // exists more pattern j = lps[j-1]; res++; // We start i to check for more than once // appearance of pattern, we will reset i // to previous start+1 if (lps[j]!=0) i = ++next_i; j = 0; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j-1]; else i = i+1; } } return res; } void computeLPSArray(String pat, int M, int []lps) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len-1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver code public static void Main(String []args) { String txt = "geeksforgeeks"; String pat = "eeks"; int ans = new KMP_String_Matching().KMPSearch(pat,txt); Console.WriteLine(ans); }} // This code is contributed by Princi Singh <script> // JavaScript program to count occurrences // of pattern in a text. function computeLPSArray(pat,M,lps) { // Length of the previous longest // prefix suffix let len = 0; let i = 1; lps[0] = 0; // lps[0] is always 0 // The loop calculates lps[i] for // i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not // increment i here } else // if (len == 0) { lps[i] = len; i++; } } } } function KMPSearch(pat,txt) { let M = pat.length; let N = txt.length; // Create lps[] that will hold the longest // prefix suffix values for pattern let lps = new Array(M); lps.fill(0); let j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); let i = 0; // index for txt[] let res = 0; let next_i = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { // When we find pattern first time, // we iterate again to check if there // exists more pattern j = lps[j - 1]; res++; // We start i to check for more than once // appearance of pattern, we will reset i // to previous start+1 if (lps[j]!=0) i = ++next_i; j = 0; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] // characters, they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } return res; } // Driver code let txt = "geeksforgeeks"; let pat = "eeks"; let ans = KMPSearch(pat, txt); document.write(ans); </script> 2 Time Complexity : O(M + N) KMP Algorithm | Searching for Patterns | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersKMP Algorithm | Searching for Patterns | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:25•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cH-5KcgUcOE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 29AjayKumar princiraj1992 Akanksha_Rai ROHITKISHORTRIPATHI princi singh vinaylingam akhilsaini surajjain code_hunt kavania2002 vaibhavrabadiya117 zaid47304 frequency-counting Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if an URL is valid or not using Regular Expression Search a Word in a 2D Grid of characters Split the binary string into substrings with equal number of 0s and 1s String matching where one string contains wildcard characters Find all occurrences of a given word in a matrix Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Dec, 2021" }, { "code": null, "e": 161, "s": 54, "text": "Given an input string and a substring. Find the frequency of occurrences of a substring in a given string." }, { "code": null, "e": 172, "s": 161, "text": "Examples: " }, { "code": null, "e": 406, "s": 172, "text": "Input : man (pattern)\n dhimanman (string)\nOutput : 2\n\nInput : nn (pattern)\n Banana (String)\nOutput : 0\n\nInput : man (pattern)\n dhimanman (string)\nOutput : 2\n\nInput : aa (pattern)\n aaaaa (String)\nOutput : 4" }, { "code": null, "e": 577, "s": 406, "text": "A simple solution is to match characters one by one. And whenever we see a complete match, we increment count. Below is simple solution based on Naive pattern searching. " }, { "code": null, "e": 581, "s": 577, "text": "C++" }, { "code": null, "e": 586, "s": 581, "text": "Java" }, { "code": null, "e": 594, "s": 586, "text": "Python3" }, { "code": null, "e": 597, "s": 594, "text": "C#" }, { "code": null, "e": 601, "s": 597, "text": "PHP" }, { "code": null, "e": 612, "s": 601, "text": "Javascript" }, { "code": "// Simple C++ program to count occurrences// of pat in txt.#include<bits/stdc++.h>using namespace std; int countFreq(string &pat, string &txt){ int M = pat.length(); int N = txt.length(); int res = 0; /* A loop to slide pat[] one by one */ for (int i = 0; i <= N - M; i++) { /* For current index i, check for pattern match */ int j; for (j = 0; j < M; j++) if (txt[i+j] != pat[j]) break; // if pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) { res++; } } return res;} /* Driver program to test above function */int main(){ string txt = \"dhimanman\"; string pat = \"man\"; cout << countFreq(pat, txt); return 0;}", "e": 1358, "s": 612, "text": null }, { "code": "// Simple Java program to count occurrences// of pat in txt. class GFG { static int countFreq(String pat, String txt) { int M = pat.length(); int N = txt.length(); int res = 0; /* A loop to slide pat[] one by one */ for (int i = 0; i <= N - M; i++) { /* For current index i, check for pattern match */ int j; for (j = 0; j < M; j++) { if (txt.charAt(i + j) != pat.charAt(j)) { break; } } // if pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) { res++; j = 0; } } return res; } /* Driver program to test above function */ static public void main(String[] args) { String txt = \"dhimanman\"; String pat = \"man\"; System.out.println(countFreq(pat, txt)); }} // This code is contributed by 29AjayKumar", "e": 2432, "s": 1358, "text": null }, { "code": "# Simple python program to count# occurrences of pat in txt.def countFreq(pat, txt): M = len(pat) N = len(txt) res = 0 # A loop to slide pat[] one by one for i in range(N - M + 1): # For current index i, check # for pattern match j = 0 while j < M: if (txt[i + j] != pat[j]): break j += 1 if (j == M): res += 1 j = 0 return res # Driver Codeif __name__ == '__main__': txt = \"dhimanman\" pat = \"man\" print(countFreq(pat, txt)) # This code is contributed# by PrinciRaj1992", "e": 3042, "s": 2432, "text": null }, { "code": " // Simple C# program to count occurrences// of pat in txt.using System;public class GFG { static int countFreq(String pat, String txt) { int M = pat.Length; int N = txt.Length; int res = 0; /* A loop to slide pat[] one by one */ for (int i = 0; i <= N - M; i++) { /* For current index i, check for pattern match */ int j; for (j = 0; j < M; j++) { if (txt[i + j] != pat[j]) { break; } } // if pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) { res++; j = 0; } } return res; } /* Driver program to test above function */ static public void Main() { String txt = \"dhimanman\"; String pat = \"man\"; Console.Write(countFreq(pat, txt)); }} // This code is contributed by 29AjayKumar", "e": 4107, "s": 3042, "text": null }, { "code": "<?php// Simple PHP program to count occurrences// of pat in txt. function countFreq($pat, $txt){ $M = strlen($pat); $N = strlen($txt); $res = 0; /* A loop to slide pat[] one by one */ for ($i = 0; $i <= $N - $M; $i++) { /* For current index i, check for pattern match */ for ($j = 0; $j < $M; $j++) if ($txt[$i+$j] != $pat[$j]) break; // if pat[0...M-1] = txt[i, i+1, ...i+M-1] if ($j == $M) { $res++; $j = 0; } } return $res;} // Driver Code$txt = \"dhimanman\";$pat = \"man\";echo countFreq($pat, $txt); // This code is contributed// by Akanksha Rai", "e": 4778, "s": 4107, "text": null }, { "code": "<script> // JavaScript program to count occurrences// of pat in txt.let mod = 100000007; function countFreq(pat, txt){ let M = pat.length; let N = txt.length; let res = 0; // A loop to slide pat[] one by one for(let i = 0; i <= N - M; i++) { // For current index i, check for // pattern match let j; for(j = 0; j < M; j++) { if (txt[i + j] != pat[j]) { break; } } // If pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) { res++; j = 0; } } return res; } // Driver Codelet txt = \"dhimanman\"; let pat = \"man\"; document.write(countFreq(pat, txt)); // This code is contributed by code_hunt </script>", "e": 5647, "s": 4778, "text": null }, { "code": null, "e": 5649, "s": 5647, "text": "2" }, { "code": null, "e": 5675, "s": 5649, "text": "Time Complexity: O(M * N)" }, { "code": null, "e": 5684, "s": 5675, "text": "Chapters" }, { "code": null, "e": 5711, "s": 5684, "text": "descriptions off, selected" }, { "code": null, "e": 5761, "s": 5711, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 5784, "s": 5761, "text": "captions off, selected" }, { "code": null, "e": 5792, "s": 5784, "text": "English" }, { "code": null, "e": 5810, "s": 5792, "text": "default, selected" }, { "code": null, "e": 5834, "s": 5810, "text": "This is a modal window." }, { "code": null, "e": 5903, "s": 5834, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 5925, "s": 5903, "text": "End of dialog window." }, { "code": null, "e": 5973, "s": 5925, "text": "An efficient solution is to use KMP algorithm. " }, { "code": null, "e": 5977, "s": 5973, "text": "C++" }, { "code": null, "e": 5982, "s": 5977, "text": "Java" }, { "code": null, "e": 5990, "s": 5982, "text": "Python3" }, { "code": null, "e": 5993, "s": 5990, "text": "C#" }, { "code": null, "e": 6004, "s": 5993, "text": "Javascript" }, { "code": "// C++ program to count occurrences// of pattern in a text.#include <iostream>using namespace std; void computeLPSArray(string pat, int M, int lps[]){ // Length of the previous longest // prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // The loop calculates lps[i] for // i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not // increment i here } else // if (len == 0) { lps[i] = len; i++; } } }} int KMPSearch(string pat, string txt){ int M = pat.length(); int N = txt.length(); // Create lps[] that will hold the longest // prefix suffix values for pattern int lps[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] int res = 0; int next_i = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { // When we find pattern first time, // we iterate again to check if there // exists more pattern j = lps[j - 1]; res++; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] // characters, they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } return res;} // Driver codeint main(){ string txt = \"geeksforgeeks\"; string pat = \"eeks\"; int ans = KMPSearch(pat, txt); cout << ans; return 0;} // This code is contributed by akhilsaini", "e": 8217, "s": 6004, "text": null }, { "code": "// Java program to count occurrences of pattern// in a text.class KMP_String_Matching{ int KMPSearch(String pat, String txt) { int M = pat.length(); int N = txt.length(); // create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat,M,lps); int i = 0; // index for txt[] int res = 0; int next_i = 0; while (i < N) { if (pat.charAt(j) == txt.charAt(i)) { j++; i++; } if (j == M) { // When we find pattern first time, // we iterate again to check if there // exists more pattern j = lps[j-1]; res++; // We start i to check for more than once // appearance of pattern, we will reset i // to previous start+1 if (lps[j]!=0) i = ++next_i; j = 0; } // mismatch after j matches else if (i < N && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j-1]; else i = i+1; } } return res; } void computeLPSArray(String pat, int M, int lps[]) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len-1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver program to test above function public static void main(String args[]) { String txt = \"geeksforgeeks\"; String pat = \"eeks\"; int ans = new KMP_String_Matching().KMPSearch(pat,txt); System.out.println(ans); }}", "e": 10982, "s": 8217, "text": null }, { "code": "# Python3 program to count occurrences of# pattern in a text.def KMPSearch(pat, txt): M = len(pat) N = len(txt) # Create lps[] that will hold the longest # prefix suffix values for pattern lps = [None] * M j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] # array) computeLPSArray(pat, M, lps) i = 0 # index for txt[] res = 0 next_i = 0 while (i < N): if pat[j] == txt[i]: j = j + 1 i = i + 1 if j == M: # When we find pattern first time, # we iterate again to check if there # exists more pattern j = lps[j - 1] res = res + 1 # We start i to check for more than once # appearance of pattern, we will reset i # to previous start+1 if lps[j] != 0: next_i = next_i + 1 i = next_i j = 0 # Mismatch after j matches elif ((i < N) and (pat[j] != txt[i])): # Do not match lps[0..lps[j-1]] # characters, they will match anyway if (j != 0): j = lps[j - 1] else: i = i + 1 return res def computeLPSArray(pat, M, lps): # Length of the previous longest # prefix suffix len = 0 i = 1 lps[0] = 0 # lps[0] is always 0 # The loop calculates lps[i] for # i = 1 to M-1 while (i < M): if pat[i] == pat[len]: len = len + 1 lps[i] = len i = i + 1 else: # (pat[i] != pat[len]) # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if len != 0: len = lps[len - 1] # Also, note that we do not increment # i here else: # if (len == 0) lps[i] = len i = i + 1 # Driver codeif __name__ == \"__main__\": txt = \"geeksforgeeks\" pat = \"eeks\" ans = KMPSearch(pat, txt) print(ans) # This code is contributed by akhilsaini", "e": 13172, "s": 10982, "text": null }, { "code": "// C# program to count occurrences of pattern// in a text.using System; public class KMP_String_Matching{ int KMPSearch(String pat, String txt) { int M = pat.Length; int N = txt.Length; // create lps[] that will hold the longest // prefix suffix values for pattern int []lps = new int[M]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat,M,lps); int i = 0; // index for txt[] int res = 0; int next_i = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { // When we find pattern first time, // we iterate again to check if there // exists more pattern j = lps[j-1]; res++; // We start i to check for more than once // appearance of pattern, we will reset i // to previous start+1 if (lps[j]!=0) i = ++next_i; j = 0; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j-1]; else i = i+1; } } return res; } void computeLPSArray(String pat, int M, int []lps) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len-1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = len; i++; } } } } // Driver code public static void Main(String []args) { String txt = \"geeksforgeeks\"; String pat = \"eeks\"; int ans = new KMP_String_Matching().KMPSearch(pat,txt); Console.WriteLine(ans); }} // This code is contributed by Princi Singh", "e": 15931, "s": 13172, "text": null }, { "code": "<script> // JavaScript program to count occurrences // of pattern in a text. function computeLPSArray(pat,M,lps) { // Length of the previous longest // prefix suffix let len = 0; let i = 1; lps[0] = 0; // lps[0] is always 0 // The loop calculates lps[i] for // i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not // increment i here } else // if (len == 0) { lps[i] = len; i++; } } } } function KMPSearch(pat,txt) { let M = pat.length; let N = txt.length; // Create lps[] that will hold the longest // prefix suffix values for pattern let lps = new Array(M); lps.fill(0); let j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, M, lps); let i = 0; // index for txt[] let res = 0; let next_i = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { // When we find pattern first time, // we iterate again to check if there // exists more pattern j = lps[j - 1]; res++; // We start i to check for more than once // appearance of pattern, we will reset i // to previous start+1 if (lps[j]!=0) i = ++next_i; j = 0; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] // characters, they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } return res; } // Driver code let txt = \"geeksforgeeks\"; let pat = \"eeks\"; let ans = KMPSearch(pat, txt); document.write(ans); </script>", "e": 18559, "s": 15931, "text": null }, { "code": null, "e": 18561, "s": 18559, "text": "2" }, { "code": null, "e": 18588, "s": 18561, "text": "Time Complexity : O(M + N)" }, { "code": null, "e": 19482, "s": 18588, "text": "KMP Algorithm | Searching for Patterns | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersKMP Algorithm | Searching for Patterns | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:25•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=cH-5KcgUcOE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 19494, "s": 19482, "text": "29AjayKumar" }, { "code": null, "e": 19508, "s": 19494, "text": "princiraj1992" }, { "code": null, "e": 19521, "s": 19508, "text": "Akanksha_Rai" }, { "code": null, "e": 19541, "s": 19521, "text": "ROHITKISHORTRIPATHI" }, { "code": null, "e": 19554, "s": 19541, "text": "princi singh" }, { "code": null, "e": 19566, "s": 19554, "text": "vinaylingam" }, { "code": null, "e": 19577, "s": 19566, "text": "akhilsaini" }, { "code": null, "e": 19587, "s": 19577, "text": "surajjain" }, { "code": null, "e": 19597, "s": 19587, "text": "code_hunt" }, { "code": null, "e": 19609, "s": 19597, "text": "kavania2002" }, { "code": null, "e": 19628, "s": 19609, "text": "vaibhavrabadiya117" }, { "code": null, "e": 19638, "s": 19628, "text": "zaid47304" }, { "code": null, "e": 19657, "s": 19638, "text": "frequency-counting" }, { "code": null, "e": 19675, "s": 19657, "text": "Pattern Searching" }, { "code": null, "e": 19683, "s": 19675, "text": "Strings" }, { "code": null, "e": 19691, "s": 19683, "text": "Strings" }, { "code": null, "e": 19709, "s": 19691, "text": "Pattern Searching" }, { "code": null, "e": 19807, "s": 19709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19864, "s": 19807, "text": "Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 19905, "s": 19864, "text": "Search a Word in a 2D Grid of characters" }, { "code": null, "e": 19976, "s": 19905, "text": "Split the binary string into substrings with equal number of 0s and 1s" }, { "code": null, "e": 20038, "s": 19976, "text": "String matching where one string contains wildcard characters" }, { "code": null, "e": 20087, "s": 20038, "text": "Find all occurrences of a given word in a matrix" }, { "code": null, "e": 20133, "s": 20087, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 20158, "s": 20133, "text": "Reverse a string in Java" }, { "code": null, "e": 20218, "s": 20158, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 20233, "s": 20218, "text": "C++ Data Types" } ]
Simple Chat Room using Python
In this article we will see how to make a server and client chat room system using Socket Programming with Python. The sockets are the endpoints of any communication channel. These are used to connect the server and client. Sockets are Bi-Directional. In this area, we will setup sockets for each end and setup the chatroom system among different clients through the server. The server side has some ports to connect with client sockets. When a client tries to connect with the same port, then the connection will be established for the chat room. There are basically two parts. The server side and the client side. When the server side script is running, it waits for any active connection request. When one connection is established, it can communicate with it. In this case we are using localhost. If machines are connected via LAN, then we can use IP addresses to communicate. The server will display its IP, and ask for a name for the server. From the client side, we have to mention a name, and also the IP address of the server to connect. import time, socket, sys print('Setup Server...') time.sleep(1) #Get the hostname, IP Address from socket and set Port soc = socket.socket() host_name = socket.gethostname() ip = socket.gethostbyname(host_name) port = 1234 soc.bind((host_name, port)) print(host_name, '({})'.format(ip)) name = input('Enter name: ') soc.listen(1) #Try to locate using socket print('Waiting for incoming connections...') connection, addr = soc.accept() print("Received connection from ", addr[0], "(", addr[1], ")\n") print('Connection Established. Connected From: {}, ({})'.format(addr[0], addr[0])) #get a connection from client side client_name = connection.recv(1024) client_name = client_name.decode() print(client_name + ' has connected.') print('Press [bye] to leave the chat room') connection.send(name.encode()) whileTrue: message = input('Me > ') if message == '[bye]': message = 'Good Night...' connection.send(message.encode()) print("\n") break connection.send(message.encode()) message = connection.recv(1024) message = message.decode() print(client_name, '>', message) import time, socket, sys print('Client Server...') time.sleep(1) #Get the hostname, IP Address from socket and set Port soc = socket.socket() shost = socket.gethostname() ip = socket.gethostbyname(shost) #get information to connect with the server print(shost, '({})'.format(ip)) server_host = input('Enter server\'s IP address:') name = input('Enter Client\'s name: ') port = 1234 print('Trying to connect to the server: {}, ({})'.format(server_host, port)) time.sleep(1) soc.connect((server_host, port)) print("Connected...\n") soc.send(name.encode()) server_name = soc.recv(1024) server_name = server_name.decode() print('{} has joined...'.format(server_name)) print('Enter [bye] to exit.') whileTrue: message = soc.recv(1024) message = message.decode() print(server_name, ">", message) message = input(str("Me > ")) if message == "[bye]": message = "Leaving the Chat room" soc.send(message.encode()) print("\n") break soc.send(message.encode())
[ { "code": null, "e": 1177, "s": 1062, "text": "In this article we will see how to make a server and client chat room system using Socket Programming with Python." }, { "code": null, "e": 1610, "s": 1177, "text": "The sockets are the endpoints of any communication channel. These are used to connect the server and client. Sockets are Bi-Directional. In this area, we will setup sockets for each end and setup the chatroom system among different clients through the server. The server side has some ports to connect with client sockets. When a client tries to connect with the same port, then the connection will be established for the chat room." }, { "code": null, "e": 1826, "s": 1610, "text": "There are basically two parts. The server side and the client side. When the server side script is running, it waits for any active connection request. When one connection is established, it can communicate with it." }, { "code": null, "e": 2109, "s": 1826, "text": "In this case we are using localhost. If machines are connected via LAN, then we can use IP addresses to communicate. The server will display its IP, and ask for a name for the server. From the client side, we have to mention a name, and also the IP address of the server to connect." }, { "code": null, "e": 3175, "s": 2109, "text": "import time, socket, sys\nprint('Setup Server...')\ntime.sleep(1)\n#Get the hostname, IP Address from socket and set Port\nsoc = socket.socket()\nhost_name = socket.gethostname()\nip = socket.gethostbyname(host_name)\nport = 1234\nsoc.bind((host_name, port))\nprint(host_name, '({})'.format(ip))\nname = input('Enter name: ')\nsoc.listen(1) #Try to locate using socket\nprint('Waiting for incoming connections...')\nconnection, addr = soc.accept()\nprint(\"Received connection from \", addr[0], \"(\", addr[1], \")\\n\")\nprint('Connection Established. Connected From: {}, ({})'.format(addr[0], addr[0]))\n#get a connection from client side\nclient_name = connection.recv(1024)\nclient_name = client_name.decode()\nprint(client_name + ' has connected.')\nprint('Press [bye] to leave the chat room')\nconnection.send(name.encode())\nwhileTrue:\nmessage = input('Me > ')\nif message == '[bye]':\nmessage = 'Good Night...'\nconnection.send(message.encode())\nprint(\"\\n\")\nbreak\nconnection.send(message.encode())\nmessage = connection.recv(1024)\nmessage = message.decode()\nprint(client_name, '>', message)" }, { "code": null, "e": 4124, "s": 3175, "text": "import time, socket, sys\nprint('Client Server...')\ntime.sleep(1)\n#Get the hostname, IP Address from socket and set Port\nsoc = socket.socket()\nshost = socket.gethostname()\nip = socket.gethostbyname(shost)\n#get information to connect with the server\nprint(shost, '({})'.format(ip))\nserver_host = input('Enter server\\'s IP address:')\nname = input('Enter Client\\'s name: ')\nport = 1234\nprint('Trying to connect to the server: {}, ({})'.format(server_host, port))\ntime.sleep(1)\nsoc.connect((server_host, port))\nprint(\"Connected...\\n\")\nsoc.send(name.encode())\nserver_name = soc.recv(1024)\nserver_name = server_name.decode()\nprint('{} has joined...'.format(server_name))\nprint('Enter [bye] to exit.')\nwhileTrue:\nmessage = soc.recv(1024)\nmessage = message.decode()\nprint(server_name, \">\", message)\nmessage = input(str(\"Me > \"))\nif message == \"[bye]\":\nmessage = \"Leaving the Chat room\"\nsoc.send(message.encode())\nprint(\"\\n\")\nbreak\nsoc.send(message.encode())" } ]
Sort an array of strings according to string lengths in C++
Here we will see how to sort a list of strings based on their lengths. So if a string has less number of characters, then that will be placed first, then other longer strings will be placed. Suppose the strings are str_list = {“Hello”, “ABC”, “Programming”, “Length”, “Population”} after sorting, they will be − str_list = {“ABC”, “Hello”, “Length”, “Population”, “Programming”} Here we will create our own comparison logic to sort them. That comparison logic will be used in the sort function in C++ STL. compare(str1, str2): Begin if length of str1 < length of str2, then return 1 return 0 End Live Demo #include<iostream> #include<algorithm> using namespace std; int compare(string str1, string str2){ if(str1.length() < str2.length()) return 1; return 0; } main(){ string str_list[] = {"Hello", "ABC", "Programming", "Length", "Population"}; int n = 5; sort(str_list, str_list + n, compare); for(int i = 0; i<n; i++){ cout << str_list[i] << " "; } } ABC Hello Length Population Programming
[ { "code": null, "e": 1277, "s": 1062, "text": "Here we will see how to sort a list of strings based on their lengths. So if a string has less number of characters, then that will be placed first, then other longer strings will be placed. Suppose the strings are" }, { "code": null, "e": 1344, "s": 1277, "text": "str_list = {“Hello”, “ABC”, “Programming”, “Length”, “Population”}" }, { "code": null, "e": 1374, "s": 1344, "text": "after sorting, they will be −" }, { "code": null, "e": 1441, "s": 1374, "text": "str_list = {“ABC”, “Hello”, “Length”, “Population”, “Programming”}" }, { "code": null, "e": 1568, "s": 1441, "text": "Here we will create our own comparison logic to sort them. That comparison logic will be used in the sort function in C++ STL." }, { "code": null, "e": 1670, "s": 1568, "text": "compare(str1, str2):\nBegin\n if length of str1 < length of str2, then\n return 1\n return 0\nEnd" }, { "code": null, "e": 1681, "s": 1670, "text": " Live Demo" }, { "code": null, "e": 2059, "s": 1681, "text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\nint compare(string str1, string str2){\n if(str1.length() < str2.length())\n return 1;\n return 0;\n}\nmain(){\n string str_list[] = {\"Hello\", \"ABC\", \"Programming\", \"Length\", \"Population\"};\n int n = 5;\n sort(str_list, str_list + n, compare);\n for(int i = 0; i<n; i++){\n cout << str_list[i] << \" \";\n }\n}" }, { "code": null, "e": 2099, "s": 2059, "text": "ABC Hello Length Population Programming" } ]
How can I get onclick event on webview in Android?
This example demonstrates how do I get onClick event on webView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.MotionEvent; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnTouchListener, Handler.Callback { private static final int CLICK_ON_WEBVIEW = 1; private static final int CLICK_ON_URL = 2; private final Handler handler = new Handler(this); WebView webView; WebViewClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = findViewById(R.id.webView); webView.setOnTouchListener(this); client = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { handler.sendEmptyMessage(CLICK_ON_URL); return false; } }; webView.setWebViewClient(client); webView.setVerticalScrollBarEnabled(false); webView.loadUrl("http://www.google.com"); } @Override public boolean handleMessage(Message msg) { if (msg.what == CLICK_ON_URL) { handler.removeMessages(CLICK_ON_WEBVIEW); return true; } if (msg.what == CLICK_ON_WEBVIEW) { Toast.makeText(this, "WebView clicked", Toast.LENGTH_SHORT).show(); return true; } return false; } @Override public boolean onTouch(View v, MotionEvent event) { if (v.getId() == R.id.webView && event.getAction() == MotionEvent.ACTION_DOWN) { handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 500); } return false; } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.INTERNET"/> <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 the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
[ { "code": null, "e": 1138, "s": 1062, "text": "This example demonstrates how do I get onClick event on webView in android." }, { "code": null, "e": 1267, "s": 1138, "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": 1332, "s": 1267, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1805, "s": 1332, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n<WebView\n android:id=\"@+id/webView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1862, "s": 1805, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3670, "s": 1862, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity implements View.OnTouchListener,\nHandler.Callback {\n private static final int CLICK_ON_WEBVIEW = 1;\n private static final int CLICK_ON_URL = 2;\n private final Handler handler = new Handler(this);\n WebView webView;\n WebViewClient client;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n webView = findViewById(R.id.webView);\n webView.setOnTouchListener(this);\n client = new WebViewClient() {\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n handler.sendEmptyMessage(CLICK_ON_URL);\n return false;\n }\n };\n webView.setWebViewClient(client);\n webView.setVerticalScrollBarEnabled(false);\n webView.loadUrl(\"http://www.google.com\");\n }\n @Override\n public boolean handleMessage(Message msg) {\n if (msg.what == CLICK_ON_URL) {\n handler.removeMessages(CLICK_ON_WEBVIEW);\n return true;\n }\n if (msg.what == CLICK_ON_WEBVIEW) {\n Toast.makeText(this, \"WebView clicked\", Toast.LENGTH_SHORT).show();\n return true;\n }\n return false;\n }\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if (v.getId() == R.id.webView && event.getAction() == MotionEvent.ACTION_DOWN) {\n handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 500);\n }\n return false;\n }\n}\n" }, { "code": null, "e": 3725, "s": 3670, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4463, "s": 3725, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\"/>\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": 4818, "s": 4463, "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 the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" } ]
Decorators in Python: Fundamentals for Data Scientists | by Erdem Isbilen | Towards Data Science
Decorators in Python is used to extend the functionality of a callable object without modifying its structure. Basically, decorator functions wrap another function to enhance or modify its behaviour. This post will introduce you to the basics of decorators in Python. Let’s write a Python3 code that contains examples of decorator implementations: def decorator_func_logger(target_func): def wrapper_func(): print("Before calling", target_func.__name__) target_func() print("After calling", target_func.__name__) return wrapper_funcdef target(): print('Python is in the decorated target function')dec_func = decorator_func_logger(target)dec_func()Output:air-MacBook-Air:$ python DecoratorsExample.py('Before calling', 'target')Python is in the decorated target function('After calling', 'target') Above decorator structure helps us to display some notes on the console before and after a target function is called. Here are the simple steps for defining a decorator; First, we should define a callable object such as a decorator function which also contains a wrapper function inside. Decorator functions should take a target function as a parameter. And it should return wrapper function which extends the target function passed as an argument. Wrapper function should contain a target function call together with the code extending the behaviour of target function. def decorator_func_logger(target_func): def wrapper_func(): print("Before calling", target_func.__name__) target_func() print("After calling", target_func.__name__) return wrapper_func@decorator_func_loggerdef target(): print('Python is in the decorated target function')target()Output:air-MacBook-Air:$ python DecoratorsExample.py('Before calling', 'target')Python is in the decorated target function('After calling', 'target') With the help of the syntactic sugar provided by Python, we can simplify the decorator definition as shown above. Note that @decorator_func_logger is added just before the target function we would like to decorate. We can then directly call the target function. There is no need to explicitly assign the decorator, as we did in the first example. import timedef decorator_func_logger(target_func): def wrapper_func(*args, **kwargs): print("Before calling", target_func.__name__) target_func(*args, **kwargs) print("After calling", target_func.__name__) return wrapper_funcdef decorator_func_timeit(target_func): def wrapper_func(*args, **kwargs): ts = time.time() target_func(*args, **kwargs) te = time.time() print (target_func.__name__, (te - ts) * 1000) return wrapper_func@decorator_func_logger@decorator_func_timeitdef target(loop): count = 0 print('Python is in the decorated target function') for number in range(loop): count += numbertarget(100)target(3000)Output:air-MacBook-Air:$ python DecoratorsExample.py('Before calling', 'wrapper_func')Python is in the decorated target function('target', 0.015974044799804688)('After calling', 'wrapper_func')('Before calling', 'wrapper_func')Python is in the decorated target function('target', 0.47397613525390625)('After calling', 'wrapper_func') You can easily decorate a target function with multiple decorators, by adding several decorators before the target function with using ‘@’ syntax. The order that the decorators are being executed will be the same as how they are listed before target function. Note that we have a parameter, loop, in our target function. This is no issue as long as the same parameter is used for the wrapper function. To make sure that the decorator is flexible to take an arbitrary number of parameters, (*args, **kwargs) parameters are used for the wrapper function. Decorators define reusable code blocks that you can apply to a callable object (functions, methods, classes, objects) to modify or extend its behaviour without modifying the object itself. Consider that you have many functions in your script performing many different tasks and you need to add specific behaviour to all of your functions. In such a case, it is not a good solution to copy the same code block into your functions to have the required functionality. You can simply decorate your functions instead. In this post, I explained the basics of decorators in Python. The code in this post is available in my GitHub repository. I hope you found this post useful. Thank you for reading!
[ { "code": null, "e": 372, "s": 172, "text": "Decorators in Python is used to extend the functionality of a callable object without modifying its structure. Basically, decorator functions wrap another function to enhance or modify its behaviour." }, { "code": null, "e": 440, "s": 372, "text": "This post will introduce you to the basics of decorators in Python." }, { "code": null, "e": 520, "s": 440, "text": "Let’s write a Python3 code that contains examples of decorator implementations:" }, { "code": null, "e": 976, "s": 520, "text": "def decorator_func_logger(target_func): def wrapper_func(): print(\"Before calling\", target_func.__name__) target_func() print(\"After calling\", target_func.__name__) return wrapper_funcdef target(): print('Python is in the decorated target function')dec_func = decorator_func_logger(target)dec_func()Output:air-MacBook-Air:$ python DecoratorsExample.py('Before calling', 'target')Python is in the decorated target function('After calling', 'target')" }, { "code": null, "e": 1094, "s": 976, "text": "Above decorator structure helps us to display some notes on the console before and after a target function is called." }, { "code": null, "e": 1146, "s": 1094, "text": "Here are the simple steps for defining a decorator;" }, { "code": null, "e": 1264, "s": 1146, "text": "First, we should define a callable object such as a decorator function which also contains a wrapper function inside." }, { "code": null, "e": 1330, "s": 1264, "text": "Decorator functions should take a target function as a parameter." }, { "code": null, "e": 1425, "s": 1330, "text": "And it should return wrapper function which extends the target function passed as an argument." }, { "code": null, "e": 1547, "s": 1425, "text": "Wrapper function should contain a target function call together with the code extending the behaviour of target function." }, { "code": null, "e": 1983, "s": 1547, "text": "def decorator_func_logger(target_func): def wrapper_func(): print(\"Before calling\", target_func.__name__) target_func() print(\"After calling\", target_func.__name__) return wrapper_func@decorator_func_loggerdef target(): print('Python is in the decorated target function')target()Output:air-MacBook-Air:$ python DecoratorsExample.py('Before calling', 'target')Python is in the decorated target function('After calling', 'target')" }, { "code": null, "e": 2097, "s": 1983, "text": "With the help of the syntactic sugar provided by Python, we can simplify the decorator definition as shown above." }, { "code": null, "e": 2330, "s": 2097, "text": "Note that @decorator_func_logger is added just before the target function we would like to decorate. We can then directly call the target function. There is no need to explicitly assign the decorator, as we did in the first example." }, { "code": null, "e": 3290, "s": 2330, "text": "import timedef decorator_func_logger(target_func): def wrapper_func(*args, **kwargs): print(\"Before calling\", target_func.__name__) target_func(*args, **kwargs) print(\"After calling\", target_func.__name__) return wrapper_funcdef decorator_func_timeit(target_func): def wrapper_func(*args, **kwargs): ts = time.time() target_func(*args, **kwargs) te = time.time() print (target_func.__name__, (te - ts) * 1000) return wrapper_func@decorator_func_logger@decorator_func_timeitdef target(loop): count = 0 print('Python is in the decorated target function') for number in range(loop): count += numbertarget(100)target(3000)Output:air-MacBook-Air:$ python DecoratorsExample.py('Before calling', 'wrapper_func')Python is in the decorated target function('target', 0.015974044799804688)('After calling', 'wrapper_func')('Before calling', 'wrapper_func')Python is in the decorated target function('target', 0.47397613525390625)('After calling', 'wrapper_func')" }, { "code": null, "e": 3550, "s": 3290, "text": "You can easily decorate a target function with multiple decorators, by adding several decorators before the target function with using ‘@’ syntax. The order that the decorators are being executed will be the same as how they are listed before target function." }, { "code": null, "e": 3843, "s": 3550, "text": "Note that we have a parameter, loop, in our target function. This is no issue as long as the same parameter is used for the wrapper function. To make sure that the decorator is flexible to take an arbitrary number of parameters, (*args, **kwargs) parameters are used for the wrapper function." }, { "code": null, "e": 4032, "s": 3843, "text": "Decorators define reusable code blocks that you can apply to a callable object (functions, methods, classes, objects) to modify or extend its behaviour without modifying the object itself." }, { "code": null, "e": 4356, "s": 4032, "text": "Consider that you have many functions in your script performing many different tasks and you need to add specific behaviour to all of your functions. In such a case, it is not a good solution to copy the same code block into your functions to have the required functionality. You can simply decorate your functions instead." }, { "code": null, "e": 4418, "s": 4356, "text": "In this post, I explained the basics of decorators in Python." }, { "code": null, "e": 4478, "s": 4418, "text": "The code in this post is available in my GitHub repository." }, { "code": null, "e": 4513, "s": 4478, "text": "I hope you found this post useful." } ]
CSS - Fade Out Effect
The image come or cause to come gradually into or out of view, or to merge into another shot. @keyframes fadeOut { 0% {opacity: 1;} 100% {opacity: 0;} } Transform − Transform applies to 2d and 3d transformation to an element. Transform − Transform applies to 2d and 3d transformation to an element. Opacity − Opacity applies to an element to make translucence. Opacity − Opacity applies to an element to make translucence. <html> <head> <style> .animated { background-image: url(/css/images/logo.png); background-repeat: no-repeat; background-position: left top; padding-top:95px; margin-bottom:60px; -webkit-animation-duration: 10s;animation-duration: 10s; -webkit-animation-fill-mode: both;animation-fill-mode: both; } @-webkit-keyframes fadeOut { 0% {opacity: 1;} 100% {opacity: 0;} } @keyframes fadeOut { 0% {opacity: 1;} 100% {opacity: 0;} } .fadeOut { -webkit-animation-name: fadeOut; animation-name: fadeOut; } </style> </head> <body> <div id = "animated-example" class = "animated fadeOut"></div> <button onclick = "myFunction()">Reload page</button> <script> function myFunction() { location.reload(); } </script> </body> </html> It will produce the following result − Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Selected Reading UPSC IAS Exams Notes Developer's Best Practices Questions and Answers Effective Resume Writing HR Interview Questions Computer Glossary Who is Who Print Add Notes Bookmark this page
[ { "code": null, "e": 2720, "s": 2626, "text": "The image come or cause to come gradually into or out of view, or to merge into another shot." }, { "code": null, "e": 2787, "s": 2720, "text": "@keyframes fadeOut {\n 0% {opacity: 1;}\n 100% {opacity: 0;} \n} " }, { "code": null, "e": 2860, "s": 2787, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 2933, "s": 2860, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 2995, "s": 2933, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 3057, "s": 2995, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 4128, "s": 3057, "text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;animation-duration: 10s;\n -webkit-animation-fill-mode: both;animation-fill-mode: both;\n }\n \n @-webkit-keyframes fadeOut {\n 0% {opacity: 1;}\n 100% {opacity: 0;}\n }\n \n @keyframes fadeOut {\n 0% {opacity: 1;}\n 100% {opacity: 0;}\n }\n \n .fadeOut {\n -webkit-animation-name: fadeOut;\n animation-name: fadeOut;\n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated fadeOut\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 4167, "s": 4128, "text": "It will produce the following result −" }, { "code": null, "e": 4814, "s": 4167, "text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n" }, { "code": null, "e": 4834, "s": 4814, "text": " Academic Tutorials" }, { "code": null, "e": 4857, "s": 4834, "text": " Big Data & Analytics " }, { "code": null, "e": 4880, "s": 4857, "text": " Computer Programming " }, { "code": null, "e": 4899, "s": 4880, "text": " Computer Science " }, { "code": null, "e": 4911, "s": 4899, "text": " Databases " }, { "code": null, "e": 4920, "s": 4911, "text": " DevOps " }, { "code": null, "e": 4940, "s": 4920, "text": " Digital Marketing " }, { "code": null, "e": 4964, "s": 4940, "text": " Engineering Tutorials " }, { "code": null, "e": 4981, "s": 4964, "text": " Exams Syllabus " }, { "code": null, "e": 5000, "s": 4981, "text": " Famous Monuments " }, { "code": null, "e": 5022, "s": 5000, "text": " GATE Exams Tutorials" }, { "code": null, "e": 5044, "s": 5022, "text": " Latest Technologies " }, { "code": null, "e": 5063, "s": 5044, "text": " Machine Learning " }, { "code": null, "e": 5087, "s": 5063, "text": " Mainframe Development " }, { "code": null, "e": 5110, "s": 5087, "text": " Management Tutorials " }, { "code": null, "e": 5133, "s": 5110, "text": " Mathematics Tutorials" }, { "code": null, "e": 5158, "s": 5133, "text": " Microsoft Technologies " }, { "code": null, "e": 5175, "s": 5158, "text": " Misc tutorials " }, { "code": null, "e": 5196, "s": 5175, "text": " Mobile Development " }, { "code": null, "e": 5216, "s": 5196, "text": " Java Technologies " }, { "code": null, "e": 5238, "s": 5216, "text": " Python Technologies " }, { "code": null, "e": 5254, "s": 5238, "text": " SAP Tutorials " }, { "code": null, "e": 5275, "s": 5254, "text": "Programming Scripts " }, { "code": null, "e": 5294, "s": 5275, "text": " Selected Reading " }, { "code": null, "e": 5313, "s": 5294, "text": " Software Quality " }, { "code": null, "e": 5327, "s": 5313, "text": " Soft Skills " }, { "code": null, "e": 5347, "s": 5327, "text": " Telecom Tutorials " }, { "code": null, "e": 5364, "s": 5347, "text": " UPSC IAS Exams " }, { "code": null, "e": 5382, "s": 5364, "text": " Web Development " }, { "code": null, "e": 5401, "s": 5382, "text": " Sports Tutorials " }, { "code": null, "e": 5420, "s": 5401, "text": " XML Technologies " }, { "code": null, "e": 5436, "s": 5420, "text": " Multi-Language" }, { "code": null, "e": 5457, "s": 5436, "text": " Interview Questions" }, { "code": null, "e": 5474, "s": 5457, "text": "Selected Reading" }, { "code": null, "e": 5495, "s": 5474, "text": "UPSC IAS Exams Notes" }, { "code": null, "e": 5522, "s": 5495, "text": "Developer's Best Practices" }, { "code": null, "e": 5544, "s": 5522, "text": "Questions and Answers" }, { "code": null, "e": 5569, "s": 5544, "text": "Effective Resume Writing" }, { "code": null, "e": 5592, "s": 5569, "text": "HR Interview Questions" }, { "code": null, "e": 5610, "s": 5592, "text": "Computer Glossary" }, { "code": null, "e": 5621, "s": 5610, "text": "Who is Who" }, { "code": null, "e": 5628, "s": 5621, "text": " Print" }, { "code": null, "e": 5639, "s": 5628, "text": " Add Notes" } ]
Debugging Python code using breakpoint() and pdb - GeeksforGeeks
23 Feb, 2019 While developing an application or exploring some features of a language, one might need to debug the code anytime. Therefore, having an idea of debugging the code is quite necessary. Let’s see some basics of debugging using built-in function breakpoint() and pdb module. We know that debugger plays an important role when we want to find a bug in a particular line of code. Here, Python comes with the latest built-in function breakpoint which do the same thing as pdb.set_trace() in Python 3.6 and below versions. Debugger finds the bug in the code line by line where we add the breakpoint, if a bug is found then program stops temporarily then you can remove the error and start to execute the code again. Syntax: 1) breakpoint() # in Python 3.7 2) import pdb; pdb.set_trace() # in Python 3.6 and below Method #1 : Using breakpoint() functionIn this method, we simply introduce the breakpoint where you have doubt or somewhere you want to check for bugs or errors. def debugger(a, b): breakpoint() result = a / b return result print(debugger(5, 0)) Output : In order to run the debugger just type c and press enter. Commands for debugging : c -> continue execution q -> quit the debugger/execution n -> step to next line within the same function s -> step to next line in this function or a called function Method #2 : Using pdb moduleAs the same suggests, PDB means Python debugger. To use the PDB in the program we have to use one of its method named set_trace(). Although this will result the same but this the another way to introduce the debugger in python version 3.6 and below. def debugger(a, b): import pdb; pdb.set_trace() result = a / b return result print(debugger(5, 0)) Output : In order to run the debugger just type c and press enter. Example : def debugger(a): import pdb; pdb.set_trace() result = [a[element] for element in range(0, len(a)+5)] return result print(debugger([1, 2, 3])) Output : Python-Miscellaneous Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python How To Convert Python Dictionary To JSON? sum() function in Python
[ { "code": null, "e": 24422, "s": 24394, "text": "\n23 Feb, 2019" }, { "code": null, "e": 24694, "s": 24422, "text": "While developing an application or exploring some features of a language, one might need to debug the code anytime. Therefore, having an idea of debugging the code is quite necessary. Let’s see some basics of debugging using built-in function breakpoint() and pdb module." }, { "code": null, "e": 24938, "s": 24694, "text": "We know that debugger plays an important role when we want to find a bug in a particular line of code. Here, Python comes with the latest built-in function breakpoint which do the same thing as pdb.set_trace() in Python 3.6 and below versions." }, { "code": null, "e": 25131, "s": 24938, "text": "Debugger finds the bug in the code line by line where we add the breakpoint, if a bug is found then program stops temporarily then you can remove the error and start to execute the code again." }, { "code": null, "e": 25139, "s": 25131, "text": "Syntax:" }, { "code": null, "e": 25251, "s": 25139, "text": "1) breakpoint() # in Python 3.7 \n \n2) import pdb; pdb.set_trace() # in Python 3.6 and below\n" }, { "code": null, "e": 25414, "s": 25251, "text": " Method #1 : Using breakpoint() functionIn this method, we simply introduce the breakpoint where you have doubt or somewhere you want to check for bugs or errors." }, { "code": "def debugger(a, b): breakpoint() result = a / b return result print(debugger(5, 0))", "e": 25508, "s": 25414, "text": null }, { "code": null, "e": 25517, "s": 25508, "text": "Output :" }, { "code": null, "e": 25576, "s": 25517, "text": "In order to run the debugger just type c and press enter. " }, { "code": null, "e": 25601, "s": 25576, "text": "Commands for debugging :" }, { "code": null, "e": 25768, "s": 25601, "text": "c -> continue execution\nq -> quit the debugger/execution\nn -> step to next line within the same function\ns -> step to next line in this function or a called function\n" }, { "code": null, "e": 26048, "s": 25770, "text": "Method #2 : Using pdb moduleAs the same suggests, PDB means Python debugger. To use the PDB in the program we have to use one of its method named set_trace(). Although this will result the same but this the another way to introduce the debugger in python version 3.6 and below." }, { "code": "def debugger(a, b): import pdb; pdb.set_trace() result = a / b return result print(debugger(5, 0))", "e": 26157, "s": 26048, "text": null }, { "code": null, "e": 26166, "s": 26157, "text": "Output :" }, { "code": null, "e": 26224, "s": 26166, "text": "In order to run the debugger just type c and press enter." }, { "code": null, "e": 26234, "s": 26224, "text": "Example :" }, { "code": "def debugger(a): import pdb; pdb.set_trace() result = [a[element] for element in range(0, len(a)+5)] return result print(debugger([1, 2, 3]))", "e": 26386, "s": 26234, "text": null }, { "code": null, "e": 26395, "s": 26386, "text": "Output :" }, { "code": null, "e": 26416, "s": 26395, "text": "Python-Miscellaneous" }, { "code": null, "e": 26423, "s": 26416, "text": "Python" }, { "code": null, "e": 26521, "s": 26423, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26539, "s": 26521, "text": "Python Dictionary" }, { "code": null, "e": 26574, "s": 26539, "text": "Read a file line by line in Python" }, { "code": null, "e": 26606, "s": 26574, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26648, "s": 26606, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26674, "s": 26648, "text": "Python String | replace()" }, { "code": null, "e": 26711, "s": 26674, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26755, "s": 26711, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26784, "s": 26755, "text": "*args and **kwargs in Python" }, { "code": null, "e": 26826, "s": 26784, "text": "How To Convert Python Dictionary To JSON?" } ]
Memory leaks in Java
In Java, garbage collection (the work of destructor) is done automatically using garbage collection. But what if there are objects that have references to them in the code? It can’t be de-allocated, i.e their memory can’t be cleared. If such a situation occurs again and again, and the created or referred objects are not used at all, they become useless. This is what is known as a memory leak. If the memory limit is exceeded, the program gets terminated by throwing an error, i.e ‘OutOfMemoryError’. This is the reason why it is always suggested to remove all references to an object so that Java Garbage collector can automatically destroy it. Below is an example that illustrates how the compiler runs out of space when too much memory is trying to be used − Live Demo import java.util.Vector; public class Demo{ public static void main(String[] args){ Vector my_v1 = new Vector(314567); Vector my_v2 = new Vector(784324678); System.out.println("This is the last line to be printed"); } } Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.base/java.util.Vector.<init>(Vector.java:142) at java.base/java.util.Vector.<init>(Vector.java:155) at Demo.main(Demo.java:7) A class named Demo contains the main function where two vector objects have been created by assigning them too large of a space. The last print line is just written to check if the compiler reaches that line. In reality, it doesn’t, since the space occupied by these vectors is huge and so much memory can’t be allocated, resulting in an error.
[ { "code": null, "e": 1458, "s": 1062, "text": "In Java, garbage collection (the work of destructor) is done automatically using garbage collection. But what if there are objects that have references to them in the code? It can’t be de-allocated, i.e their memory can’t be cleared. If such a situation occurs again and again, and the created or referred objects are not used at all, they become useless. This is what is known as a memory leak." }, { "code": null, "e": 1710, "s": 1458, "text": "If the memory limit is exceeded, the program gets terminated by throwing an error, i.e ‘OutOfMemoryError’. This is the reason why it is always suggested to remove all references to an object so that Java Garbage collector can automatically destroy it." }, { "code": null, "e": 1826, "s": 1710, "text": "Below is an example that illustrates how the compiler runs out of space when too much memory is trying to be used −" }, { "code": null, "e": 1837, "s": 1826, "text": " Live Demo" }, { "code": null, "e": 2081, "s": 1837, "text": "import java.util.Vector;\npublic class Demo{\n public static void main(String[] args){\n Vector my_v1 = new Vector(314567);\n Vector my_v2 = new Vector(784324678);\n System.out.println(\"This is the last line to be printed\");\n }\n}" }, { "code": null, "e": 2286, "s": 2081, "text": "Exception in thread \"main\" java.lang.OutOfMemoryError: Java heap space\nat java.base/java.util.Vector.<init>(Vector.java:142)\nat java.base/java.util.Vector.<init>(Vector.java:155)\nat Demo.main(Demo.java:7)" }, { "code": null, "e": 2631, "s": 2286, "text": "A class named Demo contains the main function where two vector objects have been created by assigning them too large of a space. The last print line is just written to check if the compiler reaches that line. In reality, it doesn’t, since the space occupied by these vectors is huge and so much memory can’t be allocated, resulting in an error." } ]
Print multiples of Unit Digit of Given Number in C Program
Input number N and fetch the unit digit of a given number and display the multiples of that number. Input − N=326 Output − unit digit is 6 and its multiples are 2 and 3 Note − Unit digit of any number can be fetched by calculating the %10 with that number For example − if your’re given with a number N and you need to find its unit digit that you can use N%10 it will return you unit digit of number N START Step 1 -> Declare start variables num, num2 and i Step 2 -> input number num Step 3 -> store num%10 in num2 to fetch unit digit Step 4 -> print num2 Step 5 -> Loop For i=2 and i<=num2/2 and ++i IF num2%i=0\ Print i End IF Step 6 -> End For Loop STOP #include<stdio.h> int main() { int num,num2,i; printf("\nenter a number"); scanf("%d" , &num); num2=num%10; //storing unit digit in num2 printf("\n unit digit of %d is: %d",num,num2); for(i=2;i<=num2/2;++i) { //loop till half of unit digit if(num2%i==0) { //calculate multiples printf("\n multiple of %d is : %d ",num2,i); } } return 0; } If we run above program then it will generate following output enter a number329 unit digit of 329 is: 9 multiple of 9 is : 3
[ { "code": null, "e": 1162, "s": 1062, "text": "Input number N and fetch the unit digit of a given number and display the multiples of that number." }, { "code": null, "e": 1176, "s": 1162, "text": "Input − N=326" }, { "code": null, "e": 1231, "s": 1176, "text": "Output − unit digit is 6 and its multiples are 2 and 3" }, { "code": null, "e": 1318, "s": 1231, "text": "Note − Unit digit of any number can be fetched by calculating the %10 with that number" }, { "code": null, "e": 1406, "s": 1318, "text": "For example − if your’re given with a number N and you need to find its unit digit that" }, { "code": null, "e": 1465, "s": 1406, "text": "you can use N%10 it will return you unit digit of number N" }, { "code": null, "e": 1733, "s": 1465, "text": "START\nStep 1 -> Declare start variables num, num2 and i\nStep 2 -> input number num\nStep 3 -> store num%10 in num2 to fetch unit digit\nStep 4 -> print num2\nStep 5 -> Loop For i=2 and i<=num2/2 and ++i\n IF num2%i=0\\\n Print i\n End IF\nStep 6 -> End For Loop\nSTOP" }, { "code": null, "e": 2123, "s": 1733, "text": "#include<stdio.h>\nint main() {\n int num,num2,i;\n printf(\"\\nenter a number\");\n scanf(\"%d\" , &num);\n num2=num%10; //storing unit digit in num2\n printf(\"\\n unit digit of %d is: %d\",num,num2);\n for(i=2;i<=num2/2;++i) { //loop till half of unit digit\n if(num2%i==0) { //calculate multiples\n printf(\"\\n multiple of %d is : %d \",num2,i);\n }\n }\nreturn 0;\n}" }, { "code": null, "e": 2186, "s": 2123, "text": "If we run above program then it will generate following output" }, { "code": null, "e": 2249, "s": 2186, "text": "enter a number329\nunit digit of 329 is: 9\nmultiple of 9 is : 3" } ]
How to add text to an image using Java OpenCV library?
You can add text to an image using the putText() method of the org.opencv.imgproc.Imgproc class. This method renders the specified text in the given image. It accepts − An empty mat object to store the source image. An empty mat object to store the source image. A string object to specify the desired text. A string object to specify the desired text. A Point object specifying the position of the text. A Point object specifying the position of the text. Integer constant specifying the font of the text. Integer constant specifying the font of the text. scale factor that is multiplied by the font-specific base size. scale factor that is multiplied by the font-specific base size. A Scalar object specifying the color of the text. A Scalar object specifying the color of the text. An integer value specifying the color of the text An integer value specifying the color of the text import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class AddingText { public static void main(String args[]) throws Exception { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the contents of the image String file ="D:\\Images\\shapes.jpg"; Mat src = Imgcodecs.imread(file); //Preparing the arguments String text = "JavaFX 2D shapes"; Point position = new Point(170, 280); Scalar color = new Scalar(0, 0, 255); int font = Imgproc.FONT_HERSHEY_SIMPLEX; int scale = 1; int thickness = 3; //Adding text to the image Imgproc.putText(src, text, position, font, scale, color, thickness); //Displaying the resultant Image HighGui.imshow("Contours operation", src); HighGui.waitKey(); } }
[ { "code": null, "e": 1231, "s": 1062, "text": "You can add text to an image using the putText() method of the org.opencv.imgproc.Imgproc class. This method renders the specified text in the given image. It accepts −" }, { "code": null, "e": 1278, "s": 1231, "text": "An empty mat object to store the source image." }, { "code": null, "e": 1325, "s": 1278, "text": "An empty mat object to store the source image." }, { "code": null, "e": 1370, "s": 1325, "text": "A string object to specify the desired text." }, { "code": null, "e": 1415, "s": 1370, "text": "A string object to specify the desired text." }, { "code": null, "e": 1467, "s": 1415, "text": "A Point object specifying the position of the text." }, { "code": null, "e": 1519, "s": 1467, "text": "A Point object specifying the position of the text." }, { "code": null, "e": 1569, "s": 1519, "text": "Integer constant specifying the font of the text." }, { "code": null, "e": 1619, "s": 1569, "text": "Integer constant specifying the font of the text." }, { "code": null, "e": 1683, "s": 1619, "text": "scale factor that is multiplied by the font-specific base size." }, { "code": null, "e": 1747, "s": 1683, "text": "scale factor that is multiplied by the font-specific base size." }, { "code": null, "e": 1797, "s": 1747, "text": "A Scalar object specifying the color of the text." }, { "code": null, "e": 1847, "s": 1797, "text": "A Scalar object specifying the color of the text." }, { "code": null, "e": 1897, "s": 1847, "text": "An integer value specifying the color of the text" }, { "code": null, "e": 1947, "s": 1897, "text": "An integer value specifying the color of the text" }, { "code": null, "e": 2963, "s": 1947, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.Point;\nimport org.opencv.core.Scalar;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class AddingText {\n public static void main(String args[]) throws Exception {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading the contents of the image\n String file =\"D:\\\\Images\\\\shapes.jpg\";\n Mat src = Imgcodecs.imread(file);\n //Preparing the arguments\n String text = \"JavaFX 2D shapes\";\n Point position = new Point(170, 280);\n Scalar color = new Scalar(0, 0, 255);\n int font = Imgproc.FONT_HERSHEY_SIMPLEX;\n int scale = 1;\n int thickness = 3;\n //Adding text to the image\n Imgproc.putText(src, text, position, font, scale, color, thickness);\n //Displaying the resultant Image\n HighGui.imshow(\"Contours operation\", src);\n HighGui.waitKey();\n }\n}" } ]
Tryit Editor v3.6 - Show Python
#if this page is executed with no errors, you have the "mysql.connector" module installed.
[]
Clojure - While Statement
Following is the syntax of the ‘while’ statement. (while(expression) (do codeblock)) The while statement is executed by first evaluating the condition expression (a Boolean value), and if the result is true, then the statements in the while loop are executed. The process is repeated starting from the evaluation of the condition in the while statement. This loop continues until the condition evaluates to false. When the condition is false, the loop terminates. The program logic then continues with the statement immediately following the while statement. Following is the diagrammatic representation of this loop. Following is an example of a while loop statement. (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (def x (atom 1)) (while ( < @x 5 ) (do (println @x) (swap! x inc)))) (Example) In the above example, we are first initializing the value of ‘x’ variable to 1. Note that we are using an atom value, which is a value which can be modified. Then our condition in the while loop is that we are evaluating the condition of the expression to be such as ‘x’ should be less than 5. Till the value of ‘x’ is less than 5, we will print the value of ‘x’ and then increase its value. The swap statement is used to populate the atom variable of ‘x’ with the new incremented value. The above code produces the following output. 1 2 3 4 Print Add Notes Bookmark this page
[ { "code": null, "e": 2424, "s": 2374, "text": "Following is the syntax of the ‘while’ statement." }, { "code": null, "e": 2469, "s": 2424, "text": "(while(expression)\n (do\n codeblock))\n" }, { "code": null, "e": 3002, "s": 2469, "text": "The while statement is executed by first evaluating the condition expression (a Boolean value), and if the result is true, then the statements in the while loop are executed. The process is repeated starting from the evaluation of the condition in the while statement. This loop continues until the condition evaluates to false. When the condition is false, the loop terminates. The program logic then continues with the statement immediately following the while statement. Following is the diagrammatic representation of this loop." }, { "code": null, "e": 3053, "s": 3002, "text": "Following is an example of a while loop statement." }, { "code": null, "e": 3261, "s": 3053, "text": "(ns clojure.examples.hello\n (:gen-class))\n\n;; This program displays Hello World\n(defn Example []\n (def x (atom 1))\n (while ( < @x 5 )\n (do\n (println @x)\n (swap! x inc))))\n(Example)" }, { "code": null, "e": 3749, "s": 3261, "text": "In the above example, we are first initializing the value of ‘x’ variable to 1. Note that we are using an atom value, which is a value which can be modified. Then our condition in the while loop is that we are evaluating the condition of the expression to be such as ‘x’ should be less than 5. Till the value of ‘x’ is less than 5, we will print the value of ‘x’ and then increase its value. The swap statement is used to populate the atom variable of ‘x’ with the new incremented value." }, { "code": null, "e": 3795, "s": 3749, "text": "The above code produces the following output." }, { "code": null, "e": 3804, "s": 3795, "text": "1\n2\n3\n4\n" }, { "code": null, "e": 3811, "s": 3804, "text": " Print" }, { "code": null, "e": 3822, "s": 3811, "text": " Add Notes" } ]
How to draw a hollow circle in SVG?
To draw a hollow circle in SVG, use the <circle> element. For that, use fill=”none” and draw the outline. SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG. You can try to run the following code to learn how to draw a hollow circle in SVG <!DOCTYPE html> <html> <head> <title>HTML5 SVG Hollow Circle</title> <head> <body> <svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg"> <circle cx="100" cy="50" r="40" stroke="black" stroke-width="7" fill="none" /> </svg> </body> </html>
[ { "code": null, "e": 1168, "s": 1062, "text": "To draw a hollow circle in SVG, use the <circle> element. For that, use fill=”none” and draw the outline." }, { "code": null, "e": 1421, "s": 1168, "text": "SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG." }, { "code": null, "e": 1503, "s": 1421, "text": "You can try to run the following code to learn how to draw a hollow circle in SVG" }, { "code": null, "e": 1794, "s": 1503, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML5 SVG Hollow Circle</title>\n <head>\n <body>\n <svg id=\"svgelem\" height=\"200\" xmlns=\"http://www.w3.org/2000/svg\">\n <circle cx=\"100\" cy=\"50\" r=\"40\" stroke=\"black\" stroke-width=\"7\" fill=\"none\" />\n </svg>\n </body>\n</html>" } ]
\lower - Tex Command
\lower - Used to lower the argument by the amount specified in dimen. { \lower <dimen> #1 } \lower command lowers the argument by the amount specified in dimen. l\lower 2pt {owe} r lower l\lower 2pt {owe} r lower l\lower 2pt {owe} r 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8056, "s": 7986, "text": "\\lower - Used to lower the argument by the amount specified in dimen." }, { "code": null, "e": 8078, "s": 8056, "text": "{ \\lower <dimen> #1 }" }, { "code": null, "e": 8147, "s": 8078, "text": "\\lower command lowers the argument by the amount specified in dimen." }, { "code": null, "e": 8178, "s": 8147, "text": "\nl\\lower 2pt {owe} r\n\nlower\n\n\n" }, { "code": null, "e": 8207, "s": 8178, "text": "l\\lower 2pt {owe} r\n\nlower\n\n" }, { "code": null, "e": 8227, "s": 8207, "text": "l\\lower 2pt {owe} r" }, { "code": null, "e": 8259, "s": 8227, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8272, "s": 8259, "text": " Ashraf Said" }, { "code": null, "e": 8305, "s": 8272, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8318, "s": 8305, "text": " Ashraf Said" }, { "code": null, "e": 8350, "s": 8318, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8386, "s": 8350, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8421, "s": 8386, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8438, "s": 8421, "text": " Mohammad Nauman" }, { "code": null, "e": 8471, "s": 8438, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8485, "s": 8471, "text": " Daniel Stern" }, { "code": null, "e": 8517, "s": 8485, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8532, "s": 8517, "text": " Nishant Kumar" }, { "code": null, "e": 8539, "s": 8532, "text": " Print" }, { "code": null, "e": 8550, "s": 8539, "text": " Add Notes" } ]
Differences between CompletableFuture and Future in Java 9?
CompletableFuture<T> class implements Future<T> interface in Java. CompletableFuture can be used as a Future that has explicitly completed. The Future interface doesn’t provide a lot of features, we need to get the result of asynchronous computation using the get() method, which is blocked, so there is no scope to run multiple dependent tasks in a non-blocking fashion whereas CompleteFuture class can provide the functionality to chain multiple dependent tasks that run asynchronously, so we can create a chain of tasks where the next task is triggered when the result of the current task is available. public class CompletableFuture<T> extends Object implements Future<T>, CompletionStage<T> import java.util.function.Supplier; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureTest { public static void main(String args[]) throws ExecutionException, InterruptedException { Calculator calc = new Calculator(4, 7); CompletableFuture<Integer> future = CompletableFuture.supplyAsync(calc); future.thenAccept(result -> { System.out.println(result); }); System.out.println("CompletableFutureTest End.... "); Thread.sleep(10000); } } // Calculator class class Calculator implements Supplier<Integer> { private int x, y; public Calculator(int x, int y) { this.x = x; this.y = y; } @Override public Integer get() { try { Thread.sleep(3000); } catch(InterruptedException e) { e.printStackTrace(); } return x + y; } } CompletableFutureTest End.... 11
[ { "code": null, "e": 1668, "s": 1062, "text": "CompletableFuture<T> class implements Future<T> interface in Java. CompletableFuture can be used as a Future that has explicitly completed. The Future interface doesn’t provide a lot of features, we need to get the result of asynchronous computation using the get() method, which is blocked, so there is no scope to run multiple dependent tasks in a non-blocking fashion whereas CompleteFuture class can provide the functionality to chain multiple dependent tasks that run asynchronously, so we can create a chain of tasks where the next task is triggered when the result of the current task is available." }, { "code": null, "e": 1758, "s": 1668, "text": "public class CompletableFuture<T> extends Object implements Future<T>, CompletionStage<T>" }, { "code": null, "e": 2674, "s": 1758, "text": "import java.util.function.Supplier;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ExecutionException;\n\npublic class CompletableFutureTest {\n public static void main(String args[]) throws ExecutionException, InterruptedException {\n Calculator calc = new Calculator(4, 7);\n CompletableFuture<Integer> future = CompletableFuture.supplyAsync(calc);\n future.thenAccept(result -> {\n System.out.println(result);\n });\n System.out.println(\"CompletableFutureTest End.... \");\n Thread.sleep(10000);\n }\n}\n\n// Calculator class\nclass Calculator implements Supplier<Integer> {\n private int x, y;\n public Calculator(int x, int y) {\n this.x = x;\n this.y = y;\n }\n @Override\n public Integer get() {\n try {\n Thread.sleep(3000);\n } catch(InterruptedException e) {\n e.printStackTrace();\n }\n return x + y;\n }\n}" }, { "code": null, "e": 2707, "s": 2674, "text": "CompletableFutureTest End....\n11" } ]
How to get the length of an object in JavaScript?
The length property is only applicable to arrays and strings. So when we call the length property on an object we will get undefined. Live Demo <html> <body> <script> var object = {prop:1, prop:2}; document.write(object.length); </script> </body> </html> undefined Whereas arrays and strings will display their length when length property is used on them. Live Demo <html> <body> <script> var string = 'hello'; var array = [1,2,3]; var len1 = string.length; var len2 = array.length; document.write(len1); document.write("</br>"); document.write(len2); </script> </body> </html> 5 3 In javascript, we have Object.keys() property, which checks whether there are any properties or not. If we use the length property with Object.keys() then the number of properties will be displayed which is nothing but the length of the object. Live Demo <html> <body> <script> var object = {one: 1, two:2, three:3}; document.write(Object.keys(object).length); </script> </body> </html> 3
[ { "code": null, "e": 1196, "s": 1062, "text": "The length property is only applicable to arrays and strings. So when we call the length property on an object we will get undefined." }, { "code": null, "e": 1206, "s": 1196, "text": "Live Demo" }, { "code": null, "e": 1323, "s": 1206, "text": "<html>\n<body>\n<script>\n var object = {prop:1, prop:2};\n document.write(object.length);\n</script>\n</body>\n</html>" }, { "code": null, "e": 1333, "s": 1323, "text": "undefined" }, { "code": null, "e": 1424, "s": 1333, "text": "Whereas arrays and strings will display their length when length property is used on them." }, { "code": null, "e": 1434, "s": 1424, "text": "Live Demo" }, { "code": null, "e": 1667, "s": 1434, "text": "<html>\n<body>\n<script>\n var string = 'hello';\n var array = [1,2,3];\n var len1 = string.length;\n var len2 = array.length;\n document.write(len1);\n document.write(\"</br>\");\n document.write(len2);\n</script>\n</body>\n</html>" }, { "code": null, "e": 1671, "s": 1667, "text": "5\n3" }, { "code": null, "e": 1917, "s": 1671, "text": "In javascript, we have Object.keys() property, which checks whether there are any properties or not. If we use the length property with Object.keys() then the number of properties will be displayed which is nothing but the length of the object. " }, { "code": null, "e": 1927, "s": 1917, "text": "Live Demo" }, { "code": null, "e": 2065, "s": 1927, "text": "<html>\n<body>\n<script>\n var object = {one: 1, two:2, three:3};\n document.write(Object.keys(object).length);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2067, "s": 2065, "text": "3" } ]
Python - Processing Unstructured Data
The data that is already present in a row and column format or which can be easily converted to rows and columns so that later it can fit nicely into a database is known as structured data. Examples are CSV, TXT, XLS files etc. These files have a delimiter and either fixed or variable width where the missing values are represented as blanks in between the delimiters. But sometimes we get data where the lines are not fixed width, or they are just HTML, image or pdf files. Such data is known as unstructured data. While the HTML file can be handled by processing the HTML tags, a feed from twitter or a plain text document from a news feed can without having a delimiter does not have tags to handle. In such scenario we use different in-built functions from various python libraries to process the file. In the below example we take a text file and read the file segregating each of the lines in it. Next we can divide the output into further lines and words. The original file is a text file containing some paragraphs describing the python language. filename = 'path\input.txt' with open(filename) as fn: # Read each line ln = fn.readline() # Keep count of lines lncnt = 1 while ln: print("Line {}: {}".format(lncnt, ln.strip())) ln = fn.readline() lncnt += 1 When we execute the above code, it produces the following result. Line 1: Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales. Line 2: Python features a dynamic type system and automatic memory management. It supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library. Line 3: Python interpreters are available for many operating systems. CPython, the reference implementation of Python, is open source software and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation. We can count the frequency of the words in the file using the counter function as follows. from collections import Counter with open(r'pathinput2.txt') as f: p = Counter(f.read().split()) print(p) When we execute the above code, it produces the following result. Counter({'and': 3, 'Python': 3, 'that': 2, 'a': 2, 'programming': 2, 'code': 1, '1991,': 1, 'is': 1, 'programming.': 1, 'dynamic': 1, 'an': 1, 'design': 1, 'in': 1, 'high-level': 1, 'management.': 1, 'features': 1, 'readability,': 1, 'van': 1, 'both': 1, 'for': 1, 'Rossum': 1, 'system': 1, 'provides': 1, 'memory': 1, 'has': 1, 'type': 1, 'enable': 1, 'Created': 1, 'philosophy': 1, 'constructs': 1, 'emphasizes': 1, 'general-purpose': 1, 'notably': 1, 'released': 1, 'significant': 1, 'Guido': 1, 'using': 1, 'interpreted': 1, 'by': 1, 'on': 1, 'language': 1, 'whitespace.': 1, 'clear': 1, 'It': 1, 'large': 1, 'small': 1, 'automatic': 1, 'scales.': 1, 'first': 1}) 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3337, "s": 2529, "text": "The data that is already present in a row and column format or which can be easily converted to rows and columns so that later it can fit nicely into a database is known as structured data. Examples are CSV, TXT, XLS files etc. These files have a delimiter and either fixed or variable width where the missing values are represented as blanks in between the delimiters. But sometimes we get data where the lines are not fixed width, or they are just HTML, image or pdf files. Such data is known as unstructured data. While the HTML file can be handled by processing the HTML tags, a feed from twitter or a plain text document from a news feed can without having a delimiter does not have tags to handle. In such scenario we use different in-built functions from various python libraries to process the file." }, { "code": null, "e": 3585, "s": 3337, "text": "In the below example we take a text file and read the file segregating each of the lines in it. Next we can divide the output into further lines and words. The original file is a text file containing some paragraphs describing the python language." }, { "code": null, "e": 3832, "s": 3585, "text": "filename = 'path\\input.txt' \n\nwith open(filename) as fn: \n\n# Read each line\n ln = fn.readline()\n\n# Keep count of lines\n lncnt = 1\n while ln:\n print(\"Line {}: {}\".format(lncnt, ln.strip()))\n ln = fn.readline()\n lncnt += 1" }, { "code": null, "e": 3898, "s": 3832, "text": "When we execute the above code, it produces the following result." }, { "code": null, "e": 4783, "s": 3898, "text": "Line 1: Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales.\nLine 2: Python features a dynamic type system and automatic memory management. It supports multiple programming paradigms, including object-oriented, imperative, functional and procedural, and has a large and comprehensive standard library.\nLine 3: Python interpreters are available for many operating systems. CPython, the reference implementation of Python, is open source software and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation." }, { "code": null, "e": 4874, "s": 4783, "text": "We can count the frequency of the words in the file using the counter function as follows." }, { "code": null, "e": 5011, "s": 4874, "text": "from collections import Counter\n\nwith open(r'pathinput2.txt') as f:\n p = Counter(f.read().split())\n print(p)" }, { "code": null, "e": 5077, "s": 5011, "text": "When we execute the above code, it produces the following result." }, { "code": null, "e": 5745, "s": 5077, "text": "Counter({'and': 3, 'Python': 3, 'that': 2, 'a': 2, 'programming': 2, 'code': 1, '1991,': 1, 'is': 1, 'programming.': 1, 'dynamic': 1, 'an': 1, 'design': 1, 'in': 1, 'high-level': 1, 'management.': 1, 'features': 1, 'readability,': 1, 'van': 1, 'both': 1, 'for': 1, 'Rossum': 1, 'system': 1, 'provides': 1, 'memory': 1, 'has': 1, 'type': 1, 'enable': 1, 'Created': 1, 'philosophy': 1, 'constructs': 1, 'emphasizes': 1, 'general-purpose': 1, 'notably': 1, 'released': 1, 'significant': 1, 'Guido': 1, 'using': 1, 'interpreted': 1, 'by': 1, 'on': 1, 'language': 1, 'whitespace.': 1, 'clear': 1, 'It': 1, 'large': 1, 'small': 1, 'automatic': 1, 'scales.': 1, 'first': 1})" }, { "code": null, "e": 5782, "s": 5745, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5798, "s": 5782, "text": " Malhar Lathkar" }, { "code": null, "e": 5831, "s": 5798, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 5850, "s": 5831, "text": " Arnab Chakraborty" }, { "code": null, "e": 5885, "s": 5850, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 5907, "s": 5885, "text": " In28Minutes Official" }, { "code": null, "e": 5941, "s": 5907, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5969, "s": 5941, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6004, "s": 5969, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6018, "s": 6004, "text": " Lets Kode It" }, { "code": null, "e": 6051, "s": 6018, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6068, "s": 6051, "text": " Abhilash Nelson" }, { "code": null, "e": 6075, "s": 6068, "text": " Print" }, { "code": null, "e": 6086, "s": 6075, "text": " Add Notes" } ]
How to draw profile icon shape in android?
This example demonstrate about How to draw profile icon shape in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" android:layout_marginTop="30dp" tools:context=".MainActivity"> <ImageView android:layout_width="100dp" android:layout_height="100dp" android:background="@drawable/background"/> </LinearLayout> In the above code, we have taken imageview and added background as background.xml. Step 3 − Add the following code to drawable/ background.xml <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:autoMirrored="true" android:viewportWidth="277.58" android:viewportHeight="277.58"> <path android:fillColor="#D80027" android:pathData="M138.46,164.287c-38.628,0 -69.925,-37.519 -69.925,-83.767C68.535, 34.277 99.832,0 138.46,0c38.634,0 69.957,34.277 69.957,80.52C208.417, 126.768 177.093,164.287 138.46,164.287zM29.689,277.528c0,0 -14.832, 0.979 -21.365,-8.023c-3.53,-4.863 -1.071,-14.718 1.343,-20.217l5.912, -13.473c0,0 16.35,-36.567 34.962,-57.757c11.433,-12.994 25.031, -10.035 33.826,-5.809c5.417,2.6 11.542,10.176 16.018,14.191c6.168, 5.532 17.057,11.819 34.859,12.173h10.922c17.791,-0.354 28.68, -6.641 34.843,-12.173c4.471,-4.014 10.427,-11.825 15.795, -14.511c8.072,-4.041 20.358,-6.527 31.492,6.13c18.618,21.191 33.363, 58.421 33.363,58.421l6.059,13.212c2.507,5.461 5.075,15.267 1.643, 20.195c-6.124,8.811 -19.874,7.642 -19.874,7.642S29.689,277.528 29.689, 277.528z" /> </vector> 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": 1136, "s": 1062, "text": "This example demonstrate about How to draw profile icon shape in android." }, { "code": null, "e": 1265, "s": 1136, "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": 1330, "s": 1265, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1853, "s": 1330, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center\"\n android:layout_marginTop=\"30dp\"\n tools:context=\".MainActivity\">\n <ImageView\n android:layout_width=\"100dp\"\n android:layout_height=\"100dp\"\n android:background=\"@drawable/background\"/>\n</LinearLayout>" }, { "code": null, "e": 1936, "s": 1853, "text": "In the above code, we have taken imageview and added background as background.xml." }, { "code": null, "e": 1996, "s": 1936, "text": "Step 3 − Add the following code to drawable/ background.xml" }, { "code": null, "e": 3298, "s": 1996, "text": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:width=\"24dp\"\n android:height=\"24dp\"\n android:autoMirrored=\"true\"\n android:viewportWidth=\"277.58\"\n android:viewportHeight=\"277.58\">\n <path\n android:fillColor=\"#D80027\"\n android:pathData=\"M138.46,164.287c-38.628,0 -69.925,-37.519 -69.925,-83.767C68.535,\n 34.277 99.832,0 138.46,0c38.634,0 69.957,34.277 69.957,80.52C208.417,\n 126.768 177.093,164.287 138.46,164.287zM29.689,277.528c0,0 -14.832,\n 0.979 -21.365,-8.023c-3.53,-4.863 -1.071,-14.718 1.343,-20.217l5.912,\n -13.473c0,0 16.35,-36.567 34.962,-57.757c11.433,-12.994 25.031,\n -10.035 33.826,-5.809c5.417,2.6 11.542,10.176 16.018,14.191c6.168,\n 5.532 17.057,11.819 34.859,12.173h10.922c17.791,-0.354 28.68,\n -6.641 34.843,-12.173c4.471,-4.014 10.427,-11.825 15.795,\n -14.511c8.072,-4.041 20.358,-6.527 31.492,6.13c18.618,21.191 33.363,\n 58.421 33.363,58.421l6.059,13.212c2.507,5.461 5.075,15.267 1.643,\n 20.195c-6.124,8.811 -19.874,7.642 -19.874,7.642S29.689,277.528 29.689,\n 277.528z\" />\n</vector>" }, { "code": null, "e": 3645, "s": 3298, "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": 3685, "s": 3645, "text": "Click here to download the project code" } ]
Q-Learning in Python - GeeksforGeeks
09 Nov, 2021 Pre-Requisite : Reinforcement Learning Reinforcement Learning briefly is a paradigm of Learning Process in which a learning agent learns, overtime, to behave optimally in a certain environment by interacting continuously in the environment. The agent during its course of learning experience various different situations in the environment it is in. These are called states. The agent while being in that state may choose from a set of allowable actions which may fetch different rewards(or penalties). The learning agent overtime learns to maximize these rewards so as to behave optimally at any given state it is in. Q-Learning is a basic form of Reinforcement Learning which uses Q-values (also called action values) to iteratively improve the behavior of the learning agent. Q-Values or Action-Values: Q-values are defined for states and actions. is an estimation of how good is it to take the action at the state . This estimation of will be iteratively computed using the TD- Update rule which we will see in the upcoming sections.Rewards and Episodes: An agent over the course of its lifetime starts from a start state, makes a number of transitions from its current state to a next state based on its choice of action and also the environment the agent is interacting in. At every step of transition, the agent from a state takes an action, observes a reward from the environment, and then transits to another state. If at any point of time the agent ends up in one of the terminating states that means there are no further transition possible. This is said to be the completion of an episode.Temporal Difference or TD-Update:The Temporal Difference or TD-Update rule can be represented as follows :This update rule to estimate the value of Q is applied at every time step of the agents interaction with the environment. The terms used are explained below. : : Current State of the agent. : Current Action Picked according to some policy. : Next State where the agent ends up. : Next best action to be picked using current Q-value estimation, i.e. pick the action with the maximum Q-value in the next state. : Current Reward observed from the environment in Response of current action.(>0 and <=1) : Discounting Factor for Future Rewards. Future rewards are less valuable than current rewards so they must be discounted. Since Q-value is an estimation of expected rewards from a state, discounting rule applies here as well. : Step length taken to update the estimation of Q(S, A).Choosing the Action to take using -greedy policy:-greedy policy of is a very simple policy of choosing actions using the current Q-value estimations. It goes as follows :With probability choose the action which has the highest Q-value.With probability choose any action at random. Now with all the theory required in hand let us take an example. We will use OpenAI’s gym environment to train our Q-Learning model.Command to Install gym –pip install gymBefore starting with example, you will need some helper code in order to visualize the working of the algorithms. There will be two helper files which need to be downloaded in the working directory. One can find the files here.Step # 1 : Import required libraries.import gymimport itertoolsimport matplotlibimport matplotlib.styleimport numpy as npimport pandas as pdimport sys from collections import defaultdictfrom windy_gridworld import WindyGridworldEnvimport plotting matplotlib.style.use('ggplot') Step #2 : Create gym environment.env = WindyGridworldEnv() Step #3 : Make the -greedy policy.def createEpsilonGreedyPolicy(Q, epsilon, num_actions): """ Creates an epsilon-greedy policy based on a given Q-function and epsilon. Returns a function that takes the state as an input and returns the probabilities for each action in the form of a numpy array of length of the action space(set of possible actions). """ def policyFunction(state): Action_probabilities = np.ones(num_actions, dtype = float) * epsilon / num_actions best_action = np.argmax(Q[state]) Action_probabilities[best_action] += (1.0 - epsilon) return Action_probabilities return policyFunction Step #4 : Build Q-Learning Model.def qLearning(env, num_episodes, discount_factor = 1.0, alpha = 0.6, epsilon = 0.1): """ Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy while improving following an epsilon-greedy policy""" # Action value function # A nested dictionary that maps # state -> (action -> action-value). Q = defaultdict(lambda: np.zeros(env.action_space.n)) # Keeps track of useful statistics stats = plotting.EpisodeStats( episode_lengths = np.zeros(num_episodes), episode_rewards = np.zeros(num_episodes)) # Create an epsilon greedy policy function # appropriately for environment action space policy = createEpsilonGreedyPolicy(Q, epsilon, env.action_space.n) # For every episode for ith_episode in range(num_episodes): # Reset the environment and pick the first action state = env.reset() for t in itertools.count(): # get probabilities of all actions from current state action_probabilities = policy(state) # choose action according to # the probability distribution action = np.random.choice(np.arange( len(action_probabilities)), p = action_probabilities) # take action and get reward, transit to next state next_state, reward, done, _ = env.step(action) # Update statistics stats.episode_rewards[ith_episode] += reward stats.episode_lengths[ith_episode] = t # TD Update best_next_action = np.argmax(Q[next_state]) td_target = reward + discount_factor * Q[next_state][best_next_action] td_delta = td_target - Q[state][action] Q[state][action] += alpha * td_delta # done is True if episode terminated if done: break state = next_state return Q, stats Step #5 : Train the model.Q, stats = qLearning(env, 1000) Step #6 : Plot important statistics.plotting.plot_episode_stats(stats)Conclusion:We see that in the Episode Reward over time plot that the episode rewards progressively increase over time and ultimately levels out at a high reward per episode value which indicates that the agent has learnt to maximize its total reward earned in an episode by behaving optimally at every state.My Personal Notes arrow_drop_upSave Q-Values or Action-Values: Q-values are defined for states and actions. is an estimation of how good is it to take the action at the state . This estimation of will be iteratively computed using the TD- Update rule which we will see in the upcoming sections. Rewards and Episodes: An agent over the course of its lifetime starts from a start state, makes a number of transitions from its current state to a next state based on its choice of action and also the environment the agent is interacting in. At every step of transition, the agent from a state takes an action, observes a reward from the environment, and then transits to another state. If at any point of time the agent ends up in one of the terminating states that means there are no further transition possible. This is said to be the completion of an episode. Temporal Difference or TD-Update:The Temporal Difference or TD-Update rule can be represented as follows :This update rule to estimate the value of Q is applied at every time step of the agents interaction with the environment. The terms used are explained below. : : Current State of the agent. : Current Action Picked according to some policy. : Next State where the agent ends up. : Next best action to be picked using current Q-value estimation, i.e. pick the action with the maximum Q-value in the next state. : Current Reward observed from the environment in Response of current action.(>0 and <=1) : Discounting Factor for Future Rewards. Future rewards are less valuable than current rewards so they must be discounted. Since Q-value is an estimation of expected rewards from a state, discounting rule applies here as well. : Step length taken to update the estimation of Q(S, A). The Temporal Difference or TD-Update rule can be represented as follows : This update rule to estimate the value of Q is applied at every time step of the agents interaction with the environment. The terms used are explained below. : : Current State of the agent. : Current Action Picked according to some policy. : Next State where the agent ends up. : Next best action to be picked using current Q-value estimation, i.e. pick the action with the maximum Q-value in the next state. : Current Reward observed from the environment in Response of current action. (>0 and <=1) : Discounting Factor for Future Rewards. Future rewards are less valuable than current rewards so they must be discounted. Since Q-value is an estimation of expected rewards from a state, discounting rule applies here as well. : Step length taken to update the estimation of Q(S, A). Choosing the Action to take using -greedy policy:-greedy policy of is a very simple policy of choosing actions using the current Q-value estimations. It goes as follows :With probability choose the action which has the highest Q-value.With probability choose any action at random. Now with all the theory required in hand let us take an example. We will use OpenAI’s gym environment to train our Q-Learning model.Command to Install gym –pip install gymBefore starting with example, you will need some helper code in order to visualize the working of the algorithms. There will be two helper files which need to be downloaded in the working directory. One can find the files here.Step # 1 : Import required libraries.import gymimport itertoolsimport matplotlibimport matplotlib.styleimport numpy as npimport pandas as pdimport sys from collections import defaultdictfrom windy_gridworld import WindyGridworldEnvimport plotting matplotlib.style.use('ggplot') Step #2 : Create gym environment.env = WindyGridworldEnv() Step #3 : Make the -greedy policy.def createEpsilonGreedyPolicy(Q, epsilon, num_actions): """ Creates an epsilon-greedy policy based on a given Q-function and epsilon. Returns a function that takes the state as an input and returns the probabilities for each action in the form of a numpy array of length of the action space(set of possible actions). """ def policyFunction(state): Action_probabilities = np.ones(num_actions, dtype = float) * epsilon / num_actions best_action = np.argmax(Q[state]) Action_probabilities[best_action] += (1.0 - epsilon) return Action_probabilities return policyFunction Step #4 : Build Q-Learning Model.def qLearning(env, num_episodes, discount_factor = 1.0, alpha = 0.6, epsilon = 0.1): """ Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy while improving following an epsilon-greedy policy""" # Action value function # A nested dictionary that maps # state -> (action -> action-value). Q = defaultdict(lambda: np.zeros(env.action_space.n)) # Keeps track of useful statistics stats = plotting.EpisodeStats( episode_lengths = np.zeros(num_episodes), episode_rewards = np.zeros(num_episodes)) # Create an epsilon greedy policy function # appropriately for environment action space policy = createEpsilonGreedyPolicy(Q, epsilon, env.action_space.n) # For every episode for ith_episode in range(num_episodes): # Reset the environment and pick the first action state = env.reset() for t in itertools.count(): # get probabilities of all actions from current state action_probabilities = policy(state) # choose action according to # the probability distribution action = np.random.choice(np.arange( len(action_probabilities)), p = action_probabilities) # take action and get reward, transit to next state next_state, reward, done, _ = env.step(action) # Update statistics stats.episode_rewards[ith_episode] += reward stats.episode_lengths[ith_episode] = t # TD Update best_next_action = np.argmax(Q[next_state]) td_target = reward + discount_factor * Q[next_state][best_next_action] td_delta = td_target - Q[state][action] Q[state][action] += alpha * td_delta # done is True if episode terminated if done: break state = next_state return Q, stats Step #5 : Train the model.Q, stats = qLearning(env, 1000) Step #6 : Plot important statistics.plotting.plot_episode_stats(stats)Conclusion:We see that in the Episode Reward over time plot that the episode rewards progressively increase over time and ultimately levels out at a high reward per episode value which indicates that the agent has learnt to maximize its total reward earned in an episode by behaving optimally at every state.My Personal Notes arrow_drop_upSave -greedy policy of is a very simple policy of choosing actions using the current Q-value estimations. It goes as follows : With probability choose the action which has the highest Q-value. With probability choose any action at random. Now with all the theory required in hand let us take an example. We will use OpenAI’s gym environment to train our Q-Learning model. Command to Install gym – pip install gym Before starting with example, you will need some helper code in order to visualize the working of the algorithms. There will be two helper files which need to be downloaded in the working directory. One can find the files here. Step # 1 : Import required libraries. import gymimport itertoolsimport matplotlibimport matplotlib.styleimport numpy as npimport pandas as pdimport sys from collections import defaultdictfrom windy_gridworld import WindyGridworldEnvimport plotting matplotlib.style.use('ggplot') Step #2 : Create gym environment. env = WindyGridworldEnv() Step #3 : Make the -greedy policy. def createEpsilonGreedyPolicy(Q, epsilon, num_actions): """ Creates an epsilon-greedy policy based on a given Q-function and epsilon. Returns a function that takes the state as an input and returns the probabilities for each action in the form of a numpy array of length of the action space(set of possible actions). """ def policyFunction(state): Action_probabilities = np.ones(num_actions, dtype = float) * epsilon / num_actions best_action = np.argmax(Q[state]) Action_probabilities[best_action] += (1.0 - epsilon) return Action_probabilities return policyFunction Step #4 : Build Q-Learning Model. def qLearning(env, num_episodes, discount_factor = 1.0, alpha = 0.6, epsilon = 0.1): """ Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy while improving following an epsilon-greedy policy""" # Action value function # A nested dictionary that maps # state -> (action -> action-value). Q = defaultdict(lambda: np.zeros(env.action_space.n)) # Keeps track of useful statistics stats = plotting.EpisodeStats( episode_lengths = np.zeros(num_episodes), episode_rewards = np.zeros(num_episodes)) # Create an epsilon greedy policy function # appropriately for environment action space policy = createEpsilonGreedyPolicy(Q, epsilon, env.action_space.n) # For every episode for ith_episode in range(num_episodes): # Reset the environment and pick the first action state = env.reset() for t in itertools.count(): # get probabilities of all actions from current state action_probabilities = policy(state) # choose action according to # the probability distribution action = np.random.choice(np.arange( len(action_probabilities)), p = action_probabilities) # take action and get reward, transit to next state next_state, reward, done, _ = env.step(action) # Update statistics stats.episode_rewards[ith_episode] += reward stats.episode_lengths[ith_episode] = t # TD Update best_next_action = np.argmax(Q[next_state]) td_target = reward + discount_factor * Q[next_state][best_next_action] td_delta = td_target - Q[state][action] Q[state][action] += alpha * td_delta # done is True if episode terminated if done: break state = next_state return Q, stats Step #5 : Train the model. Q, stats = qLearning(env, 1000) Step #6 : Plot important statistics. plotting.plot_episode_stats(stats) Conclusion:We see that in the Episode Reward over time plot that the episode rewards progressively increase over time and ultimately levels out at a high reward per episode value which indicates that the agent has learnt to maximize its total reward earned in an episode by behaving optimally at every state. VishvajeetRamanuj rajeev0719singh Advanced Computer Subject Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Decision Tree System Design Tutorial Copying Files to and from Docker Containers Python | Decision tree implementation Decision Tree Introduction with example Agents in Artificial Intelligence Decision Tree Python | Decision tree implementation Search Algorithms in AI Difference between Informed and Uninformed Search in AI
[ { "code": null, "e": 23799, "s": 23771, "text": "\n09 Nov, 2021" }, { "code": null, "e": 23838, "s": 23799, "text": "Pre-Requisite : Reinforcement Learning" }, { "code": null, "e": 24418, "s": 23838, "text": "Reinforcement Learning briefly is a paradigm of Learning Process in which a learning agent learns, overtime, to behave optimally in a certain environment by interacting continuously in the environment. The agent during its course of learning experience various different situations in the environment it is in. These are called states. The agent while being in that state may choose from a set of allowable actions which may fetch different rewards(or penalties). The learning agent overtime learns to maximize these rewards so as to behave optimally at any given state it is in." }, { "code": null, "e": 24578, "s": 24418, "text": "Q-Learning is a basic form of Reinforcement Learning which uses Q-values (also called action values) to iteratively improve the behavior of the learning agent." }, { "code": null, "e": 30583, "s": 24578, "text": "Q-Values or Action-Values: Q-values are defined for states and actions. is an estimation of how good is it to take the action at the state . This estimation of will be iteratively computed using the TD- Update rule which we will see in the upcoming sections.Rewards and Episodes: An agent over the course of its lifetime starts from a start state, makes a number of transitions from its current state to a next state based on its choice of action and also the environment the agent is interacting in. At every step of transition, the agent from a state takes an action, observes a reward from the environment, and then transits to another state. If at any point of time the agent ends up in one of the terminating states that means there are no further transition possible. This is said to be the completion of an episode.Temporal Difference or TD-Update:The Temporal Difference or TD-Update rule can be represented as follows :This update rule to estimate the value of Q is applied at every time step of the agents interaction with the environment. The terms used are explained below. : : Current State of the agent. : Current Action Picked according to some policy. : Next State where the agent ends up. : Next best action to be picked using current Q-value estimation, i.e. pick the action with the maximum Q-value in the next state. : Current Reward observed from the environment in Response of current action.(>0 and <=1) : Discounting Factor for Future Rewards. Future rewards are less valuable than current rewards so they must be discounted. Since Q-value is an estimation of expected rewards from a state, discounting rule applies here as well. : Step length taken to update the estimation of Q(S, A).Choosing the Action to take using -greedy policy:-greedy policy of is a very simple policy of choosing actions using the current Q-value estimations. It goes as follows :With probability choose the action which has the highest Q-value.With probability choose any action at random. Now with all the theory required in hand let us take an example. We will use OpenAI’s gym environment to train our Q-Learning model.Command to Install gym –pip install gymBefore starting with example, you will need some helper code in order to visualize the working of the algorithms. There will be two helper files which need to be downloaded in the working directory. One can find the files here.Step # 1 : Import required libraries.import gymimport itertoolsimport matplotlibimport matplotlib.styleimport numpy as npimport pandas as pdimport sys from collections import defaultdictfrom windy_gridworld import WindyGridworldEnvimport plotting matplotlib.style.use('ggplot') Step #2 : Create gym environment.env = WindyGridworldEnv() Step #3 : Make the -greedy policy.def createEpsilonGreedyPolicy(Q, epsilon, num_actions): \"\"\" Creates an epsilon-greedy policy based on a given Q-function and epsilon. Returns a function that takes the state as an input and returns the probabilities for each action in the form of a numpy array of length of the action space(set of possible actions). \"\"\" def policyFunction(state): Action_probabilities = np.ones(num_actions, dtype = float) * epsilon / num_actions best_action = np.argmax(Q[state]) Action_probabilities[best_action] += (1.0 - epsilon) return Action_probabilities return policyFunction Step #4 : Build Q-Learning Model.def qLearning(env, num_episodes, discount_factor = 1.0, alpha = 0.6, epsilon = 0.1): \"\"\" Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy while improving following an epsilon-greedy policy\"\"\" # Action value function # A nested dictionary that maps # state -> (action -> action-value). Q = defaultdict(lambda: np.zeros(env.action_space.n)) # Keeps track of useful statistics stats = plotting.EpisodeStats( episode_lengths = np.zeros(num_episodes), episode_rewards = np.zeros(num_episodes)) # Create an epsilon greedy policy function # appropriately for environment action space policy = createEpsilonGreedyPolicy(Q, epsilon, env.action_space.n) # For every episode for ith_episode in range(num_episodes): # Reset the environment and pick the first action state = env.reset() for t in itertools.count(): # get probabilities of all actions from current state action_probabilities = policy(state) # choose action according to # the probability distribution action = np.random.choice(np.arange( len(action_probabilities)), p = action_probabilities) # take action and get reward, transit to next state next_state, reward, done, _ = env.step(action) # Update statistics stats.episode_rewards[ith_episode] += reward stats.episode_lengths[ith_episode] = t # TD Update best_next_action = np.argmax(Q[next_state]) td_target = reward + discount_factor * Q[next_state][best_next_action] td_delta = td_target - Q[state][action] Q[state][action] += alpha * td_delta # done is True if episode terminated if done: break state = next_state return Q, stats Step #5 : Train the model.Q, stats = qLearning(env, 1000) Step #6 : Plot important statistics.plotting.plot_episode_stats(stats)Conclusion:We see that in the Episode Reward over time plot that the episode rewards progressively increase over time and ultimately levels out at a high reward per episode value which indicates that the agent has learnt to maximize its total reward earned in an episode by behaving optimally at every state.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30845, "s": 30583, "text": "Q-Values or Action-Values: Q-values are defined for states and actions. is an estimation of how good is it to take the action at the state . This estimation of will be iteratively computed using the TD- Update rule which we will see in the upcoming sections." }, { "code": null, "e": 31410, "s": 30845, "text": "Rewards and Episodes: An agent over the course of its lifetime starts from a start state, makes a number of transitions from its current state to a next state based on its choice of action and also the environment the agent is interacting in. At every step of transition, the agent from a state takes an action, observes a reward from the environment, and then transits to another state. If at any point of time the agent ends up in one of the terminating states that means there are no further transition possible. This is said to be the completion of an episode." }, { "code": null, "e": 32299, "s": 31410, "text": "Temporal Difference or TD-Update:The Temporal Difference or TD-Update rule can be represented as follows :This update rule to estimate the value of Q is applied at every time step of the agents interaction with the environment. The terms used are explained below. : : Current State of the agent. : Current Action Picked according to some policy. : Next State where the agent ends up. : Next best action to be picked using current Q-value estimation, i.e. pick the action with the maximum Q-value in the next state. : Current Reward observed from the environment in Response of current action.(>0 and <=1) : Discounting Factor for Future Rewards. Future rewards are less valuable than current rewards so they must be discounted. Since Q-value is an estimation of expected rewards from a state, discounting rule applies here as well. : Step length taken to update the estimation of Q(S, A)." }, { "code": null, "e": 32373, "s": 32299, "text": "The Temporal Difference or TD-Update rule can be represented as follows :" }, { "code": null, "e": 32533, "s": 32373, "text": "This update rule to estimate the value of Q is applied at every time step of the agents interaction with the environment. The terms used are explained below. :" }, { "code": null, "e": 32564, "s": 32533, "text": " : Current State of the agent." }, { "code": null, "e": 32615, "s": 32564, "text": " : Current Action Picked according to some policy." }, { "code": null, "e": 32654, "s": 32615, "text": " : Next State where the agent ends up." }, { "code": null, "e": 32786, "s": 32654, "text": " : Next best action to be picked using current Q-value estimation, i.e. pick the action with the maximum Q-value in the next state." }, { "code": null, "e": 32865, "s": 32786, "text": " : Current Reward observed from the environment in Response of current action." }, { "code": null, "e": 33105, "s": 32865, "text": "(>0 and <=1) : Discounting Factor for Future Rewards. Future rewards are less valuable than current rewards so they must be discounted. Since Q-value is an estimation of expected rewards from a state, discounting rule applies here as well." }, { "code": null, "e": 33163, "s": 33105, "text": " : Step length taken to update the estimation of Q(S, A)." }, { "code": null, "e": 37455, "s": 33163, "text": "Choosing the Action to take using -greedy policy:-greedy policy of is a very simple policy of choosing actions using the current Q-value estimations. It goes as follows :With probability choose the action which has the highest Q-value.With probability choose any action at random. Now with all the theory required in hand let us take an example. We will use OpenAI’s gym environment to train our Q-Learning model.Command to Install gym –pip install gymBefore starting with example, you will need some helper code in order to visualize the working of the algorithms. There will be two helper files which need to be downloaded in the working directory. One can find the files here.Step # 1 : Import required libraries.import gymimport itertoolsimport matplotlibimport matplotlib.styleimport numpy as npimport pandas as pdimport sys from collections import defaultdictfrom windy_gridworld import WindyGridworldEnvimport plotting matplotlib.style.use('ggplot') Step #2 : Create gym environment.env = WindyGridworldEnv() Step #3 : Make the -greedy policy.def createEpsilonGreedyPolicy(Q, epsilon, num_actions): \"\"\" Creates an epsilon-greedy policy based on a given Q-function and epsilon. Returns a function that takes the state as an input and returns the probabilities for each action in the form of a numpy array of length of the action space(set of possible actions). \"\"\" def policyFunction(state): Action_probabilities = np.ones(num_actions, dtype = float) * epsilon / num_actions best_action = np.argmax(Q[state]) Action_probabilities[best_action] += (1.0 - epsilon) return Action_probabilities return policyFunction Step #4 : Build Q-Learning Model.def qLearning(env, num_episodes, discount_factor = 1.0, alpha = 0.6, epsilon = 0.1): \"\"\" Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy while improving following an epsilon-greedy policy\"\"\" # Action value function # A nested dictionary that maps # state -> (action -> action-value). Q = defaultdict(lambda: np.zeros(env.action_space.n)) # Keeps track of useful statistics stats = plotting.EpisodeStats( episode_lengths = np.zeros(num_episodes), episode_rewards = np.zeros(num_episodes)) # Create an epsilon greedy policy function # appropriately for environment action space policy = createEpsilonGreedyPolicy(Q, epsilon, env.action_space.n) # For every episode for ith_episode in range(num_episodes): # Reset the environment and pick the first action state = env.reset() for t in itertools.count(): # get probabilities of all actions from current state action_probabilities = policy(state) # choose action according to # the probability distribution action = np.random.choice(np.arange( len(action_probabilities)), p = action_probabilities) # take action and get reward, transit to next state next_state, reward, done, _ = env.step(action) # Update statistics stats.episode_rewards[ith_episode] += reward stats.episode_lengths[ith_episode] = t # TD Update best_next_action = np.argmax(Q[next_state]) td_target = reward + discount_factor * Q[next_state][best_next_action] td_delta = td_target - Q[state][action] Q[state][action] += alpha * td_delta # done is True if episode terminated if done: break state = next_state return Q, stats Step #5 : Train the model.Q, stats = qLearning(env, 1000) Step #6 : Plot important statistics.plotting.plot_episode_stats(stats)Conclusion:We see that in the Episode Reward over time plot that the episode rewards progressively increase over time and ultimately levels out at a high reward per episode value which indicates that the agent has learnt to maximize its total reward earned in an episode by behaving optimally at every state.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 37577, "s": 37455, "text": "-greedy policy of is a very simple policy of choosing actions using the current Q-value estimations. It goes as follows :" }, { "code": null, "e": 37644, "s": 37577, "text": "With probability choose the action which has the highest Q-value." }, { "code": null, "e": 37691, "s": 37644, "text": "With probability choose any action at random." }, { "code": null, "e": 37826, "s": 37693, "text": "Now with all the theory required in hand let us take an example. We will use OpenAI’s gym environment to train our Q-Learning model." }, { "code": null, "e": 37851, "s": 37826, "text": "Command to Install gym –" }, { "code": null, "e": 37867, "s": 37851, "text": "pip install gym" }, { "code": null, "e": 38095, "s": 37867, "text": "Before starting with example, you will need some helper code in order to visualize the working of the algorithms. There will be two helper files which need to be downloaded in the working directory. One can find the files here." }, { "code": null, "e": 38133, "s": 38095, "text": "Step # 1 : Import required libraries." }, { "code": "import gymimport itertoolsimport matplotlibimport matplotlib.styleimport numpy as npimport pandas as pdimport sys from collections import defaultdictfrom windy_gridworld import WindyGridworldEnvimport plotting matplotlib.style.use('ggplot')", "e": 38378, "s": 38133, "text": null }, { "code": null, "e": 38413, "s": 38378, "text": " Step #2 : Create gym environment." }, { "code": "env = WindyGridworldEnv()", "e": 38439, "s": 38413, "text": null }, { "code": null, "e": 38475, "s": 38439, "text": " Step #3 : Make the -greedy policy." }, { "code": "def createEpsilonGreedyPolicy(Q, epsilon, num_actions): \"\"\" Creates an epsilon-greedy policy based on a given Q-function and epsilon. Returns a function that takes the state as an input and returns the probabilities for each action in the form of a numpy array of length of the action space(set of possible actions). \"\"\" def policyFunction(state): Action_probabilities = np.ones(num_actions, dtype = float) * epsilon / num_actions best_action = np.argmax(Q[state]) Action_probabilities[best_action] += (1.0 - epsilon) return Action_probabilities return policyFunction", "e": 39148, "s": 38475, "text": null }, { "code": null, "e": 39183, "s": 39148, "text": " Step #4 : Build Q-Learning Model." }, { "code": "def qLearning(env, num_episodes, discount_factor = 1.0, alpha = 0.6, epsilon = 0.1): \"\"\" Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy while improving following an epsilon-greedy policy\"\"\" # Action value function # A nested dictionary that maps # state -> (action -> action-value). Q = defaultdict(lambda: np.zeros(env.action_space.n)) # Keeps track of useful statistics stats = plotting.EpisodeStats( episode_lengths = np.zeros(num_episodes), episode_rewards = np.zeros(num_episodes)) # Create an epsilon greedy policy function # appropriately for environment action space policy = createEpsilonGreedyPolicy(Q, epsilon, env.action_space.n) # For every episode for ith_episode in range(num_episodes): # Reset the environment and pick the first action state = env.reset() for t in itertools.count(): # get probabilities of all actions from current state action_probabilities = policy(state) # choose action according to # the probability distribution action = np.random.choice(np.arange( len(action_probabilities)), p = action_probabilities) # take action and get reward, transit to next state next_state, reward, done, _ = env.step(action) # Update statistics stats.episode_rewards[ith_episode] += reward stats.episode_lengths[ith_episode] = t # TD Update best_next_action = np.argmax(Q[next_state]) td_target = reward + discount_factor * Q[next_state][best_next_action] td_delta = td_target - Q[state][action] Q[state][action] += alpha * td_delta # done is True if episode terminated if done: break state = next_state return Q, stats", "e": 41241, "s": 39183, "text": null }, { "code": null, "e": 41269, "s": 41241, "text": " Step #5 : Train the model." }, { "code": "Q, stats = qLearning(env, 1000)", "e": 41301, "s": 41269, "text": null }, { "code": null, "e": 41339, "s": 41301, "text": " Step #6 : Plot important statistics." }, { "code": "plotting.plot_episode_stats(stats)", "e": 41374, "s": 41339, "text": null }, { "code": null, "e": 41683, "s": 41374, "text": "Conclusion:We see that in the Episode Reward over time plot that the episode rewards progressively increase over time and ultimately levels out at a high reward per episode value which indicates that the agent has learnt to maximize its total reward earned in an episode by behaving optimally at every state." }, { "code": null, "e": 41701, "s": 41683, "text": "VishvajeetRamanuj" }, { "code": null, "e": 41717, "s": 41701, "text": "rajeev0719singh" }, { "code": null, "e": 41743, "s": 41717, "text": "Advanced Computer Subject" }, { "code": null, "e": 41760, "s": 41743, "text": "Machine Learning" }, { "code": null, "e": 41767, "s": 41760, "text": "Python" }, { "code": null, "e": 41784, "s": 41767, "text": "Machine Learning" }, { "code": null, "e": 41882, "s": 41784, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41891, "s": 41882, "text": "Comments" }, { "code": null, "e": 41904, "s": 41891, "text": "Old Comments" }, { "code": null, "e": 41918, "s": 41904, "text": "Decision Tree" }, { "code": null, "e": 41941, "s": 41918, "text": "System Design Tutorial" }, { "code": null, "e": 41985, "s": 41941, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 42023, "s": 41985, "text": "Python | Decision tree implementation" }, { "code": null, "e": 42063, "s": 42023, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 42097, "s": 42063, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 42111, "s": 42097, "text": "Decision Tree" }, { "code": null, "e": 42149, "s": 42111, "text": "Python | Decision tree implementation" }, { "code": null, "e": 42173, "s": 42149, "text": "Search Algorithms in AI" } ]
ARIMA Models with Turing.jl. Using the Probabilistic Programming... | by Saumya Shah | Towards Data Science
Hello! This article is a part of my work done in Julia Season of Contributions (JSoC) 2019. It describes the Julia implementation of ARIMA models using the Probabilistic Programming Language (PPL) Turing.jl, which provides great ease in defining probabilistic models. This aspect of Turing will become more obvious when we look at model definitions later on in the article. Furthermore, Turing supports the use of custom distributions for specifying models. Okay, so let’s get straight onto it! We will use a dataset containing S&P 500 Adjusted Closing Values 1995–2015 with a monthly frequency. The dataset can be downloaded from here (MIT License). The following plot is obtained after running the code above. This is essentially how our data looks like, plotting the value at each time index: We split the data into training and test sets, taking 95% of the data as training set: We can see from the plots that the mean of the series rises towards the end. So, the series is not stationary. This is reinforced by the Augmented Dickey-Fuller (ADF)Test for stationarity: Thus, we difference the time series in an attempt to remove the stationarity: This series seems to have a roughly constant mean, though this does not necessarily mean that the series is stationary. We use the ADF test once again: Success! We can safely assume this series to be stationary since the p-value is so low. We can now move on to selecting the AR and MA terms for our differenced time series with the help of ACF and PACF plots. The ACF and PACF plots obtained for our training data are as shown below: These plots can be construed in the following ways: We can have a first-order autoregressive term since there is positive autocorrelation at lag 1. The PACF plot decays gradually and the ACF plot cuts off sharply after a few lags. This suggests the presence of a moving average term. The order this term should be one since all the lags greater than 1 do not have a significant correlation. Having both AR and MA terms in an ARIMA model is not very common. So, we will not consider this case. From the two points above, it seems that the model is more likely to have a Moving Average term. Nevertheless, we will consider two plausible cases for our ARIMA model: ARIMA(1,1,0) ARIMA(0,1,1) The notation for an ARIMA(p, d, q) model is defined as follows: p: The number of autoregressive terms q: The number of moving average terms d: The order of differencing We implement both of these cases and compare the models using the Akaike information criterion (AIC). This webpage1 is used as a reference for defining the ARIMA(1, 1, 0) and ARIMA(0, 1, 1) models below. The ARIMA(1,1,0) model is defined as follows: @model ARIMA110(x) = begin T = length(x) μ ~ Uniform(-10, 10) φ ~ Uniform(-1, 1) for t in 3:T val = μ + # Drift term. x[t-1] + # ARIMA(0,1,0) portion. φ * (x[t-1] - x[t-2]) # ARIMA(1,0,0) portion. x[t] ~ Normal(val, 1) endend Here, x is the original time series as we have accounted for differencing in the model definition itself. Note that we will have one autoregressive term since p = 1. The ARIMA(1,1,0) model is defined as follows: @model ARIMA011(x) = begin T = length(x) # Set up error vector. ε = Vector(undef, T) x_hat = Vector(undef, T) θ ~ Uniform(-5, 5) # Treat the first x_hat as a parameter to estimate. x_hat[1] ~ Normal(0, 1) ε[1] = x[1] - x_hat[1] for t in 2:T # Predicted value for x. x_hat[t] = x[t-1] - θ * ε[t-1] # Calculate observed error. ε[t] = x[t] - x_hat[t] # Observe likelihood. x[t] ~ Normal(x_hat[t], 1) endend As in the previous model definition, x is the original time series. Note that we will have one Moving Average term since q = 1. A point to be observed here is how the code written in Turing is essentially the same as it would be written on a piece of paper. This is evident from the model definitions above where one can understand these model definitions simply by looking at the code. The chain is sampled using the NUTS sampler. You can check out the docs to know more about NUTS and several other samplers that Turing supports. The code for sampling is as follows: To get the visualisations and the summary statistics for the parameters, you can have a look at them in the code here (Jupyter notebook) or here (.jl file). The Akaike information criterion (AIC) measures the relative “goodness” of different statistical models. Thus, it can be used for the purpose of model comparison. The lower the value of AIC, the better the model is. Also, one must remember that the absolute value of AIC does not have much meaning, the relative values are what matter. Mathematically, AIC is given by: Using this formula, we can calculate the AIC values for our two models. This PDF2 has been used as a reference for calculating the AIC values of the two models. ARIMA(1,1,0) function calculate_aic_ARIMA110(β::Float64, μ:: Float64, σ::Float64, s::Array{Float64, 1}) T = length(s) ε = Vector(undef, T) s_pred = Vector(undef, T) s_pred[1], s_pred[2] = s[1], s[2] ε[1], ε[2] = 0.0, 0.0 for t in 3:T s_pred[t] = μ + s_pred[t-1] + β * (s_pred[t-1] - s_pred[t-2]) ε[t] = s_pred[t] - s[t] end log_likelihood = (-(T - 1)/2)*2*π*σ^2 - (1/σ^2)*sum(ε.^2) - π*σ^2/(1 - β^2) - ((s[1] - μ/(1 - β))^2)/(2*σ^2/(1 - β^2)) aic = -2*log_likelihood + 2 return aicend Using this function, we get the value of AIC for ARIMA(1,1,0) as approximately -299655.26 ARIMA(0,1,1) function calculate_aic_ARIMA011(β::Float64, σ::Float64, s::Array{Float64, 1}) T = length(s) ε = Vector(undef, T) s_pred = Vector(undef, T) s_pred[1] = s[1] ε[1] = 0.0 for t in 2:T s_pred[t] = s[t-1] - β * ε[t-1] ε[t] = s[t] - s_pred[t] end log_likelihood = -(T/2)*log(2*π) - (T/2)*log(σ^2) + (1/2*σ^2)*sum(ε.^2) aic = -2*log_likelihood + 1 return aicend Using this function, we get the value of AIC for ARIMA(1,1,0) as approximately 6.22 x 107. Clearly, we can see that the ARIMA(0,1,1) model is better. This brings to an end my article on ARIMA Models with Turing.jl. I hope you found it interesting. If you have any questions or doubts regarding this article, feel free to contact me at [email protected] or you can tag me on the Julia slack with @Saumya Shah. [1] Introduction to ARIMA models. (2019). Retrieved 26 August 2019, from https://people.duke.edu/~rnau/411arim.htm [2] Thomas, S. (2009). Estimating AR/MA models [Ebook]. Retrieved from http://www.igidr.ac.in/faculty/susant/TEACHING/TSA/print06.pdf
[ { "code": null, "e": 179, "s": 172, "text": "Hello!" }, { "code": null, "e": 630, "s": 179, "text": "This article is a part of my work done in Julia Season of Contributions (JSoC) 2019. It describes the Julia implementation of ARIMA models using the Probabilistic Programming Language (PPL) Turing.jl, which provides great ease in defining probabilistic models. This aspect of Turing will become more obvious when we look at model definitions later on in the article. Furthermore, Turing supports the use of custom distributions for specifying models." }, { "code": null, "e": 667, "s": 630, "text": "Okay, so let’s get straight onto it!" }, { "code": null, "e": 823, "s": 667, "text": "We will use a dataset containing S&P 500 Adjusted Closing Values 1995–2015 with a monthly frequency. The dataset can be downloaded from here (MIT License)." }, { "code": null, "e": 968, "s": 823, "text": "The following plot is obtained after running the code above. This is essentially how our data looks like, plotting the value at each time index:" }, { "code": null, "e": 1055, "s": 968, "text": "We split the data into training and test sets, taking 95% of the data as training set:" }, { "code": null, "e": 1244, "s": 1055, "text": "We can see from the plots that the mean of the series rises towards the end. So, the series is not stationary. This is reinforced by the Augmented Dickey-Fuller (ADF)Test for stationarity:" }, { "code": null, "e": 1322, "s": 1244, "text": "Thus, we difference the time series in an attempt to remove the stationarity:" }, { "code": null, "e": 1474, "s": 1322, "text": "This series seems to have a roughly constant mean, though this does not necessarily mean that the series is stationary. We use the ADF test once again:" }, { "code": null, "e": 1683, "s": 1474, "text": "Success! We can safely assume this series to be stationary since the p-value is so low. We can now move on to selecting the AR and MA terms for our differenced time series with the help of ACF and PACF plots." }, { "code": null, "e": 1757, "s": 1683, "text": "The ACF and PACF plots obtained for our training data are as shown below:" }, { "code": null, "e": 1809, "s": 1757, "text": "These plots can be construed in the following ways:" }, { "code": null, "e": 1905, "s": 1809, "text": "We can have a first-order autoregressive term since there is positive autocorrelation at lag 1." }, { "code": null, "e": 2148, "s": 1905, "text": "The PACF plot decays gradually and the ACF plot cuts off sharply after a few lags. This suggests the presence of a moving average term. The order this term should be one since all the lags greater than 1 do not have a significant correlation." }, { "code": null, "e": 2419, "s": 2148, "text": "Having both AR and MA terms in an ARIMA model is not very common. So, we will not consider this case. From the two points above, it seems that the model is more likely to have a Moving Average term. Nevertheless, we will consider two plausible cases for our ARIMA model:" }, { "code": null, "e": 2432, "s": 2419, "text": "ARIMA(1,1,0)" }, { "code": null, "e": 2445, "s": 2432, "text": "ARIMA(0,1,1)" }, { "code": null, "e": 2509, "s": 2445, "text": "The notation for an ARIMA(p, d, q) model is defined as follows:" }, { "code": null, "e": 2547, "s": 2509, "text": "p: The number of autoregressive terms" }, { "code": null, "e": 2585, "s": 2547, "text": "q: The number of moving average terms" }, { "code": null, "e": 2614, "s": 2585, "text": "d: The order of differencing" }, { "code": null, "e": 2818, "s": 2614, "text": "We implement both of these cases and compare the models using the Akaike information criterion (AIC). This webpage1 is used as a reference for defining the ARIMA(1, 1, 0) and ARIMA(0, 1, 1) models below." }, { "code": null, "e": 2864, "s": 2818, "text": "The ARIMA(1,1,0) model is defined as follows:" }, { "code": null, "e": 3182, "s": 2864, "text": "@model ARIMA110(x) = begin T = length(x) μ ~ Uniform(-10, 10) φ ~ Uniform(-1, 1) for t in 3:T val = μ + # Drift term. x[t-1] + # ARIMA(0,1,0) portion. φ * (x[t-1] - x[t-2]) # ARIMA(1,0,0) portion. x[t] ~ Normal(val, 1) endend" }, { "code": null, "e": 3348, "s": 3182, "text": "Here, x is the original time series as we have accounted for differencing in the model definition itself. Note that we will have one autoregressive term since p = 1." }, { "code": null, "e": 3394, "s": 3348, "text": "The ARIMA(1,1,0) model is defined as follows:" }, { "code": null, "e": 3870, "s": 3394, "text": "@model ARIMA011(x) = begin T = length(x) # Set up error vector. ε = Vector(undef, T) x_hat = Vector(undef, T) θ ~ Uniform(-5, 5) # Treat the first x_hat as a parameter to estimate. x_hat[1] ~ Normal(0, 1) ε[1] = x[1] - x_hat[1] for t in 2:T # Predicted value for x. x_hat[t] = x[t-1] - θ * ε[t-1] # Calculate observed error. ε[t] = x[t] - x_hat[t] # Observe likelihood. x[t] ~ Normal(x_hat[t], 1) endend" }, { "code": null, "e": 3998, "s": 3870, "text": "As in the previous model definition, x is the original time series. Note that we will have one Moving Average term since q = 1." }, { "code": null, "e": 4257, "s": 3998, "text": "A point to be observed here is how the code written in Turing is essentially the same as it would be written on a piece of paper. This is evident from the model definitions above where one can understand these model definitions simply by looking at the code." }, { "code": null, "e": 4439, "s": 4257, "text": "The chain is sampled using the NUTS sampler. You can check out the docs to know more about NUTS and several other samplers that Turing supports. The code for sampling is as follows:" }, { "code": null, "e": 4596, "s": 4439, "text": "To get the visualisations and the summary statistics for the parameters, you can have a look at them in the code here (Jupyter notebook) or here (.jl file)." }, { "code": null, "e": 4965, "s": 4596, "text": "The Akaike information criterion (AIC) measures the relative “goodness” of different statistical models. Thus, it can be used for the purpose of model comparison. The lower the value of AIC, the better the model is. Also, one must remember that the absolute value of AIC does not have much meaning, the relative values are what matter. Mathematically, AIC is given by:" }, { "code": null, "e": 5126, "s": 4965, "text": "Using this formula, we can calculate the AIC values for our two models. This PDF2 has been used as a reference for calculating the AIC values of the two models." }, { "code": null, "e": 5139, "s": 5126, "text": "ARIMA(1,1,0)" }, { "code": null, "e": 5730, "s": 5139, "text": "function calculate_aic_ARIMA110(β::Float64, μ:: Float64, σ::Float64, s::Array{Float64, 1}) T = length(s) ε = Vector(undef, T) s_pred = Vector(undef, T) s_pred[1], s_pred[2] = s[1], s[2] ε[1], ε[2] = 0.0, 0.0 for t in 3:T s_pred[t] = μ + s_pred[t-1] + β * (s_pred[t-1] - s_pred[t-2]) ε[t] = s_pred[t] - s[t] end log_likelihood = (-(T - 1)/2)*2*π*σ^2 - (1/σ^2)*sum(ε.^2) - π*σ^2/(1 - β^2) - ((s[1] - μ/(1 - β))^2)/(2*σ^2/(1 - β^2)) aic = -2*log_likelihood + 2 return aicend" }, { "code": null, "e": 5820, "s": 5730, "text": "Using this function, we get the value of AIC for ARIMA(1,1,0) as approximately -299655.26" }, { "code": null, "e": 5833, "s": 5820, "text": "ARIMA(0,1,1)" }, { "code": null, "e": 6307, "s": 5833, "text": "function calculate_aic_ARIMA011(β::Float64, σ::Float64, s::Array{Float64, 1}) T = length(s) ε = Vector(undef, T) s_pred = Vector(undef, T) s_pred[1] = s[1] ε[1] = 0.0 for t in 2:T s_pred[t] = s[t-1] - β * ε[t-1] ε[t] = s[t] - s_pred[t] end log_likelihood = -(T/2)*log(2*π) - (T/2)*log(σ^2) + (1/2*σ^2)*sum(ε.^2) aic = -2*log_likelihood + 1 return aicend" }, { "code": null, "e": 6398, "s": 6307, "text": "Using this function, we get the value of AIC for ARIMA(1,1,0) as approximately 6.22 x 107." }, { "code": null, "e": 6457, "s": 6398, "text": "Clearly, we can see that the ARIMA(0,1,1) model is better." }, { "code": null, "e": 6715, "s": 6457, "text": "This brings to an end my article on ARIMA Models with Turing.jl. I hope you found it interesting. If you have any questions or doubts regarding this article, feel free to contact me at [email protected] or you can tag me on the Julia slack with @Saumya Shah." }, { "code": null, "e": 6830, "s": 6715, "text": "[1] Introduction to ARIMA models. (2019). Retrieved 26 August 2019, from https://people.duke.edu/~rnau/411arim.htm" } ]
Palindrome Partitioning II in C++
Suppose we have a string s, we have to find the number of cuts needed to divide this string into different substring and each part is a palindrome. So if the string is like “ababba”, then this will take 2 cuts. [aba|bb|a] To solve this, we will follow these steps − n := number of characters in the string s n := number of characters in the string s create one array called res of size n + 1 create one array called res of size n + 1 res[n] := -1 res[n] := -1 for i in range n – 1 down to 0res[i] := n – i – 1for j in range i to nif substring of a, from index i, to j – i is a palindrome, thenres[i] := min of res[i] and 1 + res[j + 1] for i in range n – 1 down to 0 res[i] := n – i – 1 res[i] := n – i – 1 for j in range i to nif substring of a, from index i, to j – i is a palindrome, thenres[i] := min of res[i] and 1 + res[j + 1] for j in range i to n if substring of a, from index i, to j – i is a palindrome, thenres[i] := min of res[i] and 1 + res[j + 1] if substring of a, from index i, to j – i is a palindrome, then res[i] := min of res[i] and 1 + res[j + 1] res[i] := min of res[i] and 1 + res[j + 1] return res[0] return res[0] Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; bool isPalindrome(string A) { int left = 0; int right = A.size()-1; while(left < right) { if(A[left] != A[right]) { return 0; } left++; right--; } return 1; } int solve(string A) { int n = A.size(); vector<int>result(n+1); result[n] = -1; for(int i=n-1;i>=0;i--) { result[i] = n-i-1; for(int j=i;j<n;j++) { if(isPalindrome(A.substr(i, j-i+1))) { result[i] = min(result[i], 1 + result[j+1]); } } } return result[0]; } class Solution { public: int minCut(string s) { return solve(s); } }; main(){ Solution ob; cout << (ob.minCut("ababba")); } “ababba” 2
[ { "code": null, "e": 1284, "s": 1062, "text": "Suppose we have a string s, we have to find the number of cuts needed to divide this string into different substring and each part is a palindrome. So if the string is like “ababba”, then this will take 2 cuts. [aba|bb|a]" }, { "code": null, "e": 1328, "s": 1284, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1370, "s": 1328, "text": "n := number of characters in the string s" }, { "code": null, "e": 1412, "s": 1370, "text": "n := number of characters in the string s" }, { "code": null, "e": 1454, "s": 1412, "text": "create one array called res of size n + 1" }, { "code": null, "e": 1496, "s": 1454, "text": "create one array called res of size n + 1" }, { "code": null, "e": 1509, "s": 1496, "text": "res[n] := -1" }, { "code": null, "e": 1522, "s": 1509, "text": "res[n] := -1" }, { "code": null, "e": 1698, "s": 1522, "text": "for i in range n – 1 down to 0res[i] := n – i – 1for j in range i to nif substring of a, from index i, to j – i is a palindrome, thenres[i] := min of res[i] and 1 + res[j + 1]" }, { "code": null, "e": 1729, "s": 1698, "text": "for i in range n – 1 down to 0" }, { "code": null, "e": 1749, "s": 1729, "text": "res[i] := n – i – 1" }, { "code": null, "e": 1769, "s": 1749, "text": "res[i] := n – i – 1" }, { "code": null, "e": 1896, "s": 1769, "text": "for j in range i to nif substring of a, from index i, to j – i is a palindrome, thenres[i] := min of res[i] and 1 + res[j + 1]" }, { "code": null, "e": 1918, "s": 1896, "text": "for j in range i to n" }, { "code": null, "e": 2024, "s": 1918, "text": "if substring of a, from index i, to j – i is a palindrome, thenres[i] := min of res[i] and 1 + res[j + 1]" }, { "code": null, "e": 2088, "s": 2024, "text": "if substring of a, from index i, to j – i is a palindrome, then" }, { "code": null, "e": 2131, "s": 2088, "text": "res[i] := min of res[i] and 1 + res[j + 1]" }, { "code": null, "e": 2174, "s": 2131, "text": "res[i] := min of res[i] and 1 + res[j + 1]" }, { "code": null, "e": 2188, "s": 2174, "text": "return res[0]" }, { "code": null, "e": 2202, "s": 2188, "text": "return res[0]" }, { "code": null, "e": 2274, "s": 2202, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2285, "s": 2274, "text": " Live Demo" }, { "code": null, "e": 3007, "s": 2285, "text": "#include <bits/stdc++.h>\nusing namespace std;\nbool isPalindrome(string A) {\n int left = 0;\n int right = A.size()-1;\n while(left < right) {\n if(A[left] != A[right]) {\n return 0;\n }\n left++;\n right--;\n }\n return 1;\n}\nint solve(string A) {\n int n = A.size();\n vector<int>result(n+1);\n result[n] = -1;\n for(int i=n-1;i>=0;i--) {\n result[i] = n-i-1;\n for(int j=i;j<n;j++) {\n if(isPalindrome(A.substr(i, j-i+1))) {\n result[i] = min(result[i], 1 + result[j+1]);\n }\n }\n }\n return result[0];\n}\nclass Solution {\n public:\n int minCut(string s) {\n return solve(s);\n }\n};\nmain(){\n Solution ob;\n cout << (ob.minCut(\"ababba\"));\n}" }, { "code": null, "e": 3016, "s": 3007, "text": "“ababba”" }, { "code": null, "e": 3018, "s": 3016, "text": "2" } ]
Difference between the shortest and second shortest path in an Unweighted Bidirectional Graph - GeeksforGeeks
26 Oct, 2021 Given an unweighted bidirectional graph containing N nodes and M edges represented by an array arr[][2]. The task is to find the difference in length of the shortest and second shortest paths from node 1 to N. If the second shortest path does not exist, print 0. Note: The graph is connected, does not contain multiple edges and self loops. (2<=N<=20) Examples: Input: N = 4, M = 4, arr[M][2]={{1, 2}, {2, 3}, {3, 4}, {1, 4}}Output: 2Explanation: The shortest path is 1->4 and the second shortest path is 1->2->3->4. Hence, the difference is 2. Input: N = 6, M = 8, arr[M][2]={{1, 2}, {1, 3}, {2, 6}, {2, 3}, {2, 4}, {3, 4}, {3, 5}, {4, 6}}Output:1 Approach: The idea is to Depth First Search to find all possible paths and store them in vector and sort the vector and find the difference between the shortest and the second shortest path. Follow the steps below to solve the problem: Define a function dfs(vector<vector<int> >& graph, int s, int e, vector<int> vis, int count, vector<int>& dp) and perform the following steps:If s is equal to e, then it means that the current path is one of the possible ones, push the value of count in the vector dp[] and return.Iterate over the range [0, graph[s]] using the variable i and performing the following steps:If vis[i] is not equal to 1, then set the value of vis[i] to 1 and call the function dfs(graph, i, e, vis, count+1, dp) to find other possible paths and set the value of vis[0] again back to 0. If s is equal to e, then it means that the current path is one of the possible ones, push the value of count in the vector dp[] and return. Iterate over the range [0, graph[s]] using the variable i and performing the following steps:If vis[i] is not equal to 1, then set the value of vis[i] to 1 and call the function dfs(graph, i, e, vis, count+1, dp) to find other possible paths and set the value of vis[0] again back to 0. If vis[i] is not equal to 1, then set the value of vis[i] to 1 and call the function dfs(graph, i, e, vis, count+1, dp) to find other possible paths and set the value of vis[0] again back to 0. Initialize a 2-D vector graph[][] with N number of rows to store the vertices connected from each vertex. Iterate over the range [0, M] using the variable i and perform the following steps:Push the value of b-1 in the vector graph[][] in row a-1.Push the value of a-1 in the vector graph[][] in row b-1. Push the value of b-1 in the vector graph[][] in row a-1. Push the value of a-1 in the vector graph[][] in row b-1. Initialize a vector vis[] of size N to keep track of visited nodes. Initialize a vector dp[] to store the length of all possible paths. Call the function dfs(graph, 0, N-1, vis, 0, dp) to find all possible paths and store them in the vector dp[]. Sort the vector dp[] in ascending order. If the size of vector dp[] is greater than 1, then return the value dp[1]-dp[0] else return 0 as the answer. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // DFS function to find all possible paths.void dfs(vector<vector<int> >& graph, int s, int e, vector<int> v, int count, vector<int>& dp){ if (s == e) { // Push the number of nodes required for // one of the possible paths dp.push_back(count); return; } for (auto i : graph[s]) { if (v[i] != 1) { // Mark the node as visited and // call the function to search for // possible paths and unmark the node. v[i] = 1; dfs(graph, i, e, v, count + 1, dp); v[i] = 0; } }} // Function to find the difference between the// shortest and second shortest pathvoid findDifference(int n, int m, int arr[][2]){ // Construct the graph vector<vector<int> > graph(n, vector<int>()); for (int i = 0; i < m; i++) { int a, b; a = arr[i][0]; b = arr[i][1]; graph[a - 1].push_back(b - 1); graph[b - 1].push_back(a - 1); } // Vector to mark the nodes as visited or not. vector<int> v(n, 0); // Vector to store the count of all possible paths. vector<int> dp; // Mark the starting node as visited. v[0] = 1; // Function to find all possible paths. dfs(graph, 0, n - 1, v, 0, dp); // Sort the vector sort(dp.begin(), dp.end()); // Print the difference if (dp.size() != 1) cout << dp[1] - dp[0]; else cout << 0;} // Driver Codeint main(){ int n, m; n = 6; m = 8; int arr[m][2] = { { 1, 2 }, { 1, 3 }, { 2, 6 }, { 2, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 6 } }; findDifference(n, m, arr); return 0;} // Java program for the above approachimport java.util.*;public class Main{ // DFS function to find all possible paths. static void dfs(Vector<Vector<Integer>> graph, int s, int e, int[] v, int count, Vector<Integer> dp) { if (s == e) { // Push the number of nodes required for // one of the possible paths dp.add(count); return; } for(int i : graph.get(s)) { if (v[i] != 1) { // Mark the node as visited and // call the function to search for // possible paths and unmark the node. v[i] = 1; dfs(graph, i, e, v, count + 1, dp); v[i] = 0; } } } // Function to find the difference between the // shortest and second shortest path static void findDifference(int n, int m, int[][] arr) { // Construct the graph Vector<Vector<Integer>> graph = new Vector<Vector<Integer>>(); for(int i = 0; i < n; i++) { graph.add(new Vector<Integer>()); } for (int i = 0; i < m; i++) { int a, b; a = arr[i][0]; b = arr[i][1]; graph.get(a - 1).add(b - 1); graph.get(b - 1).add(a - 1); } // Vector to mark the nodes as visited or not. int[] v = new int[n]; Arrays.fill(v, 0); // Vector to store the count of all possible paths. Vector<Integer> dp = new Vector<Integer>(); // Mark the starting node as visited. v[0] = 1; // Function to find all possible paths. dfs(graph, 0, n - 1, v, 0, dp); // Sort the vector Collections.sort(dp); // Print the difference if (dp.size() != 1) System.out.print(dp.get(1) - dp.get(0)); else System.out.print(0); } public static void main(String[] args) { int n, m; n = 6; m = 8; int[][] arr = { { 1, 2 }, { 1, 3 }, { 2, 6 }, { 2, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 6 } }; findDifference(n, m, arr); }} // This code is contributed by mukesh07. # Python3 program for the above approach # DFS function to find all possible paths.def dfs(graph, s, e, v, count, dp): if (s == e): # Push the number of nodes required for # one of the possible paths dp.append(count) return for i in graph[s]: if (v[i] != 1): # Mark the node as visited and # call the function to search for # possible paths and unmark the node. v[i] = 1 dfs(graph, i, e, v, count + 1, dp) v[i] = 0 # Function to find the difference between the# shortest and second shortest pathdef findDifference(n, m, arr): # Construct the graph graph = [] for i in range(n): graph.append([]) for i in range(m): a = arr[i][0] b = arr[i][1] graph[a - 1].append(b - 1) graph[b - 1].append(a - 1) # Vector to mark the nodes as visited or not. v = [0]*(n) # Vector to store the count of all possible paths. dp = [] # Mark the starting node as visited. v[0] = 1 # Function to find all possible paths. dfs(graph, 0, n - 1, v, 0, dp) # Sort the vector dp.sort() # Print the difference if (len(dp) != 1): print(dp[1] - dp[0], end = "") else: print(0, end = "") # Driver Coden = 6m = 8arr = [ [1, 2], [1, 3], [2, 6], [2, 3], [2, 4], [3, 4], [3, 5], [4, 6],] findDifference(n, m, arr) # This code is contributed by divyesh072019. // C# program for the above approachusing System;using System.Collections.Generic;class GFG { // DFS function to find all possible paths. static void dfs(List<List<int>> graph, int s, int e, List<int> v, int count, List<int> dp) { if (s == e) { // Push the number of nodes required for // one of the possible paths dp.Add(count); return; } foreach(int i in graph[s]) { if (v[i] != 1) { // Mark the node as visited and // call the function to search for // possible paths and unmark the node. v[i] = 1; dfs(graph, i, e, v, count + 1, dp); v[i] = 0; } } } // Function to find the difference between the // shortest and second shortest path static void findDifference(int n, int m, int[,] arr) { // Construct the graph List<List<int>> graph = new List<List<int>>(); for(int i = 0; i < n; i++) { graph.Add(new List<int>()); } for (int i = 0; i < m; i++) { int a, b; a = arr[i,0]; b = arr[i,1]; graph[a - 1].Add(b - 1); graph[b - 1].Add(a - 1); } // Vector to mark the nodes as visited or not. List<int> v = new List<int>(); for(int i = 0; i < n; i++) { v.Add(0); } // Vector to store the count of all possible paths. List<int> dp = new List<int>(); // Mark the starting node as visited. v[0] = 1; // Function to find all possible paths. dfs(graph, 0, n - 1, v, 0, dp); // Sort the vector dp.Sort(); // Print the difference if (dp.Count != 1) Console.Write(dp[1] - dp[0]); else Console.Write(0); } static void Main() { int n, m; n = 6; m = 8; int[,] arr = { { 1, 2 }, { 1, 3 }, { 2, 6 }, { 2, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 6 } }; findDifference(n, m, arr); }} // Ths code is contributed by decode2207. <script>// Javascript program for the above approach // DFS function to find all possible paths.function dfs(graph, s, e, v, count, dp) { if (s == e) { // Push the number of nodes required for // one of the possible paths dp.push(count); return; } for (let i of graph[s]) { if (v[i] != 1) { // Mark the node as visited and // call the function to search for // possible paths and unmark the node. v[i] = 1; dfs(graph, i, e, v, count + 1, dp); v[i] = 0; } }} // Function to find the difference between the// shortest and second shortest pathfunction findDifference(n, m, arr){ // Construct the graph let graph = new Array(n).fill(0).map(() => []); for (let i = 0; i < m; i++) { let a, b; a = arr[i][0]; b = arr[i][1]; graph[a - 1].push(b - 1); graph[b - 1].push(a - 1); } // Vector to mark the nodes as visited or not. let v = new Array(n).fill(0); // Vector to store the count of all possible paths. let dp = []; // Mark the starting node as visited. v[0] = 1; // Function to find all possible paths. dfs(graph, 0, n - 1, v, 0, dp); // Sort the vector dp.sort((a, b) => a - b); // Print the difference if (dp.length != 1) document.write(dp[1] - dp[0]); else document.write(0);} // Driver Codelet n, m;n = 6;m = 8;let arr = [ [1, 2], [1, 3], [2, 6], [2, 3], [2, 4], [3, 4], [3, 5], [4, 6],]; findDifference(n, m, arr); // This code is contributed by gfgking.</script> 1 Time Complexity: O(2^N)Auxiliary Space: O(N) Efficient Approach: Using the fact that the second shortest path can not contain all the edges same as that in the shortest path. Remove each edge of the shortest path one at a time and keep finding the shortest path, then one of them has to be the required second shortest path. Use Breadth First Search to find the solution optimally. Follow the steps below to solve the problem: Define a function get_edges(int s, vector<int>& edges, vector<int> p) and perform the following steps:If s is equal to -1, then return.Call the function get_edges(p[s], edges, p) to find all the edges along the shortest path.Push the value of s in the vector edges[]. If s is equal to -1, then return. Call the function get_edges(p[s], edges, p) to find all the edges along the shortest path. Push the value of s in the vector edges[]. Define a function dist_helper(vector<vector<int> > graph, vector<int>& d, int v1, int v2, int N) and perform the following steps:Initialize the vector vis[] to keep track of visited nodes.Initialize a queue of pairs q[] to do the Breadth First Search and find the path.Enqueue the pair {0, 0} into the queue of pairs q[].Mark the value of vis[0] as 1(visited).Iterate in a while loop till the queue of pairs q[] is not empty.Initialize a variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue.If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]. Initialize the vector vis[] to keep track of visited nodes. Initialize a queue of pairs q[] to do the Breadth First Search and find the path. Enqueue the pair {0, 0} into the queue of pairs q[]. Mark the value of vis[0] as 1(visited). Iterate in a while loop till the queue of pairs q[] is not empty.Initialize a variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue.If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]. Initialize a variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[]. Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue.If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]. If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue. If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]. Define a function dist(vector<vector<int> > graph, vector<int>& d, vector<int> &p, int N) and perform the following steps:Initialize the vector vis[] to keep track of visited nodes.Initialize a queue of pairs q[] to do the Breadth First Search and find the path.Enqueue the pair {0, 0} into the queue of pairs q[].Mark the value of vis[0] as 1(visited).Iterate in a while loop till the queue of pairs q[] is not empty.Initialize the variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]. Initialize the vector vis[] to keep track of visited nodes. Initialize a queue of pairs q[] to do the Breadth First Search and find the path. Enqueue the pair {0, 0} into the queue of pairs q[]. Mark the value of vis[0] as 1(visited). Iterate in a while loop till the queue of pairs q[] is not empty.Initialize the variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]. Initialize the variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[]. Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]. If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]. Initialize a 2-D vector graph[][] with N number of rows to store the vertices connected from each vertex. Iterate over the range [0, M] using the variable i and perform the following steps:Push the value of b-1 in the vector graph[][] in row a-1.Push the value of a-1 in the vector graph[][] in row b-1. Push the value of b-1 in the vector graph[][] in row a-1. Push the value of a-1 in the vector graph[][] in row b-1. Initialize the vectors p[] and d[] of size N to keep track of parent nodes and the length of the paths. Call the function dist(graph, d, p, N) to find the length of the shortest path. Initialize a vector distances[] to store the length of all possible paths. Push the value of d[N-1] in the vector distances[]. Initialize a vector edges[] to get all the edges along the shortest path. Call the function get_edges(N-1, edges, p) to find all the edges along the shortest path. Iterate over the range [0, edges.size()-1] using the variable i and perform the following steps:Call the function dist_helper(graph, d, edges[i], edges[i+1], N) to find all the edges along the shortest path.Push the value of d[N-1] in the vector distances[]. Call the function dist_helper(graph, d, edges[i], edges[i+1], N) to find all the edges along the shortest path. Push the value of d[N-1] in the vector distances[]. Sort the vector distances[] in ascending order. If the size of vector distances[] is greater than 1, then return the value distances[1]-distances[0] else return 0 as the answer. Below is the implementation of the above approach. C++ Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to get all the edges in// the shortest pathvoid get_edges(int s, vector<int>& edges, vector<int> p){ if (s == -1) return; get_edges(p[s], edges, p); edges.push_back(s);} // Calculate the shortest distance// after removing an edge between// v1 and v2void dist_helper(vector<vector<int> > graph, vector<int>& d, int v1, int v2, int n){ // Vector to mark the nodes visited vector<int> v(n, 0); // For BFS queue<pair<int, int> > q; q.push(make_pair(0, 0)); v[0] = 1; // Iterate over the range while (!q.empty()) { auto a = q.front(); q.pop(); for (int i : graph[a.first]) { if ((i == v1 && a.first == v2) || (i == v2 && a.first == v1)) continue; if (v[i] == 0) { d[i] = 1 + a.second; v[i] = 1; q.push(make_pair(i, d[i])); } } }} // Calculates the shortest distances and// maintain a parent arrayvoid dist(vector<vector<int> > graph, vector<int>& d, vector<int>& p, int n){ // Vector to mark the nodes visited vector<int> v(n, 0); // For BFS queue<pair<int, int> > q; q.push(make_pair(0, 0)); v[0] = 1; // Iterate over the range while (!q.empty()) { auto a = q.front(); q.pop(); for (int i : graph[a.first]) { if (v[i] == 0) { p[i] = a.first; d[i] = 1 + a.second; v[i] = 1; q.push(make_pair(i, d[i])); } } }} // Function to find the difference between the// shortest and second shortest pathvoid findDifference(int n, int m, int arr[][2]){ // Initializing and constructing the graph vector<vector<int> > graph(n, vector<int>()); for (int i = 0; i < m; i++) { int a, b; a = arr[i][0]; b = arr[i][1]; graph[a - 1].push_back(b - 1); graph[b - 1].push_back(a - 1); } // Initializing the arrays vector<int> p(n, -1); vector<int> d(n, 1e9); // Calculate the shortest path dist(graph, d, p, n); // Vector to store the lengths // of possible paths vector<int> distances; distances.push_back(d[n - 1]); vector<int> edges; // Get all the edges along the shortest path get_edges(n - 1, edges, p); // Iterate over the range for (int i = 0; i + 1 < edges.size(); i++) { // Calculate shortest distance after // removing the edge dist_helper(graph, d, edges[i], edges[i + 1], n); distances.push_back(d[n - 1]); } // Sort the paths in ascending order sort(distances.begin(), distances.end()); if (distances.size() == 1) cout << 0 << endl; else cout << distances[1] - distances[0] << endl;} // Driver Codeint main(){ int n, m; n = 6; m = 8; int arr[m][2] = { { 1, 2 }, { 1, 3 }, { 2, 6 }, { 2, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 6 } }; findDifference(n, m, arr); return 0;} # Python3 program for the above approach edges, d, p = [], [], [] # Function to get all the edges in# the shortest pathdef get_edges(s): global edges, d, p if s == -1: return get_edges(p[s]) edges.append(s) # Calculate the shortest distance# after removing an edge between# v1 and v2def dist_helper(graph, v1, v2, n): global edges, d, p # Vector to mark the nodes visited v = [0]*(n) # For BFS q = [] q.append([0, 0]) v[0] = 1 # Iterate over the range while len(q) > 0: a = q[0] q.pop(0) for i in graph[a[0]]: if (i == v1 and a[0] == v2) or (i == v2 and a[0] == v1): continue if v[i] == 0: d[i] = 1 + a[1] v[i] = 1 q.append([i, d[i]]) # Calculates the shortest distances and# maintain a parent arraydef dist(graph, n): global edges, d, p # Vector to mark the nodes visited v = [0]*(n) # For BFS q = [] q.append([0, 0]) v[0] = 1 # Iterate over the range while len(q) > 0: a = q[0] q.pop(0) for i in graph[a[0]]: if v[i] == 0: p[i] = a[0] d[i] = 1 + a[1] v[i] = 1 q.append([i, d[i]]) # Function to find the difference between the# shortest and second shortest pathdef findDifference(n, m, arr): global edges, d, p # Initializing and constructing the graph graph = [] for i in range(n): graph.append([]) for i in range(m): a = arr[i][0] b = arr[i][1] graph[a - 1].append(b - 1) graph[b - 1].append(a - 1) # Initializing the arrays p = [-1]*(n) d = [1e9]*(n) # Calculate the shortest path dist(graph, n) # Vector to store the lengths # of possible paths distances = [] distances.append(d[n - 1]) edges = [] # Get all the edges along the shortest path get_edges(n - 1) # Iterate over the range i = 0 while i + 1 < len(edges): # Calculate shortest distance after # removing the edge dist_helper(graph, edges[i], edges[i + 1], n) distances.append(d[n - 1]) i+=1 # Sort the paths in ascending order distances.sort() if len(distances) == 1: print(0) else: print(distances[1] - distances[0]) n = 6;m = 8;arr = [ [ 1, 2 ], [ 1, 3 ], [ 2, 6 ], [ 2, 3 ], [ 2, 4 ], [ 3, 4 ], [ 3, 5 ], [ 4, 6 ] ] findDifference(n, m, arr) # This code is contributed by suresh07. // C# program for the above approachusing System;using System.Collections.Generic;class GFG { static List<int> edges = new List<int>(); static List<int> d = new List<int>(); static List<int> p = new List<int>(); // Function to get all the edges in // the shortest path static void get_edges(int s) { if (s == -1) return; get_edges(p[s]); edges.Add(s); } // Calculate the shortest distance // after removing an edge between // v1 and v2 static void dist_helper(List<List<int>> graph, int v1, int v2, int n) { // Vector to mark the nodes visited List<int> v = new List<int>(); for(int i = 0; i < n; i++) { v.Add(0); } // For BFS List<Tuple<int,int>> q = new List<Tuple<int,int>>(); q.Add(new Tuple<int,int>(0, 0)); v[0] = 1; // Iterate over the range while (q.Count > 0) { Tuple<int,int> a = q[0]; q.RemoveAt(0); for (int i = 0; i < graph[a.Item1].Count; i++) { if ((graph[a.Item1][i] == v1 && a.Item1 == v2) || (graph[a.Item1][i] == v2 && a.Item1 == v1)) continue; if (v[graph[a.Item1][i]] == 0) { d[graph[a.Item1][i]] = 1 + a.Item2; v[graph[a.Item1][i]] = 1; q.Add(new Tuple<int,int>(graph[a.Item1][i], d[graph[a.Item1][i]])); } } } } // Calculates the shortest distances and // maintain a parent array static void dist(List<List<int>> graph, int n) { // Vector to mark the nodes visited List<int> v = new List<int>(); for(int i = 0; i < n; i++) { v.Add(0); } // For BFS List<Tuple<int,int>> q = new List<Tuple<int,int>>(); q.Add(new Tuple<int,int>(0, 0)); v[0] = 1; // Iterate over the range while (q.Count > 0) { Tuple<int,int> a = q[0]; q.RemoveAt(0); for (int i = 0; i < graph[a.Item1].Count; i++) { if (v[graph[a.Item1][i]] == 0) { p[graph[a.Item1][i]] = a.Item1; d[graph[a.Item1][i]] = 1 + a.Item2; v[graph[a.Item1][i]] = 1; q.Add(new Tuple<int,int>(graph[a.Item1][i], d[graph[a.Item1][i]])); } } } } // Function to find the difference between the // shortest and second shortest path static void findDifference(int n, int m, int[,] arr) { // Initializing and constructing the graph List<List<int>> graph = new List<List<int>>(); for(int i = 0; i < n; i++) { graph.Add(new List<int>()); } for (int i = 0; i < m; i++) { int a, b; a = arr[i,0]; b = arr[i,1]; graph[a - 1].Add(b - 1); graph[b - 1].Add(a - 1); } // Initializing the arrays for(int i = 0; i < n; i++) { p.Add(-1); d.Add(1000000000); } // Calculate the shortest path dist(graph, n); // Vector to store the lengths // of possible paths List<int> distances = new List<int>(); distances.Add(d[n - 1]); // Get all the edges along the shortest path get_edges(n - 1); // Iterate over the range for (int i = 0; i + 1 < edges.Count; i++) { // Calculate shortest distance after // removing the edge dist_helper(graph, edges[i], edges[i + 1], n); distances.Add(d[n - 1]); } // Sort the paths in ascending order distances.Sort(); if (distances.Count == 1) { Console.WriteLine(0); } else { Console.WriteLine((distances[1] - distances[0])); } } // Driver code static void Main() { int n, m; n = 6; m = 8; int[,] arr = { { 1, 2 }, { 1, 3 }, { 2, 6 }, { 2, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 6 } }; findDifference(n, m, arr); }} // This code is contributed by divyeshrabadiya07. <script> // Javascript program for the above approach let edges = [], d = [], p = []; // Function to get all the edges in // the shortest path function get_edges(s) { if (s == -1) return; get_edges(p[s]); edges.push(s); } // Calculate the shortest distance // after removing an edge between // v1 and v2 function dist_helper(graph, v1, v2, n) { // Vector to mark the nodes visited let v = []; for(let i = 0; i < n; i++) { v.push(0); } // For BFS let q = []; q.push([0, 0]); v[0] = 1; // Iterate over the range while (q.length > 0) { let a = q[0]; q.shift(); for (let i = 0; i < graph[a[0]].length; i++) { if ((graph[a[0]][i] == v1 && a[0] == v2) || (graph[a[0]][i] == v2 && a[0] == v1)) continue; if (v[graph[a[0]][i]] == 0) { d[graph[a[0]][i]] = 1 + a[1]; v[graph[a[0]][i]] = 1; q.push([graph[a[0]][i], d[graph[a[0]][i]]]); } } } } // Calculates the shortest distances and // maintain a parent array function dist(graph, n) { // Vector to mark the nodes visited let v = []; for(let i = 0; i < n; i++) { v.push(0); } // For BFS let q = []; q.push([0, 0]); v[0] = 1; // Iterate over the range while (q.length > 0) { let a = q[0]; q.shift(); for (let i = 0; i < graph[a[0]].length; i++) { if (v[graph[a[0]][i]] == 0) { p[graph[a[0]][i]] = a[0]; d[graph[a[0]][i]] = 1 + a[1]; v[graph[a[0]][i]] = 1; q.push([graph[a[0]][i], d[graph[a[0]][i]]]); } } } } // Function to find the difference between the // shortest and second shortest path function findDifference(n, m, arr) { // Initializing and constructing the graph let graph = []; for(let i = 0; i < n; i++) { graph.push([]); } for (let i = 0; i < m; i++) { let a, b; a = arr[i][0]; b = arr[i][1]; graph[a - 1].push(b - 1); graph[b - 1].push(a - 1); } // Initializing the arrays for(let i = 0; i < n; i++) { p.push(-1); d.push(1e9); } // Calculate the shortest path dist(graph, n); // Vector to store the lengths // of possible paths let distances = []; distances.push(d[n - 1]); // Get all the edges along the shortest path get_edges(n - 1); // Iterate over the range for (let i = 0; i + 1 < edges.length; i++) { // Calculate shortest distance after // removing the edge dist_helper(graph, edges[i], edges[i + 1], n); distances.push(d[n - 1]); } // Sort the paths in ascending order distances.sort(function(a, b){return a - b}); if (distances.length == 1) { document.write(0 + "</br>"); } else { document.write((distances[1] - distances[0]) + "</br>"); } } let n, m; n = 6; m = 8; let arr = [ [ 1, 2 ], [ 1, 3 ], [ 2, 6 ], [ 2, 3 ], [ 2, 4 ], [ 3, 4 ], [ 3, 5 ], [ 4, 6 ] ]; findDifference(n, m, arr); // This code is contributed by rameshtravel07.</script> 1 Time Complexity: O(N*M)Auxiliary Space: O(N) gfgking divyesh072019 decode2207 mukesh07 suresh07 rameshtravel07 divyeshrabadiya07 Shortest Path Graph Recursion Recursion Graph Shortest Path Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best First Search (Informed Search) Find if there is a path between two vertices in a directed graph Eulerian path and circuit for undirected graph Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm) Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS) Write a program to print all permutations of a given string Program for Tower of Hanoi Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Sum of the digits of a given number
[ { "code": null, "e": 25066, "s": 25038, "text": "\n26 Oct, 2021" }, { "code": null, "e": 25329, "s": 25066, "text": "Given an unweighted bidirectional graph containing N nodes and M edges represented by an array arr[][2]. The task is to find the difference in length of the shortest and second shortest paths from node 1 to N. If the second shortest path does not exist, print 0." }, { "code": null, "e": 25418, "s": 25329, "text": "Note: The graph is connected, does not contain multiple edges and self loops. (2<=N<=20)" }, { "code": null, "e": 25428, "s": 25418, "text": "Examples:" }, { "code": null, "e": 25611, "s": 25428, "text": "Input: N = 4, M = 4, arr[M][2]={{1, 2}, {2, 3}, {3, 4}, {1, 4}}Output: 2Explanation: The shortest path is 1->4 and the second shortest path is 1->2->3->4. Hence, the difference is 2." }, { "code": null, "e": 25715, "s": 25611, "text": "Input: N = 6, M = 8, arr[M][2]={{1, 2}, {1, 3}, {2, 6}, {2, 3}, {2, 4}, {3, 4}, {3, 5}, {4, 6}}Output:1" }, { "code": null, "e": 25951, "s": 25715, "text": "Approach: The idea is to Depth First Search to find all possible paths and store them in vector and sort the vector and find the difference between the shortest and the second shortest path. Follow the steps below to solve the problem:" }, { "code": null, "e": 26519, "s": 25951, "text": "Define a function dfs(vector<vector<int> >& graph, int s, int e, vector<int> vis, int count, vector<int>& dp) and perform the following steps:If s is equal to e, then it means that the current path is one of the possible ones, push the value of count in the vector dp[] and return.Iterate over the range [0, graph[s]] using the variable i and performing the following steps:If vis[i] is not equal to 1, then set the value of vis[i] to 1 and call the function dfs(graph, i, e, vis, count+1, dp) to find other possible paths and set the value of vis[0] again back to 0." }, { "code": null, "e": 26659, "s": 26519, "text": "If s is equal to e, then it means that the current path is one of the possible ones, push the value of count in the vector dp[] and return." }, { "code": null, "e": 26946, "s": 26659, "text": "Iterate over the range [0, graph[s]] using the variable i and performing the following steps:If vis[i] is not equal to 1, then set the value of vis[i] to 1 and call the function dfs(graph, i, e, vis, count+1, dp) to find other possible paths and set the value of vis[0] again back to 0." }, { "code": null, "e": 27140, "s": 26946, "text": "If vis[i] is not equal to 1, then set the value of vis[i] to 1 and call the function dfs(graph, i, e, vis, count+1, dp) to find other possible paths and set the value of vis[0] again back to 0." }, { "code": null, "e": 27246, "s": 27140, "text": "Initialize a 2-D vector graph[][] with N number of rows to store the vertices connected from each vertex." }, { "code": null, "e": 27444, "s": 27246, "text": "Iterate over the range [0, M] using the variable i and perform the following steps:Push the value of b-1 in the vector graph[][] in row a-1.Push the value of a-1 in the vector graph[][] in row b-1." }, { "code": null, "e": 27502, "s": 27444, "text": "Push the value of b-1 in the vector graph[][] in row a-1." }, { "code": null, "e": 27560, "s": 27502, "text": "Push the value of a-1 in the vector graph[][] in row b-1." }, { "code": null, "e": 27628, "s": 27560, "text": "Initialize a vector vis[] of size N to keep track of visited nodes." }, { "code": null, "e": 27696, "s": 27628, "text": "Initialize a vector dp[] to store the length of all possible paths." }, { "code": null, "e": 27807, "s": 27696, "text": "Call the function dfs(graph, 0, N-1, vis, 0, dp) to find all possible paths and store them in the vector dp[]." }, { "code": null, "e": 27848, "s": 27807, "text": "Sort the vector dp[] in ascending order." }, { "code": null, "e": 27957, "s": 27848, "text": "If the size of vector dp[] is greater than 1, then return the value dp[1]-dp[0] else return 0 as the answer." }, { "code": null, "e": 28008, "s": 27957, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 28012, "s": 28008, "text": "C++" }, { "code": null, "e": 28017, "s": 28012, "text": "Java" }, { "code": null, "e": 28025, "s": 28017, "text": "Python3" }, { "code": null, "e": 28028, "s": 28025, "text": "C#" }, { "code": null, "e": 28039, "s": 28028, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // DFS function to find all possible paths.void dfs(vector<vector<int> >& graph, int s, int e, vector<int> v, int count, vector<int>& dp){ if (s == e) { // Push the number of nodes required for // one of the possible paths dp.push_back(count); return; } for (auto i : graph[s]) { if (v[i] != 1) { // Mark the node as visited and // call the function to search for // possible paths and unmark the node. v[i] = 1; dfs(graph, i, e, v, count + 1, dp); v[i] = 0; } }} // Function to find the difference between the// shortest and second shortest pathvoid findDifference(int n, int m, int arr[][2]){ // Construct the graph vector<vector<int> > graph(n, vector<int>()); for (int i = 0; i < m; i++) { int a, b; a = arr[i][0]; b = arr[i][1]; graph[a - 1].push_back(b - 1); graph[b - 1].push_back(a - 1); } // Vector to mark the nodes as visited or not. vector<int> v(n, 0); // Vector to store the count of all possible paths. vector<int> dp; // Mark the starting node as visited. v[0] = 1; // Function to find all possible paths. dfs(graph, 0, n - 1, v, 0, dp); // Sort the vector sort(dp.begin(), dp.end()); // Print the difference if (dp.size() != 1) cout << dp[1] - dp[0]; else cout << 0;} // Driver Codeint main(){ int n, m; n = 6; m = 8; int arr[m][2] = { { 1, 2 }, { 1, 3 }, { 2, 6 }, { 2, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 6 } }; findDifference(n, m, arr); return 0;}", "e": 29789, "s": 28039, "text": null }, { "code": "// Java program for the above approachimport java.util.*;public class Main{ // DFS function to find all possible paths. static void dfs(Vector<Vector<Integer>> graph, int s, int e, int[] v, int count, Vector<Integer> dp) { if (s == e) { // Push the number of nodes required for // one of the possible paths dp.add(count); return; } for(int i : graph.get(s)) { if (v[i] != 1) { // Mark the node as visited and // call the function to search for // possible paths and unmark the node. v[i] = 1; dfs(graph, i, e, v, count + 1, dp); v[i] = 0; } } } // Function to find the difference between the // shortest and second shortest path static void findDifference(int n, int m, int[][] arr) { // Construct the graph Vector<Vector<Integer>> graph = new Vector<Vector<Integer>>(); for(int i = 0; i < n; i++) { graph.add(new Vector<Integer>()); } for (int i = 0; i < m; i++) { int a, b; a = arr[i][0]; b = arr[i][1]; graph.get(a - 1).add(b - 1); graph.get(b - 1).add(a - 1); } // Vector to mark the nodes as visited or not. int[] v = new int[n]; Arrays.fill(v, 0); // Vector to store the count of all possible paths. Vector<Integer> dp = new Vector<Integer>(); // Mark the starting node as visited. v[0] = 1; // Function to find all possible paths. dfs(graph, 0, n - 1, v, 0, dp); // Sort the vector Collections.sort(dp); // Print the difference if (dp.size() != 1) System.out.print(dp.get(1) - dp.get(0)); else System.out.print(0); } public static void main(String[] args) { int n, m; n = 6; m = 8; int[][] arr = { { 1, 2 }, { 1, 3 }, { 2, 6 }, { 2, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 6 } }; findDifference(n, m, arr); }} // This code is contributed by mukesh07.", "e": 31945, "s": 29789, "text": null }, { "code": "# Python3 program for the above approach # DFS function to find all possible paths.def dfs(graph, s, e, v, count, dp): if (s == e): # Push the number of nodes required for # one of the possible paths dp.append(count) return for i in graph[s]: if (v[i] != 1): # Mark the node as visited and # call the function to search for # possible paths and unmark the node. v[i] = 1 dfs(graph, i, e, v, count + 1, dp) v[i] = 0 # Function to find the difference between the# shortest and second shortest pathdef findDifference(n, m, arr): # Construct the graph graph = [] for i in range(n): graph.append([]) for i in range(m): a = arr[i][0] b = arr[i][1] graph[a - 1].append(b - 1) graph[b - 1].append(a - 1) # Vector to mark the nodes as visited or not. v = [0]*(n) # Vector to store the count of all possible paths. dp = [] # Mark the starting node as visited. v[0] = 1 # Function to find all possible paths. dfs(graph, 0, n - 1, v, 0, dp) # Sort the vector dp.sort() # Print the difference if (len(dp) != 1): print(dp[1] - dp[0], end = \"\") else: print(0, end = \"\") # Driver Coden = 6m = 8arr = [ [1, 2], [1, 3], [2, 6], [2, 3], [2, 4], [3, 4], [3, 5], [4, 6],] findDifference(n, m, arr) # This code is contributed by divyesh072019.", "e": 33290, "s": 31945, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // DFS function to find all possible paths. static void dfs(List<List<int>> graph, int s, int e, List<int> v, int count, List<int> dp) { if (s == e) { // Push the number of nodes required for // one of the possible paths dp.Add(count); return; } foreach(int i in graph[s]) { if (v[i] != 1) { // Mark the node as visited and // call the function to search for // possible paths and unmark the node. v[i] = 1; dfs(graph, i, e, v, count + 1, dp); v[i] = 0; } } } // Function to find the difference between the // shortest and second shortest path static void findDifference(int n, int m, int[,] arr) { // Construct the graph List<List<int>> graph = new List<List<int>>(); for(int i = 0; i < n; i++) { graph.Add(new List<int>()); } for (int i = 0; i < m; i++) { int a, b; a = arr[i,0]; b = arr[i,1]; graph[a - 1].Add(b - 1); graph[b - 1].Add(a - 1); } // Vector to mark the nodes as visited or not. List<int> v = new List<int>(); for(int i = 0; i < n; i++) { v.Add(0); } // Vector to store the count of all possible paths. List<int> dp = new List<int>(); // Mark the starting node as visited. v[0] = 1; // Function to find all possible paths. dfs(graph, 0, n - 1, v, 0, dp); // Sort the vector dp.Sort(); // Print the difference if (dp.Count != 1) Console.Write(dp[1] - dp[0]); else Console.Write(0); } static void Main() { int n, m; n = 6; m = 8; int[,] arr = { { 1, 2 }, { 1, 3 }, { 2, 6 }, { 2, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 6 } }; findDifference(n, m, arr); }} // Ths code is contributed by decode2207.", "e": 35354, "s": 33290, "text": null }, { "code": "<script>// Javascript program for the above approach // DFS function to find all possible paths.function dfs(graph, s, e, v, count, dp) { if (s == e) { // Push the number of nodes required for // one of the possible paths dp.push(count); return; } for (let i of graph[s]) { if (v[i] != 1) { // Mark the node as visited and // call the function to search for // possible paths and unmark the node. v[i] = 1; dfs(graph, i, e, v, count + 1, dp); v[i] = 0; } }} // Function to find the difference between the// shortest and second shortest pathfunction findDifference(n, m, arr){ // Construct the graph let graph = new Array(n).fill(0).map(() => []); for (let i = 0; i < m; i++) { let a, b; a = arr[i][0]; b = arr[i][1]; graph[a - 1].push(b - 1); graph[b - 1].push(a - 1); } // Vector to mark the nodes as visited or not. let v = new Array(n).fill(0); // Vector to store the count of all possible paths. let dp = []; // Mark the starting node as visited. v[0] = 1; // Function to find all possible paths. dfs(graph, 0, n - 1, v, 0, dp); // Sort the vector dp.sort((a, b) => a - b); // Print the difference if (dp.length != 1) document.write(dp[1] - dp[0]); else document.write(0);} // Driver Codelet n, m;n = 6;m = 8;let arr = [ [1, 2], [1, 3], [2, 6], [2, 3], [2, 4], [3, 4], [3, 5], [4, 6],]; findDifference(n, m, arr); // This code is contributed by gfgking.</script>", "e": 36833, "s": 35354, "text": null }, { "code": null, "e": 36838, "s": 36836, "text": "1" }, { "code": null, "e": 36885, "s": 36840, "text": "Time Complexity: O(2^N)Auxiliary Space: O(N)" }, { "code": null, "e": 37269, "s": 36887, "text": "Efficient Approach: Using the fact that the second shortest path can not contain all the edges same as that in the shortest path. Remove each edge of the shortest path one at a time and keep finding the shortest path, then one of them has to be the required second shortest path. Use Breadth First Search to find the solution optimally. Follow the steps below to solve the problem:" }, { "code": null, "e": 37539, "s": 37271, "text": "Define a function get_edges(int s, vector<int>& edges, vector<int> p) and perform the following steps:If s is equal to -1, then return.Call the function get_edges(p[s], edges, p) to find all the edges along the shortest path.Push the value of s in the vector edges[]." }, { "code": null, "e": 37573, "s": 37539, "text": "If s is equal to -1, then return." }, { "code": null, "e": 37664, "s": 37573, "text": "Call the function get_edges(p[s], edges, p) to find all the edges along the shortest path." }, { "code": null, "e": 37707, "s": 37664, "text": "Push the value of s in the vector edges[]." }, { "code": null, "e": 38613, "s": 37707, "text": "Define a function dist_helper(vector<vector<int> > graph, vector<int>& d, int v1, int v2, int N) and perform the following steps:Initialize the vector vis[] to keep track of visited nodes.Initialize a queue of pairs q[] to do the Breadth First Search and find the path.Enqueue the pair {0, 0} into the queue of pairs q[].Mark the value of vis[0] as 1(visited).Iterate in a while loop till the queue of pairs q[] is not empty.Initialize a variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue.If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]." }, { "code": null, "e": 38673, "s": 38613, "text": "Initialize the vector vis[] to keep track of visited nodes." }, { "code": null, "e": 38755, "s": 38673, "text": "Initialize a queue of pairs q[] to do the Breadth First Search and find the path." }, { "code": null, "e": 38808, "s": 38755, "text": "Enqueue the pair {0, 0} into the queue of pairs q[]." }, { "code": null, "e": 38848, "s": 38808, "text": "Mark the value of vis[0] as 1(visited)." }, { "code": null, "e": 39394, "s": 38848, "text": "Iterate in a while loop till the queue of pairs q[] is not empty.Initialize a variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue.If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]." }, { "code": null, "e": 39509, "s": 39394, "text": "Initialize a variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[]." }, { "code": null, "e": 39876, "s": 39509, "text": "Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue.If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]." }, { "code": null, "e": 39986, "s": 39876, "text": "If i is equal to v1 and a.first is equal to v2 or i is equal to v2 and a.first is equal to v1, then continue." }, { "code": null, "e": 40145, "s": 39986, "text": "If vis[i] is equal to 0, then set the value of d[i] as 1+a.second, p[i] as a.first and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]." }, { "code": null, "e": 40920, "s": 40145, "text": "Define a function dist(vector<vector<int> > graph, vector<int>& d, vector<int> &p, int N) and perform the following steps:Initialize the vector vis[] to keep track of visited nodes.Initialize a queue of pairs q[] to do the Breadth First Search and find the path.Enqueue the pair {0, 0} into the queue of pairs q[].Mark the value of vis[0] as 1(visited).Iterate in a while loop till the queue of pairs q[] is not empty.Initialize the variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]." }, { "code": null, "e": 40980, "s": 40920, "text": "Initialize the vector vis[] to keep track of visited nodes." }, { "code": null, "e": 41062, "s": 40980, "text": "Initialize a queue of pairs q[] to do the Breadth First Search and find the path." }, { "code": null, "e": 41115, "s": 41062, "text": "Enqueue the pair {0, 0} into the queue of pairs q[]." }, { "code": null, "e": 41155, "s": 41115, "text": "Mark the value of vis[0] as 1(visited)." }, { "code": null, "e": 41577, "s": 41155, "text": "Iterate in a while loop till the queue of pairs q[] is not empty.Initialize the variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[].Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]." }, { "code": null, "e": 41694, "s": 41577, "text": "Initialize the variable a as the front of the queue of pairs q[] and dequeue an element from the queue of pairs q[]." }, { "code": null, "e": 41935, "s": 41694, "text": "Iterate over the range [0, graph[a.first]] using the variable i and performing the following steps:If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]." }, { "code": null, "e": 42077, "s": 41935, "text": "If vis[i] is equal to 0, then set the value of d[i] as 1+a.second and vis[i] as 1 and enqueue the pair {i, d[i]} into the queue of pairs q[]." }, { "code": null, "e": 42183, "s": 42077, "text": "Initialize a 2-D vector graph[][] with N number of rows to store the vertices connected from each vertex." }, { "code": null, "e": 42381, "s": 42183, "text": "Iterate over the range [0, M] using the variable i and perform the following steps:Push the value of b-1 in the vector graph[][] in row a-1.Push the value of a-1 in the vector graph[][] in row b-1." }, { "code": null, "e": 42439, "s": 42381, "text": "Push the value of b-1 in the vector graph[][] in row a-1." }, { "code": null, "e": 42497, "s": 42439, "text": "Push the value of a-1 in the vector graph[][] in row b-1." }, { "code": null, "e": 42601, "s": 42497, "text": "Initialize the vectors p[] and d[] of size N to keep track of parent nodes and the length of the paths." }, { "code": null, "e": 42681, "s": 42601, "text": "Call the function dist(graph, d, p, N) to find the length of the shortest path." }, { "code": null, "e": 42756, "s": 42681, "text": "Initialize a vector distances[] to store the length of all possible paths." }, { "code": null, "e": 42808, "s": 42756, "text": "Push the value of d[N-1] in the vector distances[]." }, { "code": null, "e": 42882, "s": 42808, "text": "Initialize a vector edges[] to get all the edges along the shortest path." }, { "code": null, "e": 42972, "s": 42882, "text": "Call the function get_edges(N-1, edges, p) to find all the edges along the shortest path." }, { "code": null, "e": 43231, "s": 42972, "text": "Iterate over the range [0, edges.size()-1] using the variable i and perform the following steps:Call the function dist_helper(graph, d, edges[i], edges[i+1], N) to find all the edges along the shortest path.Push the value of d[N-1] in the vector distances[]." }, { "code": null, "e": 43343, "s": 43231, "text": "Call the function dist_helper(graph, d, edges[i], edges[i+1], N) to find all the edges along the shortest path." }, { "code": null, "e": 43395, "s": 43343, "text": "Push the value of d[N-1] in the vector distances[]." }, { "code": null, "e": 43443, "s": 43395, "text": "Sort the vector distances[] in ascending order." }, { "code": null, "e": 43573, "s": 43443, "text": "If the size of vector distances[] is greater than 1, then return the value distances[1]-distances[0] else return 0 as the answer." }, { "code": null, "e": 43626, "s": 43575, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 43632, "s": 43628, "text": "C++" }, { "code": null, "e": 43640, "s": 43632, "text": "Python3" }, { "code": null, "e": 43643, "s": 43640, "text": "C#" }, { "code": null, "e": 43654, "s": 43643, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to get all the edges in// the shortest pathvoid get_edges(int s, vector<int>& edges, vector<int> p){ if (s == -1) return; get_edges(p[s], edges, p); edges.push_back(s);} // Calculate the shortest distance// after removing an edge between// v1 and v2void dist_helper(vector<vector<int> > graph, vector<int>& d, int v1, int v2, int n){ // Vector to mark the nodes visited vector<int> v(n, 0); // For BFS queue<pair<int, int> > q; q.push(make_pair(0, 0)); v[0] = 1; // Iterate over the range while (!q.empty()) { auto a = q.front(); q.pop(); for (int i : graph[a.first]) { if ((i == v1 && a.first == v2) || (i == v2 && a.first == v1)) continue; if (v[i] == 0) { d[i] = 1 + a.second; v[i] = 1; q.push(make_pair(i, d[i])); } } }} // Calculates the shortest distances and// maintain a parent arrayvoid dist(vector<vector<int> > graph, vector<int>& d, vector<int>& p, int n){ // Vector to mark the nodes visited vector<int> v(n, 0); // For BFS queue<pair<int, int> > q; q.push(make_pair(0, 0)); v[0] = 1; // Iterate over the range while (!q.empty()) { auto a = q.front(); q.pop(); for (int i : graph[a.first]) { if (v[i] == 0) { p[i] = a.first; d[i] = 1 + a.second; v[i] = 1; q.push(make_pair(i, d[i])); } } }} // Function to find the difference between the// shortest and second shortest pathvoid findDifference(int n, int m, int arr[][2]){ // Initializing and constructing the graph vector<vector<int> > graph(n, vector<int>()); for (int i = 0; i < m; i++) { int a, b; a = arr[i][0]; b = arr[i][1]; graph[a - 1].push_back(b - 1); graph[b - 1].push_back(a - 1); } // Initializing the arrays vector<int> p(n, -1); vector<int> d(n, 1e9); // Calculate the shortest path dist(graph, d, p, n); // Vector to store the lengths // of possible paths vector<int> distances; distances.push_back(d[n - 1]); vector<int> edges; // Get all the edges along the shortest path get_edges(n - 1, edges, p); // Iterate over the range for (int i = 0; i + 1 < edges.size(); i++) { // Calculate shortest distance after // removing the edge dist_helper(graph, d, edges[i], edges[i + 1], n); distances.push_back(d[n - 1]); } // Sort the paths in ascending order sort(distances.begin(), distances.end()); if (distances.size() == 1) cout << 0 << endl; else cout << distances[1] - distances[0] << endl;} // Driver Codeint main(){ int n, m; n = 6; m = 8; int arr[m][2] = { { 1, 2 }, { 1, 3 }, { 2, 6 }, { 2, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 6 } }; findDifference(n, m, arr); return 0;}", "e": 46764, "s": 43654, "text": null }, { "code": "# Python3 program for the above approach edges, d, p = [], [], [] # Function to get all the edges in# the shortest pathdef get_edges(s): global edges, d, p if s == -1: return get_edges(p[s]) edges.append(s) # Calculate the shortest distance# after removing an edge between# v1 and v2def dist_helper(graph, v1, v2, n): global edges, d, p # Vector to mark the nodes visited v = [0]*(n) # For BFS q = [] q.append([0, 0]) v[0] = 1 # Iterate over the range while len(q) > 0: a = q[0] q.pop(0) for i in graph[a[0]]: if (i == v1 and a[0] == v2) or (i == v2 and a[0] == v1): continue if v[i] == 0: d[i] = 1 + a[1] v[i] = 1 q.append([i, d[i]]) # Calculates the shortest distances and# maintain a parent arraydef dist(graph, n): global edges, d, p # Vector to mark the nodes visited v = [0]*(n) # For BFS q = [] q.append([0, 0]) v[0] = 1 # Iterate over the range while len(q) > 0: a = q[0] q.pop(0) for i in graph[a[0]]: if v[i] == 0: p[i] = a[0] d[i] = 1 + a[1] v[i] = 1 q.append([i, d[i]]) # Function to find the difference between the# shortest and second shortest pathdef findDifference(n, m, arr): global edges, d, p # Initializing and constructing the graph graph = [] for i in range(n): graph.append([]) for i in range(m): a = arr[i][0] b = arr[i][1] graph[a - 1].append(b - 1) graph[b - 1].append(a - 1) # Initializing the arrays p = [-1]*(n) d = [1e9]*(n) # Calculate the shortest path dist(graph, n) # Vector to store the lengths # of possible paths distances = [] distances.append(d[n - 1]) edges = [] # Get all the edges along the shortest path get_edges(n - 1) # Iterate over the range i = 0 while i + 1 < len(edges): # Calculate shortest distance after # removing the edge dist_helper(graph, edges[i], edges[i + 1], n) distances.append(d[n - 1]) i+=1 # Sort the paths in ascending order distances.sort() if len(distances) == 1: print(0) else: print(distances[1] - distances[0]) n = 6;m = 8;arr = [ [ 1, 2 ], [ 1, 3 ], [ 2, 6 ], [ 2, 3 ], [ 2, 4 ], [ 3, 4 ], [ 3, 5 ], [ 4, 6 ] ] findDifference(n, m, arr) # This code is contributed by suresh07.", "e": 49269, "s": 46764, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { static List<int> edges = new List<int>(); static List<int> d = new List<int>(); static List<int> p = new List<int>(); // Function to get all the edges in // the shortest path static void get_edges(int s) { if (s == -1) return; get_edges(p[s]); edges.Add(s); } // Calculate the shortest distance // after removing an edge between // v1 and v2 static void dist_helper(List<List<int>> graph, int v1, int v2, int n) { // Vector to mark the nodes visited List<int> v = new List<int>(); for(int i = 0; i < n; i++) { v.Add(0); } // For BFS List<Tuple<int,int>> q = new List<Tuple<int,int>>(); q.Add(new Tuple<int,int>(0, 0)); v[0] = 1; // Iterate over the range while (q.Count > 0) { Tuple<int,int> a = q[0]; q.RemoveAt(0); for (int i = 0; i < graph[a.Item1].Count; i++) { if ((graph[a.Item1][i] == v1 && a.Item1 == v2) || (graph[a.Item1][i] == v2 && a.Item1 == v1)) continue; if (v[graph[a.Item1][i]] == 0) { d[graph[a.Item1][i]] = 1 + a.Item2; v[graph[a.Item1][i]] = 1; q.Add(new Tuple<int,int>(graph[a.Item1][i], d[graph[a.Item1][i]])); } } } } // Calculates the shortest distances and // maintain a parent array static void dist(List<List<int>> graph, int n) { // Vector to mark the nodes visited List<int> v = new List<int>(); for(int i = 0; i < n; i++) { v.Add(0); } // For BFS List<Tuple<int,int>> q = new List<Tuple<int,int>>(); q.Add(new Tuple<int,int>(0, 0)); v[0] = 1; // Iterate over the range while (q.Count > 0) { Tuple<int,int> a = q[0]; q.RemoveAt(0); for (int i = 0; i < graph[a.Item1].Count; i++) { if (v[graph[a.Item1][i]] == 0) { p[graph[a.Item1][i]] = a.Item1; d[graph[a.Item1][i]] = 1 + a.Item2; v[graph[a.Item1][i]] = 1; q.Add(new Tuple<int,int>(graph[a.Item1][i], d[graph[a.Item1][i]])); } } } } // Function to find the difference between the // shortest and second shortest path static void findDifference(int n, int m, int[,] arr) { // Initializing and constructing the graph List<List<int>> graph = new List<List<int>>(); for(int i = 0; i < n; i++) { graph.Add(new List<int>()); } for (int i = 0; i < m; i++) { int a, b; a = arr[i,0]; b = arr[i,1]; graph[a - 1].Add(b - 1); graph[b - 1].Add(a - 1); } // Initializing the arrays for(int i = 0; i < n; i++) { p.Add(-1); d.Add(1000000000); } // Calculate the shortest path dist(graph, n); // Vector to store the lengths // of possible paths List<int> distances = new List<int>(); distances.Add(d[n - 1]); // Get all the edges along the shortest path get_edges(n - 1); // Iterate over the range for (int i = 0; i + 1 < edges.Count; i++) { // Calculate shortest distance after // removing the edge dist_helper(graph, edges[i], edges[i + 1], n); distances.Add(d[n - 1]); } // Sort the paths in ascending order distances.Sort(); if (distances.Count == 1) { Console.WriteLine(0); } else { Console.WriteLine((distances[1] - distances[0])); } } // Driver code static void Main() { int n, m; n = 6; m = 8; int[,] arr = { { 1, 2 }, { 1, 3 }, { 2, 6 }, { 2, 3 }, { 2, 4 }, { 3, 4 }, { 3, 5 }, { 4, 6 } }; findDifference(n, m, arr); }} // This code is contributed by divyeshrabadiya07.", "e": 53497, "s": 49269, "text": null }, { "code": "<script> // Javascript program for the above approach let edges = [], d = [], p = []; // Function to get all the edges in // the shortest path function get_edges(s) { if (s == -1) return; get_edges(p[s]); edges.push(s); } // Calculate the shortest distance // after removing an edge between // v1 and v2 function dist_helper(graph, v1, v2, n) { // Vector to mark the nodes visited let v = []; for(let i = 0; i < n; i++) { v.push(0); } // For BFS let q = []; q.push([0, 0]); v[0] = 1; // Iterate over the range while (q.length > 0) { let a = q[0]; q.shift(); for (let i = 0; i < graph[a[0]].length; i++) { if ((graph[a[0]][i] == v1 && a[0] == v2) || (graph[a[0]][i] == v2 && a[0] == v1)) continue; if (v[graph[a[0]][i]] == 0) { d[graph[a[0]][i]] = 1 + a[1]; v[graph[a[0]][i]] = 1; q.push([graph[a[0]][i], d[graph[a[0]][i]]]); } } } } // Calculates the shortest distances and // maintain a parent array function dist(graph, n) { // Vector to mark the nodes visited let v = []; for(let i = 0; i < n; i++) { v.push(0); } // For BFS let q = []; q.push([0, 0]); v[0] = 1; // Iterate over the range while (q.length > 0) { let a = q[0]; q.shift(); for (let i = 0; i < graph[a[0]].length; i++) { if (v[graph[a[0]][i]] == 0) { p[graph[a[0]][i]] = a[0]; d[graph[a[0]][i]] = 1 + a[1]; v[graph[a[0]][i]] = 1; q.push([graph[a[0]][i], d[graph[a[0]][i]]]); } } } } // Function to find the difference between the // shortest and second shortest path function findDifference(n, m, arr) { // Initializing and constructing the graph let graph = []; for(let i = 0; i < n; i++) { graph.push([]); } for (let i = 0; i < m; i++) { let a, b; a = arr[i][0]; b = arr[i][1]; graph[a - 1].push(b - 1); graph[b - 1].push(a - 1); } // Initializing the arrays for(let i = 0; i < n; i++) { p.push(-1); d.push(1e9); } // Calculate the shortest path dist(graph, n); // Vector to store the lengths // of possible paths let distances = []; distances.push(d[n - 1]); // Get all the edges along the shortest path get_edges(n - 1); // Iterate over the range for (let i = 0; i + 1 < edges.length; i++) { // Calculate shortest distance after // removing the edge dist_helper(graph, edges[i], edges[i + 1], n); distances.push(d[n - 1]); } // Sort the paths in ascending order distances.sort(function(a, b){return a - b}); if (distances.length == 1) { document.write(0 + \"</br>\"); } else { document.write((distances[1] - distances[0]) + \"</br>\"); } } let n, m; n = 6; m = 8; let arr = [ [ 1, 2 ], [ 1, 3 ], [ 2, 6 ], [ 2, 3 ], [ 2, 4 ], [ 3, 4 ], [ 3, 5 ], [ 4, 6 ] ]; findDifference(n, m, arr); // This code is contributed by rameshtravel07.</script>", "e": 57182, "s": 53497, "text": null }, { "code": null, "e": 57187, "s": 57185, "text": "1" }, { "code": null, "e": 57234, "s": 57189, "text": "Time Complexity: O(N*M)Auxiliary Space: O(N)" }, { "code": null, "e": 57244, "s": 57236, "text": "gfgking" }, { "code": null, "e": 57258, "s": 57244, "text": "divyesh072019" }, { "code": null, "e": 57269, "s": 57258, "text": "decode2207" }, { "code": null, "e": 57278, "s": 57269, "text": "mukesh07" }, { "code": null, "e": 57287, "s": 57278, "text": "suresh07" }, { "code": null, "e": 57302, "s": 57287, "text": "rameshtravel07" }, { "code": null, "e": 57320, "s": 57302, "text": "divyeshrabadiya07" }, { "code": null, "e": 57334, "s": 57320, "text": "Shortest Path" }, { "code": null, "e": 57340, "s": 57334, "text": "Graph" }, { "code": null, "e": 57350, "s": 57340, "text": "Recursion" }, { "code": null, "e": 57360, "s": 57350, "text": "Recursion" }, { "code": null, "e": 57366, "s": 57360, "text": "Graph" }, { "code": null, "e": 57380, "s": 57366, "text": "Shortest Path" }, { "code": null, "e": 57478, "s": 57380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 57514, "s": 57478, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 57579, "s": 57514, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 57626, "s": 57579, "text": "Eulerian path and circuit for undirected graph" }, { "code": null, "e": 57696, "s": 57626, "text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)" }, { "code": null, "e": 57777, "s": 57696, "text": "Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)" }, { "code": null, "e": 57837, "s": 57777, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 57864, "s": 57837, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 57949, "s": 57864, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 57959, "s": 57949, "text": "Recursion" } ]
JavaFX - Images
You can load and modify images using the classes provided by JavaFX in the package javafx.scene.image. JavaFX supports the image formats like Bmp, Gif, Jpeg, Png. This chapter teaches you how to load images in to JavaFX, how to project an image in multiple views and how to alter the pixels of an image. You can load an image in JavaFX by instantiating the class named Image of the package javafx.scene.image. To the constructor of the class, you have to pass either of the following − An InputStream object of the image to be loaded or, An InputStream object of the image to be loaded or, A string variable holding the URL for the image. A string variable holding the URL for the image. //Passing FileInputStream object as a parameter FileInputStream inputstream = new FileInputStream("C:\\images\\image.jpg"); Image image = new Image(inputstream); //Loading image from URL //Image image = new Image(new FileInputStream("url for the image)); After loading the image, you can set the view for the image by instantiating the ImageView class and passing the image to its constructor as follows − ImageView imageView = new ImageView(image); Following is an example which demonstrates how to load an image in JavaFX and set the view. Save this code in a file with the name ImageExample.java. import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; public class ImageExample extends Application { @Override public void start(Stage stage) throws FileNotFoundException { //Creating an image Image image = new Image(new FileInputStream("path of the image")); //Setting the image view ImageView imageView = new ImageView(image); //Setting the position of the image imageView.setX(50); imageView.setY(25); //setting the fit height and width of the image view imageView.setFitHeight(455); imageView.setFitWidth(500); //Setting the preserve ratio of the image view imageView.setPreserveRatio(true); //Creating a Group object Group root = new Group(imageView); //Creating a scene object Scene scene = new Scene(root, 600, 500); //Setting title to the Stage stage.setTitle("Loading an image"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]) { launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. Javac ImageExample.java java ImageExample On executing, the above program generates a JavaFX window as follows − You can also set multiple views for an image in the same scene. The following program is an example that demonstrates how to set various views for an image in a scene in JavaFX. Save this code in a file with the name MultipleViews.java. import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; public class MultipleViews extends Application { @Override public void start(Stage stage) throws FileNotFoundException { //Creating an image Image image = new Image(new FileInputStream("file path")); //Setting the image view 1 ImageView imageView1 = new ImageView(image); //Setting the position of the image imageView1.setX(50); imageView1.setY(25); //setting the fit height and width of the image view imageView1.setFitHeight(300); imageView1.setFitWidth(250); //Setting the preserve ratio of the image view imageView1.setPreserveRatio(true); //Setting the image view 2 ImageView imageView2 = new ImageView(image); //Setting the position of the image imageView2.setX(350); imageView2.setY(25); //setting the fit height and width of the image view imageView2.setFitHeight(150); imageView2.setFitWidth(250); //Setting the preserve ratio of the image view imageView2.setPreserveRatio(true); //Setting the image view 3 ImageView imageView3 = new ImageView(image); //Setting the position of the image imageView3.setX(350); imageView3.setY(200); //setting the fit height and width of the image view imageView3.setFitHeight(100); imageView3.setFitWidth(100); //Setting the preserve ratio of the image view imageView3.setPreserveRatio(true); //Creating a Group object Group root = new Group(imageView1, imageView2, imageView3); //Creating a scene object Scene scene = new Scene(root, 600, 400); //Setting title to the Stage stage.setTitle("Multiple views of an image"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]) { launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. Javac MultipleViews.java java MultipleViews On executing, the above program generates a JavaFX window as follows − JavaFX provides classes named PixelReader and PixelWriter classes to read and write pixels of an image. The WritableImage class is used to create a writable image. Following is an example which demonstrates how to read and write pixels of an image. Here, we are reading the color value of an image and making it darker. Save this code in a file with the name WritingPixelsExample.java. import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.PixelReader; import javafx.scene.image.PixelWriter; import javafx.scene.image.WritableImage; import javafx.scene.paint.Color; import javafx.stage.Stage; public class WritingPixelsExample extends Application { @Override public void start(Stage stage) throws FileNotFoundException { //Creating an image Image image = new Image(new FileInputStream("C:\\images\\logo.jpg")); int width = (int)image.getWidth(); int height = (int)image.getHeight(); //Creating a writable image WritableImage wImage = new WritableImage(width, height); //Reading color from the loaded image PixelReader pixelReader = image.getPixelReader(); //getting the pixel writer PixelWriter writer = wImage.getPixelWriter(); //Reading the color of the image for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { //Retrieving the color of the pixel of the loaded image Color color = pixelReader.getColor(x, y); //Setting the color to the writable image writer.setColor(x, y, color.darker()); } } //Setting the view for the writable image ImageView imageView = new ImageView(wImage); //Creating a Group object Group root = new Group(imageView); //Creating a scene object Scene scene = new Scene(root, 600, 500); //Setting title to the Stage stage.setTitle("Writing pixels "); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]) { launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. Javac WritingPixelsExample.java java WritingPixelsExample On executing, the above program generates a JavaFX window as follows − 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 2063, "s": 1900, "text": "You can load and modify images using the classes provided by JavaFX in the package javafx.scene.image. JavaFX supports the image formats like Bmp, Gif, Jpeg, Png." }, { "code": null, "e": 2204, "s": 2063, "text": "This chapter teaches you how to load images in to JavaFX, how to project an image in multiple views and how to alter the pixels of an image." }, { "code": null, "e": 2310, "s": 2204, "text": "You can load an image in JavaFX by instantiating the class named Image of the package javafx.scene.image." }, { "code": null, "e": 2386, "s": 2310, "text": "To the constructor of the class, you have to pass either of the following −" }, { "code": null, "e": 2438, "s": 2386, "text": "An InputStream object of the image to be loaded or," }, { "code": null, "e": 2490, "s": 2438, "text": "An InputStream object of the image to be loaded or," }, { "code": null, "e": 2539, "s": 2490, "text": "A string variable holding the URL for the image." }, { "code": null, "e": 2588, "s": 2539, "text": "A string variable holding the URL for the image." }, { "code": null, "e": 2858, "s": 2588, "text": "//Passing FileInputStream object as a parameter \nFileInputStream inputstream = new FileInputStream(\"C:\\\\images\\\\image.jpg\"); \nImage image = new Image(inputstream); \n \n//Loading image from URL \n//Image image = new Image(new FileInputStream(\"url for the image));\n" }, { "code": null, "e": 3009, "s": 2858, "text": "After loading the image, you can set the view for the image by instantiating the ImageView class and passing the image to its constructor as follows −" }, { "code": null, "e": 3054, "s": 3009, "text": "ImageView imageView = new ImageView(image);\n" }, { "code": null, "e": 3146, "s": 3054, "text": "Following is an example which demonstrates how to load an image in JavaFX and set the view." }, { "code": null, "e": 3204, "s": 3146, "text": "Save this code in a file with the name ImageExample.java." }, { "code": null, "e": 4635, "s": 3204, "text": "import java.io.FileInputStream; \nimport java.io.FileNotFoundException; \nimport javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.image.Image;\nimport javafx.scene.image.ImageView; \nimport javafx.stage.Stage; \n\npublic class ImageExample extends Application { \n @Override \n public void start(Stage stage) throws FileNotFoundException { \n //Creating an image \n Image image = new Image(new FileInputStream(\"path of the image\")); \n \n //Setting the image view \n ImageView imageView = new ImageView(image); \n \n //Setting the position of the image \n imageView.setX(50); \n imageView.setY(25); \n \n //setting the fit height and width of the image view \n imageView.setFitHeight(455); \n imageView.setFitWidth(500); \n \n //Setting the preserve ratio of the image view \n imageView.setPreserveRatio(true); \n \n //Creating a Group object \n Group root = new Group(imageView); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 500); \n \n //Setting title to the Stage \n stage.setTitle(\"Loading an image\"); \n \n //Adding scene to the stage \n stage.setScene(scene);\n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]) { \n launch(args); \n } \n}" }, { "code": null, "e": 4729, "s": 4635, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 4773, "s": 4729, "text": "Javac ImageExample.java \njava ImageExample\n" }, { "code": null, "e": 4844, "s": 4773, "text": "On executing, the above program generates a JavaFX window as follows −" }, { "code": null, "e": 5022, "s": 4844, "text": "You can also set multiple views for an image in the same scene. The following program is an example that demonstrates how to set various views for an image in a scene in JavaFX." }, { "code": null, "e": 5081, "s": 5022, "text": "Save this code in a file with the name MultipleViews.java." }, { "code": null, "e": 7476, "s": 5081, "text": "import java.io.FileInputStream; \nimport java.io.FileNotFoundException; \nimport javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.image.Image; \nimport javafx.scene.image.ImageView; \nimport javafx.stage.Stage; \n\npublic class MultipleViews extends Application { \n @Override \n public void start(Stage stage) throws FileNotFoundException { \n //Creating an image \n Image image = new Image(new FileInputStream(\"file path\")); \n \n //Setting the image view 1 \n ImageView imageView1 = new ImageView(image); \n \n //Setting the position of the image \n imageView1.setX(50); \n imageView1.setY(25); \n \n //setting the fit height and width of the image view \n imageView1.setFitHeight(300); \n imageView1.setFitWidth(250); \n \n //Setting the preserve ratio of the image view \n imageView1.setPreserveRatio(true); \n \n //Setting the image view 2 \n ImageView imageView2 = new ImageView(image);\n \n //Setting the position of the image \n imageView2.setX(350); \n imageView2.setY(25); \n \n //setting the fit height and width of the image view \n imageView2.setFitHeight(150); \n imageView2.setFitWidth(250); \n \n //Setting the preserve ratio of the image view \n imageView2.setPreserveRatio(true); \n \n //Setting the image view 3 \n ImageView imageView3 = new ImageView(image); \n \n //Setting the position of the image \n imageView3.setX(350); \n imageView3.setY(200); \n \n //setting the fit height and width of the image view \n imageView3.setFitHeight(100); \n imageView3.setFitWidth(100); \n \n //Setting the preserve ratio of the image view \n imageView3.setPreserveRatio(true); \n \n //Creating a Group object \n Group root = new Group(imageView1, imageView2, imageView3); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 400); \n \n //Setting title to the Stage \n stage.setTitle(\"Multiple views of an image\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage\n stage.show(); \n } \n public static void main(String args[]) { \n launch(args); \n } \n} " }, { "code": null, "e": 7570, "s": 7476, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 7616, "s": 7570, "text": "Javac MultipleViews.java \njava MultipleViews\n" }, { "code": null, "e": 7687, "s": 7616, "text": "On executing, the above program generates a JavaFX window as follows −" }, { "code": null, "e": 7851, "s": 7687, "text": "JavaFX provides classes named PixelReader and PixelWriter classes to read and write pixels of an image. The WritableImage class is used to create a writable image." }, { "code": null, "e": 8007, "s": 7851, "text": "Following is an example which demonstrates how to read and write pixels of an image. Here, we are reading the color value of an image and making it darker." }, { "code": null, "e": 8073, "s": 8007, "text": "Save this code in a file with the name WritingPixelsExample.java." }, { "code": null, "e": 10196, "s": 8073, "text": "import java.io.FileInputStream; \nimport java.io.FileNotFoundException; \nimport javafx.application.Application; \n\nimport javafx.scene.Group; \nimport javafx.scene.Scene; \n\nimport javafx.scene.image.Image; \nimport javafx.scene.image.ImageView; \nimport javafx.scene.image.PixelReader; \nimport javafx.scene.image.PixelWriter; \nimport javafx.scene.image.WritableImage;\n \nimport javafx.scene.paint.Color; \nimport javafx.stage.Stage; \n\npublic class WritingPixelsExample extends Application { \n @Override \n public void start(Stage stage) throws FileNotFoundException { \n //Creating an image \n Image image = new Image(new FileInputStream(\"C:\\\\images\\\\logo.jpg\")); \n int width = (int)image.getWidth(); \n int height = (int)image.getHeight(); \n \n //Creating a writable image \n WritableImage wImage = new WritableImage(width, height); \n \n //Reading color from the loaded image \n PixelReader pixelReader = image.getPixelReader(); \n \n //getting the pixel writer \n PixelWriter writer = wImage.getPixelWriter(); \n \n //Reading the color of the image \n for(int y = 0; y < height; y++) { \n for(int x = 0; x < width; x++) { \n //Retrieving the color of the pixel of the loaded image \n Color color = pixelReader.getColor(x, y); \n \n //Setting the color to the writable image \n writer.setColor(x, y, color.darker()); \n }\n }\t\n //Setting the view for the writable image \n ImageView imageView = new ImageView(wImage); \n \n //Creating a Group object \n Group root = new Group(imageView); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 500); \n \n //Setting title to the Stage \n stage.setTitle(\"Writing pixels \"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n }\n public static void main(String args[]) { \n launch(args); \n } \n}" }, { "code": null, "e": 10290, "s": 10196, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 10351, "s": 10290, "text": "Javac WritingPixelsExample.java \njava WritingPixelsExample \n" }, { "code": null, "e": 10422, "s": 10351, "text": "On executing, the above program generates a JavaFX window as follows −" }, { "code": null, "e": 10457, "s": 10422, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 10468, "s": 10457, "text": " Syed Raza" }, { "code": null, "e": 10504, "s": 10468, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 10540, "s": 10504, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 10573, "s": 10540, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 10609, "s": 10573, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 10616, "s": 10609, "text": " Print" }, { "code": null, "e": 10627, "s": 10616, "text": " Add Notes" } ]
Find number of triplets in array such that a[i]>a[j]>a[k] and i<j<k - GeeksforGeeks
22 Dec, 2021 Given an array arr of size N. The task is to count number of triplets in the array such that a[i]>a[j]>a[k] and i<j<kExamples: Input : arr[] = {10, 8, 3, 1} Output : 4 The triplets are: 1, 3, 8 1, 3, 10 1, 8, 10 3, 8, 10Input : arr[] = {88, 64, 45, 21, 54} Output : 5 Prerequisites: Count inversions Approach: Find the greater_left array. greater_left[i] represents the number of elements greater than a[i] and in left side of it ( from 0 to i-1 ). Find the smaller_right array. smaller_right[i] represents the number of elements smaller than a[i] and in right side to it ( from i+1 to n-1 ) The final answer will be the sum of the product of greater_left[i] and smaller_right[i] for every index. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP program to find triplets// a[i]>a[j]>a[k] and i<j<k#include<bits/stdc++.h>using namespace std; // Updates a node in Binary Index Tree (BIT)// at given index(i) in BIT. The given value// 'val' is added to BITree[i] and// all of its ancestors in tree.void update(int BIT[], int n, int i, int val){ for (; i <= n; i += (i & -i)) { BIT[i] += val; }} // Returns sum of arr[0..i]. This function// assumes that the array is preprocessed// and partial sums of array elements are// stored in BIT[].int query(int BIT[], int i){ int sum = 0; for (; i > 0; i -= (i & -i)) { sum += BIT[i]; } return sum;} // Converts an array to an array with values from 1 to n// and relative order of smaller and greater elements// remains same. For example, {7, -90, 100, 1} is// converted to {3, 1, 4 ,2 }void Convert(int arr[], int n){ int temp[n]; for (int i = 0; i < n; i++) { temp[i] = arr[i]; } sort(temp, temp + n); for (int i = 0; i < n; i++) { arr[i] = lower_bound(temp, temp + n, arr[i]) - temp + 1; }} // Function to find tripletsint getCount(int arr[], int n){ // Decomposition Convert(arr, n); int BIT[n + 1] = { 0 }; int smaller_right[n + 1] = { 0 }; int greater_left[n + 1] = { 0 }; // Find all right side smaller elements for (int i = n - 1; i >= 0; i--) { smaller_right[i] = query(BIT, arr[i]-1); update(BIT, n, arr[i], 1); } for (int i = 0; i <= n; i++) { BIT[i] = 0; } // Find all left side greater elements for (int i = 0; i < n; i++) { greater_left[i] = i - query(BIT, arr[i]); update(BIT, n, arr[i], 1); } // Find the required answer int ans = 0; for (int i = 0; i < n; i++) { ans += greater_left[i] * smaller_right[i]; } // Return the required answer return ans;} // Driver codeint main(){ int arr[] = { 7, 3, 4, 3, 3, 1}; int n = sizeof(arr) / sizeof(arr[0]); cout << getCount(arr, n) << endl; return 0;} import java.io.*;import java.util.*; class GFG { public static int lower(int a[], int x) //Returns leftest index of x in sorted arr else n { //If not present returns index of just greater element int n = a.length; int l = 0; int r = n - 1; int ans = n; while(l <= r) { int m = (r - l) / 2 + l; if(a[m] >= x) { ans = m; r = m - 1; } else { l = m + 1; } } return ans; } // Returns sum of arr[0..i]. This function // assumes that the array is preprocessed // and partial sums of array elements are // stored in BIT[]. public static int query(int BIT[], int i) { int sum = 0; for (; i > 0; i -= (i & -i)) { sum += BIT[i]; } return sum; } // Converts an array to an array with values from 1 to n // and relative order of smaller and greater elements // remains same. For example, {7, -90, 100, 1} is // converted to {3, 1, 4 ,2 } public static void Convert(int arr[], int n) { int temp[]=new int[n]; for (int i = 0; i < n; i++) { temp[i] = arr[i]; } Arrays.sort(temp); for (int i = 0; i < n; i++) { arr[i] = lower(temp, arr[i]) + 1; } } // Updates a node in Binary Index Tree (BIT) // at given index(i) in BIT. The given value // 'val' is added to BITree[i] and // all of its ancestors in tree. public static void update(int BIT[], int n, int i, int val) { for (; i <= n; i += (i & -i)) { BIT[i] += val; } } // Function to find triplets public static int getCount(int arr[], int n) { // Decomposition Convert(arr, n); int BIT[] = new int[n+1]; int smaller_right[] = new int[n+1]; int greater_left[] = new int[n+1]; for(int i=0;i<n+1;i++){ BIT[i]=0; smaller_right[i]=0; greater_left[i]=0; } // Find all right side smaller elements for (int i = n - 1; i >= 0; i--) { smaller_right[i] = query(BIT, arr[i]-1); update(BIT, n, arr[i], 1); } for (int i = 0; i <= n; i++) { BIT[i] = 0; } // Find all left side greater elements for (int i = 0; i < n; i++) { greater_left[i] = i - query(BIT, arr[i]); update(BIT, n, arr[i], 1); } // Find the required answer int ans = 0; for (int i = 0; i < n; i++) { ans += greater_left[i] * smaller_right[i]; } // Return the required answer return ans; } public static void main (String[] args) { int arr[] = { 7, 3, 4, 3, 3, 1}; int n = 6; System.out.println(getCount(arr, n)); }}// this code is contributed by Manu Pathria # Python3 program to find triplets# a[i]>a[j]>a[k] and i<j<kfrom bisect import bisect_left as lower_bound # Updates a node in Binary Index Tree (BIT)# at given index(i) in BIT. The given value# 'val' is added to BITree[i] and# all of its ancestors in tree.def update(BIT, n, i, val): while i <= n: BIT[i] += val i += (i & -i) # Returns sum of arr[0..i]. This function# assumes that the array is preprocessed# and partial sums of array elements are# stored in BIT[].def query(BIT, i): summ = 0 while i > 0: summ += BIT[i] i -= (i & -i) return summ # Converts an array to an array with values# from 1 to n and relative order of smaller# and greater elements remains same. For example,# {7, -90, 100, 1} is converted to {3, 1, 4 ,2 }def convert(arr, n): temp = [0] * n for i in range(n): temp[i] = arr[i] temp.sort() for i in range(n): arr[i] = lower_bound(temp, arr[i]) + 1 # Function to find tripletsdef getCount(arr, n): # Decomposition convert(arr, n) BIT = [0] * (n + 1) smaller_right = [0] * (n + 1) greater_left = [0] * (n + 1) # Find all right side smaller elements for i in range(n - 1, -1, -1): smaller_right[i] = query(BIT, arr[i] - 1) update(BIT, n, arr[i], 1) for i in range(n + 1): BIT[i] = 0 # Find all left side greater elements for i in range(n): greater_left[i] = i - query(BIT, arr[i]) update(BIT, n, arr[i], 1) # Find the required answer ans = 0 for i in range(n): ans += greater_left[i] * smaller_right[i] # Return the required answer return ans # Driver Codeif __name__ == "__main__": arr = [7, 3, 4, 3, 3, 1] n = len(arr) print(getCount(arr, n)) # This code is contributed by# sanjeev2552 // C# implementation of the approachusing System; class GFG{ public static int lower(int[] a, int x) //Returns leftest index of x in sorted arr else n { //If not present returns index of just greater element int n = a.Length; int l = 0; int r = n - 1; int ans = n; while(l <= r) { int m = (r - l) / 2 + l; if(a[m] >= x) { ans = m; r = m - 1; } else { l = m + 1; } } return ans; } // Returns sum of arr[0..i]. This function // assumes that the array is preprocessed // and partial sums of array elements are // stored in BIT[]. public static int query(int[] BIT, int i) { int sum = 0; for (; i > 0; i -= (i & -i)) { sum += BIT[i]; } return sum; } // Converts an array to an array with values from 1 to n // and relative order of smaller and greater elements // remains same. For example, {7, -90, 100, 1} is // converted to {3, 1, 4 ,2 } public static void Convert(int[] arr, int n) { int[] temp =new int[n]; for (int i = 0; i < n; i++) { temp[i] = arr[i]; } Array.Sort(temp); for (int i = 0; i < n; i++) { arr[i] = lower(temp, arr[i]) + 1; } } // Updates a node in Binary Index Tree (BIT) // at given index(i) in BIT. The given value // 'val' is added to BITree[i] and // all of its ancestors in tree. public static void update(int[] BIT, int n, int i, int val) { for (; i <= n; i += (i & -i)) { BIT[i] += val; } } // Function to find triplets public static int getCount(int[] arr, int n) { // Decomposition Convert(arr, n); int[] BIT = new int[n + 1]; int[] smaller_right = new int[n + 1]; int[] greater_left = new int[n + 1]; for(int i = 0; i < n + 1; i++) { BIT[i] = 0; smaller_right[i] = 0; greater_left[i] = 0; } // Find all right side smaller elements for (int i = n - 1; i >= 0; i--) { smaller_right[i] = query(BIT, arr[i]-1); update(BIT, n, arr[i], 1); } for (int i = 0; i <= n; i++) { BIT[i] = 0; } // Find all left side greater elements for (int i = 0; i < n; i++) { greater_left[i] = i - query(BIT, arr[i]); update(BIT, n, arr[i], 1); } // Find the required answer int ans = 0; for (int i = 0; i < n; i++) { ans += greater_left[i] * smaller_right[i]; } // Return the required answer return ans; } // Driver code public static void Main () { int[] arr = { 7, 3, 4, 3, 3, 1}; int n = 6; Console.WriteLine(getCount(arr, n)); }} // This code is contributed by target_2. <script> // JavaScript program to find triplets// a[i]>a[j]>a[k] and i<j<k // Updates a node in Binary Index Tree (BIT)// at given index(i) in BIT. The given value// 'val' is added to BITree[i] and// all of its ancestors in tree.function update(BIT, n, i, val) { for (; i <= n; i += (i & -i)) { BIT[i] += val; }} // Returns sum of arr[0..i]. This function// assumes that the array is preprocessed// and partial sums of array elements are// stored in BIT[].function query(BIT, i) { let sum = 0; for (; i > 0; i -= (i & -i)) { sum += BIT[i]; } return sum;} //Returns leftest index of x in sorted arr else n//If not present returns index of just greater element function lower(a, x) { let n = a.length; let l = 0; let r = n - 1; let ans = n; while (l <= r) { let m = Math.floor((r - l) / 2) + l; if (a[m] >= x) { ans = m; r = m - 1; } else { l = m + 1; } } return ans;} // Converts an array to an array with values from 1 to n// and relative order of smaller and greater elements// remains same. For example, {7, -90, 100, 1} is// converted to {3, 1, 4 ,2 }function Convert(arr, n) { let temp = new Array(n); for (let i = 0; i < n; i++) { temp[i] = arr[i]; } temp.sort((a, b) => a - b); for (let i = 0; i < n; i++) { arr[i] = lower(temp, arr[i]) + 1; }} // Function to find tripletsfunction getCount(arr, n) { // Decomposition Convert(arr, n); let BIT = new Array(n + 1).fill(0); let smaller_right = new Array(n + 1).fill(0); let greater_left = new Array(n + 1).fill(0); // Find all right side smaller elements for (let i = n - 1; i >= 0; i--) { smaller_right[i] = query(BIT, arr[i] - 1); update(BIT, n, arr[i], 1); } for (let i = 0; i <= n; i++) { BIT[i] = 0; } // Find all left side greater elements for (let i = 0; i < n; i++) { greater_left[i] = i - query(BIT, arr[i]); update(BIT, n, arr[i], 1); } // Find the required answer let ans = 0; for (let i = 0; i < n; i++) { ans += greater_left[i] * smaller_right[i]; } // Return the required answer return ans;} // Driver code let arr = [7, 3, 4, 3, 3, 1]; let n = arr.length; document.write(getCount(arr, n) + "<br>"); // This code is contributed by _saurabh_jaiswal </script> Output: 8 Akanksha_Rai sanjeev2552 manupathria _saurabh_jaiswal target_2 Constructive Algorithms prefix Suffix-Array Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Python | Using 2D arrays/lists the right way Linked List vs Array Queue | Set 1 (Introduction and Array Implementation) Find the Missing Number
[ { "code": null, "e": 25134, "s": 25106, "text": "\n22 Dec, 2021" }, { "code": null, "e": 25263, "s": 25134, "text": "Given an array arr of size N. The task is to count number of triplets in the array such that a[i]>a[j]>a[k] and i<j<kExamples: " }, { "code": null, "e": 25406, "s": 25263, "text": "Input : arr[] = {10, 8, 3, 1} Output : 4 The triplets are: 1, 3, 8 1, 3, 10 1, 8, 10 3, 8, 10Input : arr[] = {88, 64, 45, 21, 54} Output : 5 " }, { "code": null, "e": 25450, "s": 25406, "text": "Prerequisites: Count inversions Approach: " }, { "code": null, "e": 25589, "s": 25450, "text": "Find the greater_left array. greater_left[i] represents the number of elements greater than a[i] and in left side of it ( from 0 to i-1 )." }, { "code": null, "e": 25732, "s": 25589, "text": "Find the smaller_right array. smaller_right[i] represents the number of elements smaller than a[i] and in right side to it ( from i+1 to n-1 )" }, { "code": null, "e": 25837, "s": 25732, "text": "The final answer will be the sum of the product of greater_left[i] and smaller_right[i] for every index." }, { "code": null, "e": 25890, "s": 25837, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25894, "s": 25890, "text": "C++" }, { "code": null, "e": 25899, "s": 25894, "text": "Java" }, { "code": null, "e": 25907, "s": 25899, "text": "Python3" }, { "code": null, "e": 25910, "s": 25907, "text": "C#" }, { "code": null, "e": 25921, "s": 25910, "text": "Javascript" }, { "code": "// CPP program to find triplets// a[i]>a[j]>a[k] and i<j<k#include<bits/stdc++.h>using namespace std; // Updates a node in Binary Index Tree (BIT)// at given index(i) in BIT. The given value// 'val' is added to BITree[i] and// all of its ancestors in tree.void update(int BIT[], int n, int i, int val){ for (; i <= n; i += (i & -i)) { BIT[i] += val; }} // Returns sum of arr[0..i]. This function// assumes that the array is preprocessed// and partial sums of array elements are// stored in BIT[].int query(int BIT[], int i){ int sum = 0; for (; i > 0; i -= (i & -i)) { sum += BIT[i]; } return sum;} // Converts an array to an array with values from 1 to n// and relative order of smaller and greater elements// remains same. For example, {7, -90, 100, 1} is// converted to {3, 1, 4 ,2 }void Convert(int arr[], int n){ int temp[n]; for (int i = 0; i < n; i++) { temp[i] = arr[i]; } sort(temp, temp + n); for (int i = 0; i < n; i++) { arr[i] = lower_bound(temp, temp + n, arr[i]) - temp + 1; }} // Function to find tripletsint getCount(int arr[], int n){ // Decomposition Convert(arr, n); int BIT[n + 1] = { 0 }; int smaller_right[n + 1] = { 0 }; int greater_left[n + 1] = { 0 }; // Find all right side smaller elements for (int i = n - 1; i >= 0; i--) { smaller_right[i] = query(BIT, arr[i]-1); update(BIT, n, arr[i], 1); } for (int i = 0; i <= n; i++) { BIT[i] = 0; } // Find all left side greater elements for (int i = 0; i < n; i++) { greater_left[i] = i - query(BIT, arr[i]); update(BIT, n, arr[i], 1); } // Find the required answer int ans = 0; for (int i = 0; i < n; i++) { ans += greater_left[i] * smaller_right[i]; } // Return the required answer return ans;} // Driver codeint main(){ int arr[] = { 7, 3, 4, 3, 3, 1}; int n = sizeof(arr) / sizeof(arr[0]); cout << getCount(arr, n) << endl; return 0;}", "e": 27940, "s": 25921, "text": null }, { "code": "import java.io.*;import java.util.*; class GFG { public static int lower(int a[], int x) //Returns leftest index of x in sorted arr else n { //If not present returns index of just greater element int n = a.length; int l = 0; int r = n - 1; int ans = n; while(l <= r) { int m = (r - l) / 2 + l; if(a[m] >= x) { ans = m; r = m - 1; } else { l = m + 1; } } return ans; } // Returns sum of arr[0..i]. This function // assumes that the array is preprocessed // and partial sums of array elements are // stored in BIT[]. public static int query(int BIT[], int i) { int sum = 0; for (; i > 0; i -= (i & -i)) { sum += BIT[i]; } return sum; } // Converts an array to an array with values from 1 to n // and relative order of smaller and greater elements // remains same. For example, {7, -90, 100, 1} is // converted to {3, 1, 4 ,2 } public static void Convert(int arr[], int n) { int temp[]=new int[n]; for (int i = 0; i < n; i++) { temp[i] = arr[i]; } Arrays.sort(temp); for (int i = 0; i < n; i++) { arr[i] = lower(temp, arr[i]) + 1; } } // Updates a node in Binary Index Tree (BIT) // at given index(i) in BIT. The given value // 'val' is added to BITree[i] and // all of its ancestors in tree. public static void update(int BIT[], int n, int i, int val) { for (; i <= n; i += (i & -i)) { BIT[i] += val; } } // Function to find triplets public static int getCount(int arr[], int n) { // Decomposition Convert(arr, n); int BIT[] = new int[n+1]; int smaller_right[] = new int[n+1]; int greater_left[] = new int[n+1]; for(int i=0;i<n+1;i++){ BIT[i]=0; smaller_right[i]=0; greater_left[i]=0; } // Find all right side smaller elements for (int i = n - 1; i >= 0; i--) { smaller_right[i] = query(BIT, arr[i]-1); update(BIT, n, arr[i], 1); } for (int i = 0; i <= n; i++) { BIT[i] = 0; } // Find all left side greater elements for (int i = 0; i < n; i++) { greater_left[i] = i - query(BIT, arr[i]); update(BIT, n, arr[i], 1); } // Find the required answer int ans = 0; for (int i = 0; i < n; i++) { ans += greater_left[i] * smaller_right[i]; } // Return the required answer return ans; } public static void main (String[] args) { int arr[] = { 7, 3, 4, 3, 3, 1}; int n = 6; System.out.println(getCount(arr, n)); }}// this code is contributed by Manu Pathria", "e": 30950, "s": 27940, "text": null }, { "code": "# Python3 program to find triplets# a[i]>a[j]>a[k] and i<j<kfrom bisect import bisect_left as lower_bound # Updates a node in Binary Index Tree (BIT)# at given index(i) in BIT. The given value# 'val' is added to BITree[i] and# all of its ancestors in tree.def update(BIT, n, i, val): while i <= n: BIT[i] += val i += (i & -i) # Returns sum of arr[0..i]. This function# assumes that the array is preprocessed# and partial sums of array elements are# stored in BIT[].def query(BIT, i): summ = 0 while i > 0: summ += BIT[i] i -= (i & -i) return summ # Converts an array to an array with values# from 1 to n and relative order of smaller# and greater elements remains same. For example,# {7, -90, 100, 1} is converted to {3, 1, 4 ,2 }def convert(arr, n): temp = [0] * n for i in range(n): temp[i] = arr[i] temp.sort() for i in range(n): arr[i] = lower_bound(temp, arr[i]) + 1 # Function to find tripletsdef getCount(arr, n): # Decomposition convert(arr, n) BIT = [0] * (n + 1) smaller_right = [0] * (n + 1) greater_left = [0] * (n + 1) # Find all right side smaller elements for i in range(n - 1, -1, -1): smaller_right[i] = query(BIT, arr[i] - 1) update(BIT, n, arr[i], 1) for i in range(n + 1): BIT[i] = 0 # Find all left side greater elements for i in range(n): greater_left[i] = i - query(BIT, arr[i]) update(BIT, n, arr[i], 1) # Find the required answer ans = 0 for i in range(n): ans += greater_left[i] * smaller_right[i] # Return the required answer return ans # Driver Codeif __name__ == \"__main__\": arr = [7, 3, 4, 3, 3, 1] n = len(arr) print(getCount(arr, n)) # This code is contributed by# sanjeev2552", "e": 32734, "s": 30950, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ public static int lower(int[] a, int x) //Returns leftest index of x in sorted arr else n { //If not present returns index of just greater element int n = a.Length; int l = 0; int r = n - 1; int ans = n; while(l <= r) { int m = (r - l) / 2 + l; if(a[m] >= x) { ans = m; r = m - 1; } else { l = m + 1; } } return ans; } // Returns sum of arr[0..i]. This function // assumes that the array is preprocessed // and partial sums of array elements are // stored in BIT[]. public static int query(int[] BIT, int i) { int sum = 0; for (; i > 0; i -= (i & -i)) { sum += BIT[i]; } return sum; } // Converts an array to an array with values from 1 to n // and relative order of smaller and greater elements // remains same. For example, {7, -90, 100, 1} is // converted to {3, 1, 4 ,2 } public static void Convert(int[] arr, int n) { int[] temp =new int[n]; for (int i = 0; i < n; i++) { temp[i] = arr[i]; } Array.Sort(temp); for (int i = 0; i < n; i++) { arr[i] = lower(temp, arr[i]) + 1; } } // Updates a node in Binary Index Tree (BIT) // at given index(i) in BIT. The given value // 'val' is added to BITree[i] and // all of its ancestors in tree. public static void update(int[] BIT, int n, int i, int val) { for (; i <= n; i += (i & -i)) { BIT[i] += val; } } // Function to find triplets public static int getCount(int[] arr, int n) { // Decomposition Convert(arr, n); int[] BIT = new int[n + 1]; int[] smaller_right = new int[n + 1]; int[] greater_left = new int[n + 1]; for(int i = 0; i < n + 1; i++) { BIT[i] = 0; smaller_right[i] = 0; greater_left[i] = 0; } // Find all right side smaller elements for (int i = n - 1; i >= 0; i--) { smaller_right[i] = query(BIT, arr[i]-1); update(BIT, n, arr[i], 1); } for (int i = 0; i <= n; i++) { BIT[i] = 0; } // Find all left side greater elements for (int i = 0; i < n; i++) { greater_left[i] = i - query(BIT, arr[i]); update(BIT, n, arr[i], 1); } // Find the required answer int ans = 0; for (int i = 0; i < n; i++) { ans += greater_left[i] * smaller_right[i]; } // Return the required answer return ans; } // Driver code public static void Main () { int[] arr = { 7, 3, 4, 3, 3, 1}; int n = 6; Console.WriteLine(getCount(arr, n)); }} // This code is contributed by target_2.", "e": 35378, "s": 32734, "text": null }, { "code": "<script> // JavaScript program to find triplets// a[i]>a[j]>a[k] and i<j<k // Updates a node in Binary Index Tree (BIT)// at given index(i) in BIT. The given value// 'val' is added to BITree[i] and// all of its ancestors in tree.function update(BIT, n, i, val) { for (; i <= n; i += (i & -i)) { BIT[i] += val; }} // Returns sum of arr[0..i]. This function// assumes that the array is preprocessed// and partial sums of array elements are// stored in BIT[].function query(BIT, i) { let sum = 0; for (; i > 0; i -= (i & -i)) { sum += BIT[i]; } return sum;} //Returns leftest index of x in sorted arr else n//If not present returns index of just greater element function lower(a, x) { let n = a.length; let l = 0; let r = n - 1; let ans = n; while (l <= r) { let m = Math.floor((r - l) / 2) + l; if (a[m] >= x) { ans = m; r = m - 1; } else { l = m + 1; } } return ans;} // Converts an array to an array with values from 1 to n// and relative order of smaller and greater elements// remains same. For example, {7, -90, 100, 1} is// converted to {3, 1, 4 ,2 }function Convert(arr, n) { let temp = new Array(n); for (let i = 0; i < n; i++) { temp[i] = arr[i]; } temp.sort((a, b) => a - b); for (let i = 0; i < n; i++) { arr[i] = lower(temp, arr[i]) + 1; }} // Function to find tripletsfunction getCount(arr, n) { // Decomposition Convert(arr, n); let BIT = new Array(n + 1).fill(0); let smaller_right = new Array(n + 1).fill(0); let greater_left = new Array(n + 1).fill(0); // Find all right side smaller elements for (let i = n - 1; i >= 0; i--) { smaller_right[i] = query(BIT, arr[i] - 1); update(BIT, n, arr[i], 1); } for (let i = 0; i <= n; i++) { BIT[i] = 0; } // Find all left side greater elements for (let i = 0; i < n; i++) { greater_left[i] = i - query(BIT, arr[i]); update(BIT, n, arr[i], 1); } // Find the required answer let ans = 0; for (let i = 0; i < n; i++) { ans += greater_left[i] * smaller_right[i]; } // Return the required answer return ans;} // Driver code let arr = [7, 3, 4, 3, 3, 1]; let n = arr.length; document.write(getCount(arr, n) + \"<br>\"); // This code is contributed by _saurabh_jaiswal </script>", "e": 37764, "s": 35378, "text": null }, { "code": null, "e": 37774, "s": 37764, "text": "Output: " }, { "code": null, "e": 37776, "s": 37774, "text": "8" }, { "code": null, "e": 37791, "s": 37778, "text": "Akanksha_Rai" }, { "code": null, "e": 37803, "s": 37791, "text": "sanjeev2552" }, { "code": null, "e": 37815, "s": 37803, "text": "manupathria" }, { "code": null, "e": 37832, "s": 37815, "text": "_saurabh_jaiswal" }, { "code": null, "e": 37841, "s": 37832, "text": "target_2" }, { "code": null, "e": 37865, "s": 37841, "text": "Constructive Algorithms" }, { "code": null, "e": 37872, "s": 37865, "text": "prefix" }, { "code": null, "e": 37885, "s": 37872, "text": "Suffix-Array" }, { "code": null, "e": 37892, "s": 37885, "text": "Arrays" }, { "code": null, "e": 37899, "s": 37892, "text": "Arrays" }, { "code": null, "e": 37997, "s": 37899, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38065, "s": 37997, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 38113, "s": 38065, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 38157, "s": 38113, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 38189, "s": 38157, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 38212, "s": 38189, "text": "Introduction to Arrays" }, { "code": null, "e": 38226, "s": 38212, "text": "Linear Search" }, { "code": null, "e": 38271, "s": 38226, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 38292, "s": 38271, "text": "Linked List vs Array" }, { "code": null, "e": 38346, "s": 38292, "text": "Queue | Set 1 (Introduction and Array Implementation)" } ]
GATE CS 2021 Official Important Dates - GeeksforGeeks
03 Jul, 2021 IIT Bombay is organizing GATE 2021. In this year, The GATE authority 2021 has made major changes and has also revised the syllabus of various GATE Papers. They also increase the number of consecutive days from three weeks to two weeks, due to COVID-19 pandemic. Before, it GATE exam was organized in three weeks but not it is going in only two weeks (may because of COVID-19 pandemic). These are Official date(s) of the respective event of the GATE 2021 exam : GATE CS 2022 TS GATE 2021 Examination Forenoon: 9:00 AM to 12:00 Noon (Tentative) Afternoon: 3:00 PM to 6:00 PM (Tentative) Friday Saturday Sunday Friday Saturday Sunday 5th February 2021 6th February 2021 7th February 2021 12th February 2021 13th February 2021 14th February 2021 The health and safety of the candidates are of utmost priority. Due to current COVID-19 pandemic situation, dates mentioned here are subject to change. In rare cases, it may be necessary to postpone the GATE 2021 examination because of situations beyond the control of GATE committee. All updates will be available on this website. Official website for GATE 2021 exam – GATE IIT BombayGATE CS Notes according to GATE 2021 syllabusGATE CS previous year solved papersImportant topics for GATE 2021 Computer ScienceLast minute notes for GATE CSGATE CS 2017 Mock TestsGATE CS 2018 Mock TestsGATE CS 2019 Mock TestsArticles on Computer Science subjects Official website for GATE 2021 exam – GATE IIT Bombay GATE CS Notes according to GATE 2021 syllabus GATE CS previous year solved papers Important topics for GATE 2021 Computer Science Last minute notes for GATE CS GATE CS 2017 Mock Tests GATE CS 2018 Mock Tests GATE CS 2019 Mock Tests Articles on Computer Science subjects Computer Subject GATE CS GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between NP hard and NP complete problem Software Engineering | Classification of Software Requirements Cloud Based Services Functional Programming Paradigm What is Transmission Control Protocol (TCP)? Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 24256, "s": 24228, "text": "\n03 Jul, 2021" }, { "code": null, "e": 24411, "s": 24256, "text": "IIT Bombay is organizing GATE 2021. In this year, The GATE authority 2021 has made major changes and has also revised the syllabus of various GATE Papers." }, { "code": null, "e": 24642, "s": 24411, "text": "They also increase the number of consecutive days from three weeks to two weeks, due to COVID-19 pandemic. Before, it GATE exam was organized in three weeks but not it is going in only two weeks (may because of COVID-19 pandemic)." }, { "code": null, "e": 24717, "s": 24642, "text": "These are Official date(s) of the respective event of the GATE 2021 exam :" }, { "code": null, "e": 24733, "s": 24717, "text": "GATE CS 2022 TS" }, { "code": null, "e": 24865, "s": 24733, "text": "GATE 2021 Examination\nForenoon: 9:00 AM to 12:00 Noon\n (Tentative)\nAfternoon: 3:00 PM to 6:00 PM\n (Tentative) " }, { "code": null, "e": 24913, "s": 24865, "text": "Friday\nSaturday\nSunday\n\nFriday\nSaturday\nSunday " }, { "code": null, "e": 25026, "s": 24913, "text": "5th February 2021\n6th February 2021\n7th February 2021\n\n12th February 2021\n13th February 2021\n14th February 2021 " }, { "code": null, "e": 25358, "s": 25026, "text": "The health and safety of the candidates are of utmost priority. Due to current COVID-19 pandemic situation, dates mentioned here are subject to change. In rare cases, it may be necessary to postpone the GATE 2021 examination because of situations beyond the control of GATE committee. All updates will be available on this website." }, { "code": null, "e": 25674, "s": 25358, "text": "Official website for GATE 2021 exam – GATE IIT BombayGATE CS Notes according to GATE 2021 syllabusGATE CS previous year solved papersImportant topics for GATE 2021 Computer ScienceLast minute notes for GATE CSGATE CS 2017 Mock TestsGATE CS 2018 Mock TestsGATE CS 2019 Mock TestsArticles on Computer Science subjects" }, { "code": null, "e": 25728, "s": 25674, "text": "Official website for GATE 2021 exam – GATE IIT Bombay" }, { "code": null, "e": 25774, "s": 25728, "text": "GATE CS Notes according to GATE 2021 syllabus" }, { "code": null, "e": 25810, "s": 25774, "text": "GATE CS previous year solved papers" }, { "code": null, "e": 25858, "s": 25810, "text": "Important topics for GATE 2021 Computer Science" }, { "code": null, "e": 25888, "s": 25858, "text": "Last minute notes for GATE CS" }, { "code": null, "e": 25912, "s": 25888, "text": "GATE CS 2017 Mock Tests" }, { "code": null, "e": 25936, "s": 25912, "text": "GATE CS 2018 Mock Tests" }, { "code": null, "e": 25960, "s": 25936, "text": "GATE CS 2019 Mock Tests" }, { "code": null, "e": 25998, "s": 25960, "text": "Articles on Computer Science subjects" }, { "code": null, "e": 26015, "s": 25998, "text": "Computer Subject" }, { "code": null, "e": 26023, "s": 26015, "text": "GATE CS" }, { "code": null, "e": 26029, "s": 26023, "text": "GBlog" }, { "code": null, "e": 26127, "s": 26029, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26178, "s": 26127, "text": "Difference between NP hard and NP complete problem" }, { "code": null, "e": 26241, "s": 26178, "text": "Software Engineering | Classification of Software Requirements" }, { "code": null, "e": 26262, "s": 26241, "text": "Cloud Based Services" }, { "code": null, "e": 26294, "s": 26262, "text": "Functional Programming Paradigm" }, { "code": null, "e": 26339, "s": 26294, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 26359, "s": 26339, "text": "Layers of OSI Model" }, { "code": null, "e": 26383, "s": 26359, "text": "ACID Properties in DBMS" }, { "code": null, "e": 26396, "s": 26383, "text": "TCP/IP Model" }, { "code": null, "e": 26423, "s": 26396, "text": "Types of Operating Systems" } ]
Using AWS Lambda@Edge with CloudFront
Lambda@Edge is an addition to the AWS Lambda compute service which is used to customize the content that cloudfront delivers. The block diagram which shows the working of AWS Lambda with cloudfront from AWS is shown below − There are four ways in which AWS Lambda can be used − Viewer Request − End user makes the request called Viewer Request to CloudFront Viewer Request − End user makes the request called Viewer Request to CloudFront Origin Request − CloudFront forwards the request to the origin Origin Request − CloudFront forwards the request to the origin Origin Response − CloudFront receives the response from the origin Origin Response − CloudFront receives the response from the origin Viewer Response − CloudFront send the response to the viewer Viewer Response − CloudFront send the response to the viewer We can use Lambda@Edge for the following purposes − To change the headers at the request and response time. To change the headers at the request and response time. Add cookies details to the headers. Carry out AB testing based on the request and response. Add cookies details to the headers. Carry out AB testing based on the request and response. Redirect the URL to another site, based on the header details. Redirect the URL to another site, based on the header details. We can fetch the user-agent from the headers and find out the details of the browser, OS, etc. We can fetch the user-agent from the headers and find out the details of the browser, OS, etc. To start with working on CloudFront and Lambda@Edge, we need the following − Create S3 storage bucket with file details Create S3 storage bucket with file details Create role which will allow permission to work with CloudFront and Lambda@Edge Create role which will allow permission to work with CloudFront and Lambda@Edge Create CloudFront distribution Create CloudFront distribution Create lambda function Create lambda function Add lambda function details to cloudfront Add lambda function details to cloudfront Check the cloudfront url in browser Check the cloudfront url in browser We will work on an example with CloudFront and Lambda@Egde, wherein we will host the page and change the response when detected as desktop and devices. Login to AWS console and create a bucket in S3 and add the . html file which you want to display. Click on S3 and Create bucket as shown below − Now, click Create bucket button and add the details of the bucket as shown below − Click on Create button and upload the .html in it. Go to AWS console and click IAM. Now, click Roles -> Create role button as shown − Choose the permission for S3, Lambda and Cloudfront. It is a good practice to create the policy giving permission to only the required function, storage by using the ARN details. In the example discussed below, we are showing the Full Access permission. Policies for the role name role for cloudfront is added as shown above. Click on Create role. All the policy required for lambda@edge and cloudfront are as shown above. There is a additional step to be done here since incase of cloudfront the url will be available across region and it needs a trust relationship between the services we are using. Now, for the role created, click on Trust relationships tab as shown − Click on Edit Trust Relationship as shown below − It displays a policy document. We need to add the other services in the Principal -> Service which we are planning to use. The final trust relationship policy document is as shown below − Click Update Trust Policy button to save the changes. Go to CloudFront service as shown below − Click on CloudFront service and click on Create Distribution − Let us look into these settings one by one − Origin Settings Various parameters of Origin settings are explained as below − Origin Domain Name − This is the name of the S3 bucket where we have stored the html files. We can also store images, if any, in the S3 bucket by creating folders of our choice. Origin Path − Here you need to enter the name of the folder where the files are stored. At present, we do not have this folder, so we will keep it blank for now. Origin ID − It gets populated when the origin domain name is selected. You can change the id as per your choice. Restrict Bucket Access − In this, we will choose the option yes. Here we need security for the S3 bucket so that no one has the access to the S3 bucket. For this option there are some more options populated like Origin Access Identity, Comment and Grant Read Permission on Bucket. Origin Access Identity − We have used create a new identity option. You can also choose the existing identity. This creates a new identity which is used by CloudFront to read the details from S3 bucket. Grand Read Permission on Bucket − For this, choose the option Yes. Origin Custom Headers − We will keep the headers blank here, as we do not need the details right now. Next, let us discuss and fill up the Behaviour Settings for Cloudront distribution − Now, select the protocol – https or http, and the caching option. Note that the default caching is 86400 or 24 hrs. You can change this value as per the requirement. Click Object Caching (customize option) to change the caching. You can use smooth streaming in case if there any videos on your page. Here, we are keeping the default option available. Once the lambda function is created, its details will be added. The details for distribution settings are shown below − Various parameters of distribution settings are explained below − Price class − It has details like the origin of users traffic. Note that here we have selected the default one - Use All Edge Locations. AWS WAF Web ACL − This is for web application firewall selection. Here, it has option as None. First, we need to create the firewall in AWS. It provides security to the site. Alternate Domain Names − Here you can specify the domain name if you have. SSL Certificate − This has all the details to be selected for SSL certificate. We will keep the default ones. Default Root Object − Here we will specify the filename which we have uploaded in S3. For this, we need the content from the .html to be displayed by default. For the rest, we will keep the default setting. Click Create Distribution button to add the distribution. Note that the distribution will take some time to show the status as deployed. Go to AWS console and create Lambda function. In AWS Lambda code, we will take the request headers and check the user-agent. If the user-agent is from desktop, we will change the response to display message as “DESKTOP : Welcome to AWS Lambda with Cloudfront!” and if device the message will be“MOBILE DEVICES : Hello from Lambda@Edge!” The corresponding AWS Lambda code is as shown below − let content = ` <\!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Simple Lambda@Edge Static Content Response</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h1>MOBILE DEVICES : Hello from Lambda@Edge!</h1> </body> </html> `; let content1 = ` <\!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Simple Lambda@Edge Static Content Response</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h1>DESKTOP : Welcome to AWS Lambda with Cloudfront!</h1> </body> </html> `; exports.handler = (event, context, callback) => { let request = event.Records[0].cf.request; let finalrequest = JSON.stringify(request); let headers = request.headers; let useragent = JSON.stringify(headers["user-agent"][0].value); let str = ""; if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|mobile|CriOS/i.test(useragent)) { str = content; } else { str = content1; } const response = { status: '200', statusDescription: 'OK', body: str+useragent, }; callback(null, response); }; Now, save the Lambda function. Note that we need to publish the Lambda function so that it can be used with all regions. To publish, we need to do the following − From Actions dropdown, select Publish new version as shown below − If you, click Publish new version, it displays the following screen − Now, enter the Version description and click Publish. The ARN will display the version of the AWS Lambda function created as shown below − Add CloudFront trigger to the new version created as shown below − Now, add the configuration details for CloudFront. The CloudFront event has option for Viewer request, Origin request, Origin response, and Viewer response. Next, choose the CloudFront distribution created earlier. From events, we will select Viewer request. Based on the viewer request, the desktop/device from user-agent will be decided and the response will be changed. Next, add the trigger details. Once the trigger is added, we need to wait for the distribution from CloudFront to be deployed. Once the status is changed to Deployed, we can test the CloudFront url and check the domain name in browser. The display in desktop browser is as shown below. Here we have printed the user-agent from the viewer-request event. This is the display in mobile device. Thus, in the above example, we have used Lambda@Edge to change response on desktop and mobile device. 35 Lectures 7.5 hours Mr. Pradeep Kshetrapal 30 Lectures 3.5 hours Priyanka Choudhary 44 Lectures 7.5 hours Eduonix Learning Solutions 51 Lectures 6 hours Manuj Aggarwal 41 Lectures 5 hours AR Shankar 14 Lectures 1 hours Zach Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2532, "s": 2406, "text": "Lambda@Edge is an addition to the AWS Lambda compute service which is used to customize the content that cloudfront delivers." }, { "code": null, "e": 2630, "s": 2532, "text": "The block diagram which shows the working of AWS Lambda with cloudfront from AWS is shown below −" }, { "code": null, "e": 2684, "s": 2630, "text": "There are four ways in which AWS Lambda can be used −" }, { "code": null, "e": 2764, "s": 2684, "text": "Viewer Request − End user makes the request called Viewer Request to CloudFront" }, { "code": null, "e": 2844, "s": 2764, "text": "Viewer Request − End user makes the request called Viewer Request to CloudFront" }, { "code": null, "e": 2907, "s": 2844, "text": "Origin Request − CloudFront forwards the request to the origin" }, { "code": null, "e": 2970, "s": 2907, "text": "Origin Request − CloudFront forwards the request to the origin" }, { "code": null, "e": 3037, "s": 2970, "text": "Origin Response − CloudFront receives the response from the origin" }, { "code": null, "e": 3104, "s": 3037, "text": "Origin Response − CloudFront receives the response from the origin" }, { "code": null, "e": 3165, "s": 3104, "text": "Viewer Response − CloudFront send the response to the viewer" }, { "code": null, "e": 3226, "s": 3165, "text": "Viewer Response − CloudFront send the response to the viewer" }, { "code": null, "e": 3278, "s": 3226, "text": "We can use Lambda@Edge for the following purposes −" }, { "code": null, "e": 3334, "s": 3278, "text": "To change the headers at the request and response time." }, { "code": null, "e": 3390, "s": 3334, "text": "To change the headers at the request and response time." }, { "code": null, "e": 3482, "s": 3390, "text": "Add cookies details to the headers. Carry out AB testing based on the request and response." }, { "code": null, "e": 3574, "s": 3482, "text": "Add cookies details to the headers. Carry out AB testing based on the request and response." }, { "code": null, "e": 3637, "s": 3574, "text": "Redirect the URL to another site, based on the header details." }, { "code": null, "e": 3700, "s": 3637, "text": "Redirect the URL to another site, based on the header details." }, { "code": null, "e": 3795, "s": 3700, "text": "We can fetch the user-agent from the headers and find out the details of the browser, OS, etc." }, { "code": null, "e": 3890, "s": 3795, "text": "We can fetch the user-agent from the headers and find out the details of the browser, OS, etc." }, { "code": null, "e": 3967, "s": 3890, "text": "To start with working on CloudFront and Lambda@Edge, we need the following −" }, { "code": null, "e": 4010, "s": 3967, "text": "Create S3 storage bucket with file details" }, { "code": null, "e": 4053, "s": 4010, "text": "Create S3 storage bucket with file details" }, { "code": null, "e": 4133, "s": 4053, "text": "Create role which will allow permission to work with CloudFront and Lambda@Edge" }, { "code": null, "e": 4213, "s": 4133, "text": "Create role which will allow permission to work with CloudFront and Lambda@Edge" }, { "code": null, "e": 4244, "s": 4213, "text": "Create CloudFront distribution" }, { "code": null, "e": 4275, "s": 4244, "text": "Create CloudFront distribution" }, { "code": null, "e": 4298, "s": 4275, "text": "Create lambda function" }, { "code": null, "e": 4321, "s": 4298, "text": "Create lambda function" }, { "code": null, "e": 4363, "s": 4321, "text": "Add lambda function details to cloudfront" }, { "code": null, "e": 4405, "s": 4363, "text": "Add lambda function details to cloudfront" }, { "code": null, "e": 4441, "s": 4405, "text": "Check the cloudfront url in browser" }, { "code": null, "e": 4477, "s": 4441, "text": "Check the cloudfront url in browser" }, { "code": null, "e": 4629, "s": 4477, "text": "We will work on an example with CloudFront and Lambda@Egde, wherein we will host the page and change the response when detected as desktop and devices." }, { "code": null, "e": 4727, "s": 4629, "text": "Login to AWS console and create a bucket in S3 and add the . html file which you want to display." }, { "code": null, "e": 4774, "s": 4727, "text": "Click on S3 and Create bucket as shown below −" }, { "code": null, "e": 4857, "s": 4774, "text": "Now, click Create bucket button and add the details of the bucket as shown below −" }, { "code": null, "e": 4908, "s": 4857, "text": "Click on Create button and upload the .html in it." }, { "code": null, "e": 4941, "s": 4908, "text": "Go to AWS console and click IAM." }, { "code": null, "e": 4991, "s": 4941, "text": "Now, click Roles -> Create role button as shown −" }, { "code": null, "e": 5170, "s": 4991, "text": "Choose the permission for S3, Lambda and Cloudfront. It is a good practice to create the policy giving permission to only the required function, storage by using the ARN details." }, { "code": null, "e": 5339, "s": 5170, "text": "In the example discussed below, we are showing the Full Access permission. Policies for the role name role for cloudfront is added as shown above. Click on Create role." }, { "code": null, "e": 5593, "s": 5339, "text": "All the policy required for lambda@edge and cloudfront are as shown above. There is a additional step to be done here since incase of cloudfront the url will be available across region and it needs a trust relationship between the services we are using." }, { "code": null, "e": 5664, "s": 5593, "text": "Now, for the role created, click on Trust relationships tab as shown −" }, { "code": null, "e": 5714, "s": 5664, "text": "Click on Edit Trust Relationship as shown below −" }, { "code": null, "e": 5902, "s": 5714, "text": "It displays a policy document. We need to add the other services in the Principal -> Service which we are planning to use. The final trust relationship policy document is as shown below −" }, { "code": null, "e": 5956, "s": 5902, "text": "Click Update Trust Policy button to save the changes." }, { "code": null, "e": 5998, "s": 5956, "text": "Go to CloudFront service as shown below −" }, { "code": null, "e": 6061, "s": 5998, "text": "Click on CloudFront service and click on Create Distribution −" }, { "code": null, "e": 6106, "s": 6061, "text": "Let us look into these settings one by one −" }, { "code": null, "e": 6122, "s": 6106, "text": "Origin Settings" }, { "code": null, "e": 6185, "s": 6122, "text": "Various parameters of Origin settings are explained as below −" }, { "code": null, "e": 6363, "s": 6185, "text": "Origin Domain Name − This is the name of the S3 bucket where we have stored the html files. We can also store images, if any, in the S3 bucket by creating folders of our choice." }, { "code": null, "e": 6525, "s": 6363, "text": "Origin Path − Here you need to enter the name of the folder where the files are stored. At present, we do not have this folder, so we will keep it blank for now." }, { "code": null, "e": 6638, "s": 6525, "text": "Origin ID − It gets populated when the origin domain name is selected. You can change the id as per your choice." }, { "code": null, "e": 6919, "s": 6638, "text": "Restrict Bucket Access − In this, we will choose the option yes. Here we need security for the S3 bucket so that no one has the access to the S3 bucket. For this option there are some more options populated like Origin Access Identity, Comment and Grant Read Permission on Bucket." }, { "code": null, "e": 7122, "s": 6919, "text": "Origin Access Identity − We have used create a new identity option. You can also choose the existing identity. This creates a new identity which is used by CloudFront to read the details from S3 bucket." }, { "code": null, "e": 7189, "s": 7122, "text": "Grand Read Permission on Bucket − For this, choose the option Yes." }, { "code": null, "e": 7291, "s": 7189, "text": "Origin Custom Headers − We will keep the headers blank here, as we do not need the details right now." }, { "code": null, "e": 7376, "s": 7291, "text": "Next, let us discuss and fill up the Behaviour Settings for Cloudront distribution −" }, { "code": null, "e": 7542, "s": 7376, "text": "Now, select the protocol – https or http, and the caching option. Note that the default caching is 86400 or 24 hrs. You can change this value as per the requirement." }, { "code": null, "e": 7791, "s": 7542, "text": "Click Object Caching (customize option) to change the caching. You can use smooth streaming in case if there any videos on your page. Here, we are keeping the default option available. Once the lambda function is created, its details will be added." }, { "code": null, "e": 7847, "s": 7791, "text": "The details for distribution settings are shown below −" }, { "code": null, "e": 7913, "s": 7847, "text": "Various parameters of distribution settings are explained below −" }, { "code": null, "e": 8050, "s": 7913, "text": "Price class − It has details like the origin of users traffic. Note that here we have selected the default one - Use All Edge Locations." }, { "code": null, "e": 8225, "s": 8050, "text": "AWS WAF Web ACL − This is for web application firewall selection. Here, it has option as None. First, we need to create the firewall in AWS. It provides security to the site." }, { "code": null, "e": 8300, "s": 8225, "text": "Alternate Domain Names − Here you can specify the domain name if you have." }, { "code": null, "e": 8410, "s": 8300, "text": "SSL Certificate − This has all the details to be selected for SSL certificate. We will keep the default ones." }, { "code": null, "e": 8569, "s": 8410, "text": "Default Root Object − Here we will specify the filename which we have uploaded in S3. For this, we need the content from the .html to be displayed by default." }, { "code": null, "e": 8617, "s": 8569, "text": "For the rest, we will keep the default setting." }, { "code": null, "e": 8675, "s": 8617, "text": "Click Create Distribution button to add the distribution." }, { "code": null, "e": 8754, "s": 8675, "text": "Note that the distribution will take some time to show the status as deployed." }, { "code": null, "e": 8800, "s": 8754, "text": "Go to AWS console and create Lambda function." }, { "code": null, "e": 9091, "s": 8800, "text": "In AWS Lambda code, we will take the request headers and check the user-agent. If the user-agent is from desktop, we will change the response to display message as “DESKTOP : Welcome to AWS Lambda with Cloudfront!” and if device the message will be“MOBILE DEVICES : Hello from Lambda@Edge!”" }, { "code": null, "e": 9145, "s": 9091, "text": "The corresponding AWS Lambda code is as shown below −" }, { "code": null, "e": 10398, "s": 9145, "text": "let content = `\n<\\!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Simple Lambda@Edge Static Content Response</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n </head>\n \n <body>\n <h1>MOBILE DEVICES : Hello from Lambda@Edge!</h1>\n </body>\n</html>\n`;\nlet content1 = `\n<\\!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Simple Lambda@Edge Static Content Response</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n </head>\n \n <body>\n <h1>DESKTOP : Welcome to AWS Lambda with Cloudfront!</h1>\n </body>\n</html>\n`;\nexports.handler = (event, context, callback) => {\n let request = event.Records[0].cf.request;\n let finalrequest = JSON.stringify(request);\n let headers = request.headers;\n let useragent = JSON.stringify(headers[\"user-agent\"][0].value);\n let str = \"\";\n if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|mobile|CriOS/i.test(useragent)) {\n str = content;\n } else {\n str = content1;\n }\n const response = {\n status: '200',\n statusDescription: 'OK', \n body: str+useragent,\n };\n callback(null, response);\n};" }, { "code": null, "e": 10561, "s": 10398, "text": "Now, save the Lambda function. Note that we need to publish the Lambda function so that it can be used with all regions. To publish, we need to do the following −" }, { "code": null, "e": 10628, "s": 10561, "text": "From Actions dropdown, select Publish new version as shown below −" }, { "code": null, "e": 10698, "s": 10628, "text": "If you, click Publish new version, it displays the following screen −" }, { "code": null, "e": 10837, "s": 10698, "text": "Now, enter the Version description and click Publish. The ARN will display the version of the AWS Lambda function created as shown below −" }, { "code": null, "e": 10904, "s": 10837, "text": "Add CloudFront trigger to the new version created as shown below −" }, { "code": null, "e": 11061, "s": 10904, "text": "Now, add the configuration details for CloudFront. The CloudFront event has option for Viewer request, Origin request, Origin response, and Viewer response." }, { "code": null, "e": 11308, "s": 11061, "text": "Next, choose the CloudFront distribution created earlier. From events, we will select Viewer request. Based on the viewer request, the desktop/device from user-agent will be decided and the response will be changed. Next, add the trigger details." }, { "code": null, "e": 11404, "s": 11308, "text": "Once the trigger is added, we need to wait for the distribution from CloudFront to be deployed." }, { "code": null, "e": 11513, "s": 11404, "text": "Once the status is changed to Deployed, we can test the CloudFront url and check the domain name in browser." }, { "code": null, "e": 11630, "s": 11513, "text": "The display in desktop browser is as shown below. Here we have printed the user-agent from the viewer-request event." }, { "code": null, "e": 11668, "s": 11630, "text": "This is the display in mobile device." }, { "code": null, "e": 11770, "s": 11668, "text": "Thus, in the above example, we have used Lambda@Edge to change response on desktop and mobile device." }, { "code": null, "e": 11805, "s": 11770, "text": "\n 35 Lectures \n 7.5 hours \n" }, { "code": null, "e": 11829, "s": 11805, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 11864, "s": 11829, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 11884, "s": 11864, "text": " Priyanka Choudhary" }, { "code": null, "e": 11919, "s": 11884, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 11947, "s": 11919, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11980, "s": 11947, "text": "\n 51 Lectures \n 6 hours \n" }, { "code": null, "e": 11996, "s": 11980, "text": " Manuj Aggarwal" }, { "code": null, "e": 12029, "s": 11996, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 12041, "s": 12029, "text": " AR Shankar" }, { "code": null, "e": 12074, "s": 12041, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 12087, "s": 12074, "text": " Zach Miller" }, { "code": null, "e": 12094, "s": 12087, "text": " Print" }, { "code": null, "e": 12105, "s": 12094, "text": " Add Notes" } ]
C program to print string tokens
Suppose we have a string s that contains a sentence with few words. We shall have to print each word into new lines. To do this we can use the strtok() function under the string.h header file. This function takes the string and a delimiter. Here the delimiter is blank space " ". So, if the input is like s = "Let us see some string tokenizing fun", then the output will be Let us see some string tokenizing fun To solve this, we will follow these steps − token := first word by using strtok(s, " ") here delimiter is " " token := first word by using strtok(s, " ") here delimiter is " " while token is non-zero, do:display tokentoken := next token of s, from now pass NULL as first argument of strtok with same delimiter space " ". while token is non-zero, do: display token display token token := next token of s, from now pass NULL as first argument of strtok with same delimiter space " ". token := next token of s, from now pass NULL as first argument of strtok with same delimiter space " ". Let us see the following implementation to get better understanding − #include <stdio.h> #include <string.h> int main(){ char s[] = "Let us see some string tokenizing fun"; char* token = strtok(s, " "); while (token) { printf("%s\n", token); token = strtok(NULL, " "); } } Let us see some string tokenizing fun Let us see some string tokenizing fun
[ { "code": null, "e": 1342, "s": 1062, "text": "Suppose we have a string s that contains a sentence with few words. We shall have to print each word into new lines. To do this we can use the strtok() function under the string.h header file. This function takes the string and a delimiter. Here the delimiter is blank space \" \"." }, { "code": null, "e": 1436, "s": 1342, "text": "So, if the input is like s = \"Let us see some string tokenizing fun\", then the output will be" }, { "code": null, "e": 1474, "s": 1436, "text": "Let\nus\nsee\nsome\nstring\ntokenizing\nfun" }, { "code": null, "e": 1518, "s": 1474, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1584, "s": 1518, "text": "token := first word by using strtok(s, \" \") here delimiter is \" \"" }, { "code": null, "e": 1650, "s": 1584, "text": "token := first word by using strtok(s, \" \") here delimiter is \" \"" }, { "code": null, "e": 1795, "s": 1650, "text": "while token is non-zero, do:display tokentoken := next token of s, from now pass NULL as first argument of strtok with same delimiter space \" \"." }, { "code": null, "e": 1824, "s": 1795, "text": "while token is non-zero, do:" }, { "code": null, "e": 1838, "s": 1824, "text": "display token" }, { "code": null, "e": 1852, "s": 1838, "text": "display token" }, { "code": null, "e": 1956, "s": 1852, "text": "token := next token of s, from now pass NULL as first argument of strtok with same delimiter space \" \"." }, { "code": null, "e": 2060, "s": 1956, "text": "token := next token of s, from now pass NULL as first argument of strtok with same delimiter space \" \"." }, { "code": null, "e": 2130, "s": 2060, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2366, "s": 2130, "text": "#include <stdio.h>\n#include <string.h>\nint main(){\n char s[] = \"Let us see some string tokenizing fun\";\n char* token = strtok(s, \" \");\n while (token) {\n printf(\"%s\\n\", token);\n token = strtok(NULL, \" \");\n }\n}\n" }, { "code": null, "e": 2404, "s": 2366, "text": "Let us see some string tokenizing fun" }, { "code": null, "e": 2442, "s": 2404, "text": "Let\nus\nsee\nsome\nstring\ntokenizing\nfun" } ]
Decimal.Divide() Method in C#
The Decimal.Divide() method in C# is used to divide two specified Decimal values. Following is the syntax − public static decimal Divide (decimal val1, decimal val2); Above, val1 is the dividend, whereas val2 is the divisor. Let us now see an example to implement the Decimal.Divide() method − using System; public class Demo { public static void Main(){ Decimal val1 = 65.15m; Decimal val2 = 5.15m; Console.WriteLine("Decimal 1 = "+val1); Console.WriteLine("Decimal 2 = "+val2); Console.WriteLine("After Division = "+(Decimal.Divide(val1,val2))); } } This will produce the following output − Decimal 1 = 65.15 Decimal 2 = 5.15 After Division = 12.650485436893203883495145631 Let us now see another example to implement the Decimal.Divide() method − using System; public class Demo { public static void Main(){ Decimal val1 = 1.0m; Decimal val2 = 1.0m; Console.WriteLine("Decimal 1 = "+val1); Console.WriteLine("Decimal 2 = "+val2); Console.WriteLine("After Division = "+(Decimal.Divide(val1,val2))); } } This will produce the following output − Decimal 1 = 1.0 Decimal 2 = 1.0 After Division = 1
[ { "code": null, "e": 1144, "s": 1062, "text": "The Decimal.Divide() method in C# is used to divide two specified Decimal values." }, { "code": null, "e": 1170, "s": 1144, "text": "Following is the syntax −" }, { "code": null, "e": 1229, "s": 1170, "text": "public static decimal Divide (decimal val1, decimal val2);" }, { "code": null, "e": 1287, "s": 1229, "text": "Above, val1 is the dividend, whereas val2 is the divisor." }, { "code": null, "e": 1356, "s": 1287, "text": "Let us now see an example to implement the Decimal.Divide() method −" }, { "code": null, "e": 1650, "s": 1356, "text": "using System;\npublic class Demo {\n public static void Main(){\n Decimal val1 = 65.15m;\n Decimal val2 = 5.15m;\n Console.WriteLine(\"Decimal 1 = \"+val1);\n Console.WriteLine(\"Decimal 2 = \"+val2);\n Console.WriteLine(\"After Division = \"+(Decimal.Divide(val1,val2)));\n }\n}" }, { "code": null, "e": 1691, "s": 1650, "text": "This will produce the following output −" }, { "code": null, "e": 1774, "s": 1691, "text": "Decimal 1 = 65.15\nDecimal 2 = 5.15\nAfter Division = 12.650485436893203883495145631" }, { "code": null, "e": 1848, "s": 1774, "text": "Let us now see another example to implement the Decimal.Divide() method −" }, { "code": null, "e": 2139, "s": 1848, "text": "using System;\npublic class Demo {\n public static void Main(){\n Decimal val1 = 1.0m;\n Decimal val2 = 1.0m;\n Console.WriteLine(\"Decimal 1 = \"+val1);\n Console.WriteLine(\"Decimal 2 = \"+val2);\n Console.WriteLine(\"After Division = \"+(Decimal.Divide(val1,val2)));\n }\n}" }, { "code": null, "e": 2180, "s": 2139, "text": "This will produce the following output −" }, { "code": null, "e": 2231, "s": 2180, "text": "Decimal 1 = 1.0\nDecimal 2 = 1.0\nAfter Division = 1" } ]
Understanding basic JavaScript codes. - GeeksforGeeks
30 Apr, 2020 Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog.<script> tags can be put between the <head> and </head> tags or between <body> and </body> tags. type attribute was the most important attribute of <script> tag. However, it is no longer used. Browser understands that <script> tag has JavaScript code inside it. <script type="text/javascript"> How to write, save and run codes:Method 1:1. Use any note editor like Notepad, Notepad++ to write the code.2. Save the page with .html extension and load it in web browser. Method 2:1. Create a .js file, and write your JS code in this file using your favorite editor.2. Add <script src="relative_path_to_file/file_name.js"></script> in the end of <body> tag inside HTML file. Code for Painting the page light blue <!DOCTYPE html><html> <head> <title></title> </head> <body bgcolor="white"> <p>Paragraph 1</p> <script type="text/javascript"> document.bgColor ="lightblue"; </script> </body><html> Output: The colour of web-page is light blue , but the opening body tag is defined to set background colour to be white. <body bgcolor="white"> The background colour of page is light blue because JavaScript is used to set the document's background colour to be light blue. document.bgcolor="lightblue"; Learning from the code:1. Page is known as document for the purpose of scripting in a web page.2. Properties of the document can be referenced by writing document followed by a dot, followed by the property name. The document has lots of properties.3. After <script> tag browser starts to interpret the text as JavaScript until the </script> comes. Code to write something to a web page using JavaScript:Lets write “Hello World!” to a blank page using JavaScript. DISPLAYING THE RESULT ON THE WEBPAGE. <!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”> <head> <title></title> </head> <body> <p id="ResultsP"></p> <script type="text/javascript">//Script Block 1 document.getElementById('ResultsP').innerHTML ='Hello World!'; </script> </body><html> Output: Learning from the code:1. The following line has been added to this code. <!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”> This lets the web browser know that user is using XHTML. It doesn’t actually make any difference to the code; it would work just fine without the extra lines. 2. Notice that <p> tag has been given an id using the id attribute. <p id=”ResultsP”> This id must be unique in the web page, because it is used by the JavaScript to identify the specific HTML element in the following line: document.getElementById(‘ResultsP’).innerHTML = ‘Hello World!’; The code simply means: “Get me the document element with id ResultsP and set the HTML inside that element to Hello World!” It is important that the code accessing the paragraph is after the paragraph otherwise, the code would be attempting to access a paragraph before it existed in the page and would throw an error. Aanisha Mishra keerthiga ragu javascript-basics JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript Form validation using HTML and JavaScript Difference Between PUT and PATCH Request Installation of Node.js on Linux Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24444, "s": 24416, "text": "\n30 Apr, 2020" }, { "code": null, "e": 24771, "s": 24444, "text": "Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog.<script> tags can be put between the <head> and </head> tags or between <body> and </body> tags." }, { "code": null, "e": 24936, "s": 24771, "text": "type attribute was the most important attribute of <script> tag. However, it is no longer used. Browser understands that <script> tag has JavaScript code inside it." }, { "code": null, "e": 24968, "s": 24936, "text": "<script type=\"text/javascript\">" }, { "code": null, "e": 25141, "s": 24968, "text": "How to write, save and run codes:Method 1:1. Use any note editor like Notepad, Notepad++ to write the code.2. Save the page with .html extension and load it in web browser." }, { "code": null, "e": 25344, "s": 25141, "text": "Method 2:1. Create a .js file, and write your JS code in this file using your favorite editor.2. Add <script src=\"relative_path_to_file/file_name.js\"></script> in the end of <body> tag inside HTML file." }, { "code": null, "e": 25382, "s": 25344, "text": "Code for Painting the page light blue" }, { "code": "<!DOCTYPE html><html> <head> <title></title> </head> <body bgcolor=\"white\"> <p>Paragraph 1</p> <script type=\"text/javascript\"> document.bgColor =\"lightblue\"; </script> </body><html>", "e": 25579, "s": 25382, "text": null }, { "code": null, "e": 25587, "s": 25579, "text": "Output:" }, { "code": null, "e": 25700, "s": 25587, "text": "The colour of web-page is light blue , but the opening body tag is defined to set background colour to be white." }, { "code": null, "e": 25724, "s": 25700, "text": "<body bgcolor=\"white\"> " }, { "code": null, "e": 25853, "s": 25724, "text": "The background colour of page is light blue because JavaScript is used to set the document's background colour to be light blue." }, { "code": null, "e": 25883, "s": 25853, "text": "document.bgcolor=\"lightblue\";" }, { "code": null, "e": 26232, "s": 25883, "text": "Learning from the code:1. Page is known as document for the purpose of scripting in a web page.2. Properties of the document can be referenced by writing document followed by a dot, followed by the property name. The document has lots of properties.3. After <script> tag browser starts to interpret the text as JavaScript until the </script> comes." }, { "code": null, "e": 26347, "s": 26232, "text": "Code to write something to a web page using JavaScript:Lets write “Hello World!” to a blank page using JavaScript." }, { "code": null, "e": 26385, "s": 26347, "text": "DISPLAYING THE RESULT ON THE WEBPAGE." }, { "code": "<!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”> <head> <title></title> </head> <body> <p id=\"ResultsP\"></p> <script type=\"text/javascript\">//Script Block 1 document.getElementById('ResultsP').innerHTML ='Hello World!'; </script> </body><html>", "e": 26762, "s": 26385, "text": null }, { "code": null, "e": 26770, "s": 26762, "text": "Output:" }, { "code": null, "e": 26844, "s": 26770, "text": "Learning from the code:1. The following line has been added to this code." }, { "code": null, "e": 27013, "s": 26844, "text": " <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0\n Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>\n <html xmlns=”http://www.w3.org/1999/xhtml”>" }, { "code": null, "e": 27172, "s": 27013, "text": "This lets the web browser know that user is using XHTML. It doesn’t actually make any difference to the code; it would work just fine without the extra lines." }, { "code": null, "e": 27240, "s": 27172, "text": "2. Notice that <p> tag has been given an id using the id attribute." }, { "code": null, "e": 27258, "s": 27240, "text": "<p id=”ResultsP”>" }, { "code": null, "e": 27396, "s": 27258, "text": "This id must be unique in the web page, because it is used by the JavaScript to identify the specific HTML element in the following line:" }, { "code": null, "e": 27460, "s": 27396, "text": "document.getElementById(‘ResultsP’).innerHTML = ‘Hello World!’;" }, { "code": null, "e": 27583, "s": 27460, "text": "The code simply means: “Get me the document element with id ResultsP and set the HTML inside that element to Hello World!”" }, { "code": null, "e": 27778, "s": 27583, "text": "It is important that the code accessing the paragraph is after the paragraph otherwise, the code would be attempting to access a paragraph before it existed in the page and would throw an error." }, { "code": null, "e": 27793, "s": 27778, "text": "Aanisha Mishra" }, { "code": null, "e": 27808, "s": 27793, "text": "keerthiga ragu" }, { "code": null, "e": 27826, "s": 27808, "text": "javascript-basics" }, { "code": null, "e": 27837, "s": 27826, "text": "JavaScript" }, { "code": null, "e": 27854, "s": 27837, "text": "Web Technologies" }, { "code": null, "e": 27952, "s": 27854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27961, "s": 27952, "text": "Comments" }, { "code": null, "e": 27974, "s": 27961, "text": "Old Comments" }, { "code": null, "e": 28035, "s": 27974, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28107, "s": 28035, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28152, "s": 28107, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28194, "s": 28152, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 28235, "s": 28194, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28268, "s": 28235, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28310, "s": 28268, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28353, "s": 28310, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28415, "s": 28353, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Reinforcement Learning with TensorFlow Agents — Tutorial | by Mauricio Fadel Argerich | Towards Data Science
Some weeks ago, I wrote an article naming different frameworks you can use to implement Reinforcement Learning (RL) in your projects, showing the ups and downs of each of them and wondering if any of them would rule them all at some point. Since then, I’ve come to know TF Agents, a library for RL based on TensorFlow and with the full support of its community (note that TF Agents is not an official Google product but it is published as a repository from the official TensorFlow account on Github). I am currently using TF Agents on a project and it has been easy to start with it, thanks to its good documentation including tutorials. It is updated regularly and has lots of contributors, which makes me think it is possible we will see TF Agents as the standard framework for implementing RL in the near future. Because of this, I’ve decided to make this article to give you a quick introduction, so you can also benefit from this library. I have published all the code used here as a Google colab notebook, so you can easily run it online. You can find the Github with all the code and documentation for TF-Agents here. You won’t need to clone their repository, but it’s always useful to have the official Github for reference. I have implemented the following example following partially one of their tutorials (1_dqn_tutorial) but I have simplified it further and used it for playing Atari games in this article. Let’s get hands on. As already said, TF-Agents runs on TensorFlow, more specifically TensorFlow 2.2.0. In addition you will need to install the following packages if you don’t have them already: pip install tensorflow==2.2.0pip install tf-agents We will implement a DQN Agent (Mnih et al. 2015) and use it for CartPole, a classic control problem. If you would like to solve something more exciting like, say, an Atari game, you just need to change the environment name with the one you wish, choosing it from all the available OpenAI environments. We start by doing all of the necessary imports. As you can see below, we implement quite a few objects from TF-Agents. These are all things we can customize and switch for our implementation. from __future__ import absolute_import, division, print_functionimport base64import IPythonimport matplotlibimport matplotlib.pyplot as pltimport numpy as npimport tensorflow as tffrom tf_agents.agents.dqn import dqn_agentfrom tf_agents.drivers import dynamic_step_driverfrom tf_agents.environments import suite_gymfrom tf_agents.environments import tf_py_environmentfrom tf_agents.eval import metric_utilsfrom tf_agents.metrics import tf_metricsfrom tf_agents.networks import q_networkfrom tf_agents.replay_buffers import tf_uniform_replay_bufferfrom tf_agents.trajectories import trajectoryfrom tf_agents.utils import common Now, we head on to create our environment. In CartPole, we have a cart with a pole on top of it, the agent’s mission is to learn to keep up the pole, moving the cart left and right. Note that we will use an e environment from suite_gym already included in TF-Agents, which is a slightly customized (and improved for its use with TF-Agents) version of OpenAI Gym environments (if you’re interested, you can check the differences with OpenAI’s implementation here). We will also use a wrapper for our environment called TFPyEnvironment — which converts the numpy arrays used for state observations, actions and rewards into TensorFlow tensors. When dealing with TensorFlow models, (i.e., neural networks) we use tensors, so by using this wrapper we save some effort we would need to convert these data. env = suite_gym.load('CartPole-v1')env = tf_py_environment.TFPyEnvironment(env) There are different agents in TF-Agents we can use: DQN, REINFORCE, DDPG, TD3, PPO and SAC. We will use DQN as said above. One of the main parameters of the agent is its Q (neural) network, which will be use to calculate the Q-values for the actions in each step. A q_network has two compulsory parameters: input_tensor_spec and action_spec defining the observation shape and the action shape. We can get this from our environment so we will define our q_network as follows: q_net = q_network.QNetwork(env.observation_spec(), env.action_spec()) There are many more parameters we can customize for our q_network as you can see here, but for now, we will go with the default ones. The agent also requires an optimiser to find the values for the q_network parameter. Let’s keep it classic and use Adam. optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.001) Finally, we define and initialize our agent with the following parameters: The time_step_spec, which we get from our environment and defines how are our time steps defined. The action_spec, same as for the q_network. The Q network we created before. The optimizer we have also created before. The TD error loss function, similar to how the loss is used in NN. The train step counter, that is just a rank 0 tensor (a.k.a. scalar) which will count the number of steps we do on the environment. train_step_counter = tf.Variable(0)agent = dqn_agent.DqnAgent(env.time_step_spec(), env.action_spec(), q_network=q_net, optimizer=optimizer, td_errors_loss_fn= common.element_wise_squared_loss, train_step_counter=train_step_counter)agent.initialize() We will also need some helper methods. The first one will iterate over the environment for a number of episodes, applying the policy to choose what actions to follow and return the average cumulative reward in these episodes. This will come in handy to evaluate the policy learned by our agent. Below, we also try the method in our environment for 10 episodes. def compute_avg_return(environment, policy, num_episodes=10): total_return = 0.0 for _ in range(num_episodes): time_step = environment.reset() episode_return = 0.0 while not time_step.is_last(): action_step = policy.action(time_step) time_step = environment.step(action_step.action) episode_return += time_step.reward total_return += episode_return avg_return = total_return / num_episodes return avg_return.numpy()[0]# Evaluate the agent's policy once before training.avg_return = compute_avg_return(env, agent.policy, 5)returns = [avg_return] We will also implement a method to collect data when training our agent. One of the breakthroughs of DQN was experience replay, in which we store the experiences of the agent (state, action, reward) and use it to train the Q network in batches in each step. This improves the learning by making it faster and more stable. In order to do this, TF-Agents includes the object TFUniformReplayBuffer, which stores these experiences to re-use them later, so we firstly create this object that we will need later on. In this method, we take an environment, a policy and a buffer, take the current time_step formed by its state observation and reward at that time_step, the action the policy chooses and then the next time_step. Then, we store this in the replay buffer. Note the replay buffer stores an object called Trajectory, so we create this object with the elements named before, and then save it to the buffer using the method add_batch. replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=agent.collect_data_spec, batch_size=env.batch_size, max_length=100000)def collect_step(environment, policy, buffer): time_step = environment.current_time_step() action_step = policy.action(time_step) next_time_step = environment.step(action_step.action) traj = trajectory.from_transition(time_step, action_step, next_time_step)# Add trajectory to the replay buffer buffer.add_batch(traj) We can finally train our agent. We define the number of steps we will make in every iteration, after this number of steps, we will train our agent in every iteration, modifying it’s policy. For now let’s just use 1 step per iteration. We also define the batch size with which our Q network will be trained and an iterator so we iterate over the experienced of the agent. Then, we will just gather some experience for our buffer and start with the common RL loop. Get experience by acting on the environment, train policy and repeat. We additionally print the loss and evaluate the performance of the agent every 200 and 1000 steps respectively. collect_steps_per_iteration = 1batch_size = 64dataset = replay_buffer.as_dataset(num_parallel_calls=3, sample_batch_size=batch_size, num_steps=2).prefetch(3)iterator = iter(dataset)num_iterations = 20000env.reset()for _ in range(batch_size): collect_step(env, agent.policy, replay_buffer)for _ in range(num_iterations): # Collect a few steps using collect_policy and save to the replay buffer. for _ in range(collect_steps_per_iteration): collect_step(env, agent.collect_policy, replay_buffer) # Sample a batch of data from the buffer and update the agent's network. experience, unused_info = next(iterator) train_loss = agent.train(experience).loss step = agent.train_step_counter.numpy() # Print loss every 200 steps. if step % 200 == 0: print('step = {0}: loss = {1}'.format(step, train_loss)) # Evaluate agent's performance every 1000 steps. if step % 1000 == 0: avg_return = compute_avg_return(env, agent.policy, 5) print('step = {0}: Average Return = {1}'.format(step, avg_return)) returns.append(avg_return) We can now plot how the cumulative average reward varies as we train the agent. For this, we will use matplotlib to make a very simple plot. iterations = range(0, num_iterations + 1, 1000)plt.plot(iterations, returns)plt.ylabel('Average Return')plt.xlabel('Iterations') I have shared all the code in this article as a Google Colab notebook. You can directly run all the code as it is, if you would like to change it, you have to save it on your own Google drive account and then you can do whatever you like. You can also download it to run it locally on your computer, if you wish to. You can follow the tutorials included in the repository of TF-Agents on Github If you would like to check other nice frameworks for RL, you can see my previous post here: towardsdatascience.com You can also check other environments in which to try TF-Agents (or any RL algorithm of your choice) in this other article I wrote some time ago. As usual, thank you for reading! Let me know in responses what you think about TF-Agents, and also if you have any question or you found any 🐛 in the code.
[ { "code": null, "e": 672, "s": 171, "text": "Some weeks ago, I wrote an article naming different frameworks you can use to implement Reinforcement Learning (RL) in your projects, showing the ups and downs of each of them and wondering if any of them would rule them all at some point. Since then, I’ve come to know TF Agents, a library for RL based on TensorFlow and with the full support of its community (note that TF Agents is not an official Google product but it is published as a repository from the official TensorFlow account on Github)." }, { "code": null, "e": 1216, "s": 672, "text": "I am currently using TF Agents on a project and it has been easy to start with it, thanks to its good documentation including tutorials. It is updated regularly and has lots of contributors, which makes me think it is possible we will see TF Agents as the standard framework for implementing RL in the near future. Because of this, I’ve decided to make this article to give you a quick introduction, so you can also benefit from this library. I have published all the code used here as a Google colab notebook, so you can easily run it online." }, { "code": null, "e": 1611, "s": 1216, "text": "You can find the Github with all the code and documentation for TF-Agents here. You won’t need to clone their repository, but it’s always useful to have the official Github for reference. I have implemented the following example following partially one of their tutorials (1_dqn_tutorial) but I have simplified it further and used it for playing Atari games in this article. Let’s get hands on." }, { "code": null, "e": 1786, "s": 1611, "text": "As already said, TF-Agents runs on TensorFlow, more specifically TensorFlow 2.2.0. In addition you will need to install the following packages if you don’t have them already:" }, { "code": null, "e": 1837, "s": 1786, "text": "pip install tensorflow==2.2.0pip install tf-agents" }, { "code": null, "e": 2139, "s": 1837, "text": "We will implement a DQN Agent (Mnih et al. 2015) and use it for CartPole, a classic control problem. If you would like to solve something more exciting like, say, an Atari game, you just need to change the environment name with the one you wish, choosing it from all the available OpenAI environments." }, { "code": null, "e": 2331, "s": 2139, "text": "We start by doing all of the necessary imports. As you can see below, we implement quite a few objects from TF-Agents. These are all things we can customize and switch for our implementation." }, { "code": null, "e": 2958, "s": 2331, "text": "from __future__ import absolute_import, division, print_functionimport base64import IPythonimport matplotlibimport matplotlib.pyplot as pltimport numpy as npimport tensorflow as tffrom tf_agents.agents.dqn import dqn_agentfrom tf_agents.drivers import dynamic_step_driverfrom tf_agents.environments import suite_gymfrom tf_agents.environments import tf_py_environmentfrom tf_agents.eval import metric_utilsfrom tf_agents.metrics import tf_metricsfrom tf_agents.networks import q_networkfrom tf_agents.replay_buffers import tf_uniform_replay_bufferfrom tf_agents.trajectories import trajectoryfrom tf_agents.utils import common" }, { "code": null, "e": 3759, "s": 2958, "text": "Now, we head on to create our environment. In CartPole, we have a cart with a pole on top of it, the agent’s mission is to learn to keep up the pole, moving the cart left and right. Note that we will use an e environment from suite_gym already included in TF-Agents, which is a slightly customized (and improved for its use with TF-Agents) version of OpenAI Gym environments (if you’re interested, you can check the differences with OpenAI’s implementation here). We will also use a wrapper for our environment called TFPyEnvironment — which converts the numpy arrays used for state observations, actions and rewards into TensorFlow tensors. When dealing with TensorFlow models, (i.e., neural networks) we use tensors, so by using this wrapper we save some effort we would need to convert these data." }, { "code": null, "e": 3839, "s": 3759, "text": "env = suite_gym.load('CartPole-v1')env = tf_py_environment.TFPyEnvironment(env)" }, { "code": null, "e": 4314, "s": 3839, "text": "There are different agents in TF-Agents we can use: DQN, REINFORCE, DDPG, TD3, PPO and SAC. We will use DQN as said above. One of the main parameters of the agent is its Q (neural) network, which will be use to calculate the Q-values for the actions in each step. A q_network has two compulsory parameters: input_tensor_spec and action_spec defining the observation shape and the action shape. We can get this from our environment so we will define our q_network as follows:" }, { "code": null, "e": 4411, "s": 4314, "text": "q_net = q_network.QNetwork(env.observation_spec(), env.action_spec())" }, { "code": null, "e": 4666, "s": 4411, "text": "There are many more parameters we can customize for our q_network as you can see here, but for now, we will go with the default ones. The agent also requires an optimiser to find the values for the q_network parameter. Let’s keep it classic and use Adam." }, { "code": null, "e": 4732, "s": 4666, "text": "optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.001)" }, { "code": null, "e": 4807, "s": 4732, "text": "Finally, we define and initialize our agent with the following parameters:" }, { "code": null, "e": 4905, "s": 4807, "text": "The time_step_spec, which we get from our environment and defines how are our time steps defined." }, { "code": null, "e": 4949, "s": 4905, "text": "The action_spec, same as for the q_network." }, { "code": null, "e": 4982, "s": 4949, "text": "The Q network we created before." }, { "code": null, "e": 5025, "s": 4982, "text": "The optimizer we have also created before." }, { "code": null, "e": 5092, "s": 5025, "text": "The TD error loss function, similar to how the loss is used in NN." }, { "code": null, "e": 5224, "s": 5092, "text": "The train step counter, that is just a rank 0 tensor (a.k.a. scalar) which will count the number of steps we do on the environment." }, { "code": null, "e": 5639, "s": 5224, "text": "train_step_counter = tf.Variable(0)agent = dqn_agent.DqnAgent(env.time_step_spec(), env.action_spec(), q_network=q_net, optimizer=optimizer, td_errors_loss_fn= common.element_wise_squared_loss, train_step_counter=train_step_counter)agent.initialize()" }, { "code": null, "e": 6000, "s": 5639, "text": "We will also need some helper methods. The first one will iterate over the environment for a number of episodes, applying the policy to choose what actions to follow and return the average cumulative reward in these episodes. This will come in handy to evaluate the policy learned by our agent. Below, we also try the method in our environment for 10 episodes." }, { "code": null, "e": 6618, "s": 6000, "text": "def compute_avg_return(environment, policy, num_episodes=10): total_return = 0.0 for _ in range(num_episodes): time_step = environment.reset() episode_return = 0.0 while not time_step.is_last(): action_step = policy.action(time_step) time_step = environment.step(action_step.action) episode_return += time_step.reward total_return += episode_return avg_return = total_return / num_episodes return avg_return.numpy()[0]# Evaluate the agent's policy once before training.avg_return = compute_avg_return(env, agent.policy, 5)returns = [avg_return]" }, { "code": null, "e": 7128, "s": 6618, "text": "We will also implement a method to collect data when training our agent. One of the breakthroughs of DQN was experience replay, in which we store the experiences of the agent (state, action, reward) and use it to train the Q network in batches in each step. This improves the learning by making it faster and more stable. In order to do this, TF-Agents includes the object TFUniformReplayBuffer, which stores these experiences to re-use them later, so we firstly create this object that we will need later on." }, { "code": null, "e": 7556, "s": 7128, "text": "In this method, we take an environment, a policy and a buffer, take the current time_step formed by its state observation and reward at that time_step, the action the policy chooses and then the next time_step. Then, we store this in the replay buffer. Note the replay buffer stores an object called Trajectory, so we create this object with the elements named before, and then save it to the buffer using the method add_batch." }, { "code": null, "e": 8328, "s": 7556, "text": "replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=agent.collect_data_spec, batch_size=env.batch_size, max_length=100000)def collect_step(environment, policy, buffer): time_step = environment.current_time_step() action_step = policy.action(time_step) next_time_step = environment.step(action_step.action) traj = trajectory.from_transition(time_step, action_step, next_time_step)# Add trajectory to the replay buffer buffer.add_batch(traj)" }, { "code": null, "e": 8699, "s": 8328, "text": "We can finally train our agent. We define the number of steps we will make in every iteration, after this number of steps, we will train our agent in every iteration, modifying it’s policy. For now let’s just use 1 step per iteration. We also define the batch size with which our Q network will be trained and an iterator so we iterate over the experienced of the agent." }, { "code": null, "e": 8973, "s": 8699, "text": "Then, we will just gather some experience for our buffer and start with the common RL loop. Get experience by acting on the environment, train policy and repeat. We additionally print the loss and evaluate the performance of the agent every 200 and 1000 steps respectively." }, { "code": null, "e": 10126, "s": 8973, "text": "collect_steps_per_iteration = 1batch_size = 64dataset = replay_buffer.as_dataset(num_parallel_calls=3, sample_batch_size=batch_size, num_steps=2).prefetch(3)iterator = iter(dataset)num_iterations = 20000env.reset()for _ in range(batch_size): collect_step(env, agent.policy, replay_buffer)for _ in range(num_iterations): # Collect a few steps using collect_policy and save to the replay buffer. for _ in range(collect_steps_per_iteration): collect_step(env, agent.collect_policy, replay_buffer) # Sample a batch of data from the buffer and update the agent's network. experience, unused_info = next(iterator) train_loss = agent.train(experience).loss step = agent.train_step_counter.numpy() # Print loss every 200 steps. if step % 200 == 0: print('step = {0}: loss = {1}'.format(step, train_loss)) # Evaluate agent's performance every 1000 steps. if step % 1000 == 0: avg_return = compute_avg_return(env, agent.policy, 5) print('step = {0}: Average Return = {1}'.format(step, avg_return)) returns.append(avg_return)" }, { "code": null, "e": 10267, "s": 10126, "text": "We can now plot how the cumulative average reward varies as we train the agent. For this, we will use matplotlib to make a very simple plot." }, { "code": null, "e": 10396, "s": 10267, "text": "iterations = range(0, num_iterations + 1, 1000)plt.plot(iterations, returns)plt.ylabel('Average Return')plt.xlabel('Iterations')" }, { "code": null, "e": 10712, "s": 10396, "text": "I have shared all the code in this article as a Google Colab notebook. You can directly run all the code as it is, if you would like to change it, you have to save it on your own Google drive account and then you can do whatever you like. You can also download it to run it locally on your computer, if you wish to." }, { "code": null, "e": 10791, "s": 10712, "text": "You can follow the tutorials included in the repository of TF-Agents on Github" }, { "code": null, "e": 10883, "s": 10791, "text": "If you would like to check other nice frameworks for RL, you can see my previous post here:" }, { "code": null, "e": 10906, "s": 10883, "text": "towardsdatascience.com" }, { "code": null, "e": 11052, "s": 10906, "text": "You can also check other environments in which to try TF-Agents (or any RL algorithm of your choice) in this other article I wrote some time ago." } ]
Build with PyCaret : Deploy on Microsoft Azure Platform | by MA Raza, Ph.D. | Towards Data Science
In this story, I have developed a working tutorial on deploying a model trained with pycaret library on Microsoft's Azure Cloud Platform. In my previous article Build with PyCaret: Deploy on Google Cloud Platform, we had learned how to deploy the model on Google cloud. We will use the same example in this tutorial and deploy the model on Microsoft Azure platform. We learn to deploy model trained with pycaret to Microsoft Azure Platform. pycaret has support to deploy a trained model on AWS but not with GCP or Azure at the moment. I followed the similar code-practices as used in library to deploy and load model with AWS to deploy the model on Microsoft's Azure Platform. PyCaret is an open source, low-code machine learning library in Python that allows you to go from preparing your data to deploying your model within seconds in your choice of notebook environment.source PyCaret is an autoML framework for citizen data scientists term used in its official documentation and homepage. This is relatively new library released few months ago for public use and still under active development. After going through some source code, I realized the current public release lacks support for deployment of trained/finalized models to Google and Azure Cloud Platforms. Although, It has support for deploying on Amazon web services. Microsoft Azure is another very popular framework for cloud services and targeting different market than Google and AWS. Having already huge customer base, Azure has captured reasonable market share. In my opinion, for citizen data scientists, probably Microsoft Azure is best starting point. Let us learn how can we deploy a model on Microsoft Azure. For this tutorial, we will use the Regression Tutorial (REG101) — Level Beginner for model training. !pip install pycaret We need to mount the google drive to read the data in colab environment. Below is the simplest way to mount it. You will be asked to enter the token generated by your access procedure. Here is the link to the article about mounting gdrive We will save models locally on Google drive for this tutorial. from google.colab import drivedrive.mount('/content/drive')Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True). Let us create a directory to save models locally. # Create directory on google drive to save models locally. You can use temp paths.import osmodel_dir = '/content/drive/My Drive/azure_deploy_model/'os.makedirs(model_dir, exist_ok=True) You can download the data from the original source found here and load it using pandas (Learn How) or you can use PyCaret’s data respository to load the data using the get_data() function (This will require internet connection). from pycaret.datasets import get_datadataset = get_data('diamond') #check the shape of datadataset.shape(6000, 8)data = dataset.sample(frac=0.9, random_state=786).reset_index(drop=True)data_unseen = dataset.drop(data.index).reset_index(drop=True)print('Data for Modeling: ' + str(data.shape))print('Unseen Data For Predictions: ' + str(data_unseen.shape))Data for Modeling: (5400, 8)Unseen Data For Predictions: (600, 8) Let us setup modelling pipeline using pycaret’s setup module. from pycaret.regression import *exp_reg101 = setup(data = data, target = 'Price', session_id=123)Setup Successfully Completed! For this tutorial, we model the data using Light GBM from many options implemented in pycaret. You can choose any model of your choice but that is not focus of this tutorial. lightgbm = create_model('lightgbm') Let us train the model also called a tuning the model in pycaret’s terminologies. tuned_lightgbm = tune_model('lightgbm') Below are the plots to see the residual errors for the model plot_model(tuned_lightgbm) Prediction Error Plot Let use plot the prediction errors vs true values of target. plot_model(tuned_lightgbm, plot = 'error') feature importance is very informative plot to see the contribution of each feature in the model. plot_model(tuned_lightgbm, plot='feature') Another way to analyze the performance of models is to use the evaluate_model() function which displays a user interface for all of the available plots for a given model. It internally uses the plot_model() function. evaluate_model(tuned_lightgbm)interactive(children=(ToggleButtons(description='Plot Type:', icons=('',), options=(('Hyperparameters', 'param... predict_model(tuned_lightgbm); final_lightgbm = finalize_model(tuned_lightgbm)#Final Light Gradient Boosting Machine parameters for deploymentprint(final_lightgbm)LGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0, importance_type='split', learning_rate=0.4, max_depth=10, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.9, n_estimators=90, n_jobs=-1, num_leaves=10, objective=None, random_state=123, reg_alpha=0.9, reg_lambda=0.2, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=0)predict_model(final_lightgbm) unseen_predictions = predict_model(final_lightgbm, data=data_unseen)unseen_predictions.head() The Label column is added onto the data_unseen set. Label is the predicted value using the final_lightgbm model. If you want predictions to be rounded, you can use round parameter inside predict_model(). Let us first save the model locally model_dirmodel_name = 'Final_lightgbm_model''/content/drive/My Drive/azure_deploy_model/'# Saving model to google drivesave_model(final_lightgbm, model_dir + model_name)Transformation Pipeline and Model Successfully Saved To load a saved model at a future date in the same or an alternative environment, we would use PyCaret’s load_model() function and then easily apply the saved model on new unseen data for prediction. saved_final_lightgbm = load_model(model_dir + model_name)Transformation Pipeline and Model Successfully Loaded Once the model is loaded in the environment, you can simply use it to predict on any new data using the same predict_model() function. Below we have applied the loaded model to predict the same data_unseen that we used in section 13 above. new_prediction = predict_model(saved_final_lightgbm, data=data_unseen)new_prediction.head() Notice that the results of unseen_predictions and new_prediction are identical. Microsoft Azure is one the biggest cloud providers and machine learning on cloud as a service. In my previous article, I have covered of deploying model to Google Cloud Platform. Library has already support for Amazon web services deployment. Once, we have the trained model the next task is to deploy it to serve the clients. There are various deployment options available however in this section I focus on deploying it on Microsoft Azure Platform. I try to use a similar approach as followed in pycaret library for deploying on AWS. The pre-requisite to deploy the ml model models on Azure cloud are Familiarity with Microsoft Azure Platform Microsoft Azure account Basic understanding of storage containers and its command line tool A Final Trained Model with pycaret Read the Guide on Quickstart: Manage blobs with Python v12 SDK import os, uuidfrom azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient AZURE_STORAGE_CONNECTION_STRING is the authentication string to connect to the Azure storage blob. You can set this string in your environment and can use any one time. Another option is that you enter your string whenever a connection is needed. Microsoft Azure storage container is equivalent to Google Cloud Storage Bucket # add the connection string in environment# Linux! export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"# After you add the environment variable, restart any running programs that will need to read the environment variable. For example, restart your development environment or editor before continuing.# Retrieve the connection string for use with the application. The storage# connection string is stored in an environment variable on the machine# running the application called AZURE_STORAGE_CONNECTION_STRING. If the environment variable is# created after the application is launched in a console or with Visual Studio,# the shell or application needs to be closed and reloaded to take the# environment variable into account.connect_str_env = os.getenv('AZURE_STORAGE_CONNECTION_STRING') You can enter your connection string in google colab using below form ## Enter connection string when running in google colabconnect_str = 'Enter Connection String Here' #@param {type:"string"}print(connect_str) To create the connection to blob container, use below command to create service client object. # Create the BlobServiceClient object which will be used to create a container clientblob_service_client = BlobServiceClient.from_connection_string(connect_str) I have written/collected below utilities to upload/download data from blobs. def create_container(container_name): # Create the container container_client = blob_service_client.create_container(container_name) return container_clientdef upload_blob(container_name, source_file_name, destination_blob_name): # Create a blob client using the local file name as the name for the blob blob_client = blob_service_client.get_blob_client(container=container_name, blob=destination_blob_name) print("\nUploading to Azure Storage as blob:\n\t" + source_file_name) # Upload the created file with open(source_file_name, "rb") as data: blob_client.upload_blob(data)def download_blob(container_name, source_blob_name, destination_file_name): # Download the blob to a local file print("\nDownloading blob to \n\t" + destination_file_name) # Create a blob client using the local file name as the name for the blob blob_client = blob_service_client.get_blob_client(container=container_name, blob=source_blob_name) if destination_file_name is not None: with open(destination_file_name, "wb") as download_file: download_file.write(blob_client.download_blob().readall()) print( "Blob {} downloaded to {}.".format( source_blob_name, destination_file_name ) ) Using above utilities, use below code to upload the model to Azure-container. Before uploading, we create the container if not done before. Containers can be created using GUI too. # Create a unique name for the containercontainer_name = "pycaret" + str(uuid.uuid4())container_client = create_container(container_name)# Save Model Local/google drive and upload to Azuremodel_name_azure = 'lightgbm-reg101-azure'save_model(final_lightgbm, model_name= model_dir + model_name_azure, verbose=False)model_src = model_dir + model_name_azure +'.pkl'model_dst = str(model_name)+'.pkl'upload_blob(CLOUD_PROJECT, bucket_name, model_src, model_dst)File /content/drive/My Drive/azure_deploy_model/lightgbm-reg101-azure.pkl uploaded to Final_lightgbm_model.pkl. Once your model is upload to Azure, you can download anytime to perform the predictions. I follow a simple flow, where model is downloaded locally or in google drive first and then using load_model function to load the model. print("\nListing blobs...")# List the blobs in the containerblob_list = container_client.list_blobs()for blob in blob_list: print("\t" + blob.name)outfile_name = model_dir + 'lightgbm-reg101-azure-downloaded'model_azure_src = str(model_name)+'.pkl'download_blob(container_name, model_azure_src, outfile_name + '.pkl') Use the recently downloaded model from Azure to perform the prediction. # Loading the model for predictionsazure_final_lightgbm = load_model(outfile_name)Transformation Pipeline and Model Successfully Loaded# Predictions from deployed modelnew_prediction_azure = predict_model(azure_final_lightgbm, data=data_unseen)new_prediction_azure.head() Follow the below Google colaboratory notebook to reproduce and practice this guide. In this tutorial, we learned how to deploy a model to Microsoft Azure when trained with pycaret library. The main objective was to use built-in utils of pycaret to deploy and load a model from Azure. Below are some highlights Mount google drive for saving models Train Regression model with pycaret Saving and loading trained/finalized model Microsoft Azure Deploying trained/finalized model to Microsoft’s Azure container Using Azure deployed model to perform predictions
[ { "code": null, "e": 538, "s": 172, "text": "In this story, I have developed a working tutorial on deploying a model trained with pycaret library on Microsoft's Azure Cloud Platform. In my previous article Build with PyCaret: Deploy on Google Cloud Platform, we had learned how to deploy the model on Google cloud. We will use the same example in this tutorial and deploy the model on Microsoft Azure platform." }, { "code": null, "e": 849, "s": 538, "text": "We learn to deploy model trained with pycaret to Microsoft Azure Platform. pycaret has support to deploy a trained model on AWS but not with GCP or Azure at the moment. I followed the similar code-practices as used in library to deploy and load model with AWS to deploy the model on Microsoft's Azure Platform." }, { "code": null, "e": 1052, "s": 849, "text": "PyCaret is an open source, low-code machine learning library in Python that allows you to go from preparing your data to deploying your model within seconds in your choice of notebook environment.source" }, { "code": null, "e": 1504, "s": 1052, "text": "PyCaret is an autoML framework for citizen data scientists term used in its official documentation and homepage. This is relatively new library released few months ago for public use and still under active development. After going through some source code, I realized the current public release lacks support for deployment of trained/finalized models to Google and Azure Cloud Platforms. Although, It has support for deploying on Amazon web services." }, { "code": null, "e": 1856, "s": 1504, "text": "Microsoft Azure is another very popular framework for cloud services and targeting different market than Google and AWS. Having already huge customer base, Azure has captured reasonable market share. In my opinion, for citizen data scientists, probably Microsoft Azure is best starting point. Let us learn how can we deploy a model on Microsoft Azure." }, { "code": null, "e": 1957, "s": 1856, "text": "For this tutorial, we will use the Regression Tutorial (REG101) — Level Beginner for model training." }, { "code": null, "e": 1978, "s": 1957, "text": "!pip install pycaret" }, { "code": null, "e": 2217, "s": 1978, "text": "We need to mount the google drive to read the data in colab environment. Below is the simplest way to mount it. You will be asked to enter the token generated by your access procedure. Here is the link to the article about mounting gdrive" }, { "code": null, "e": 2280, "s": 2217, "text": "We will save models locally on Google drive for this tutorial." }, { "code": null, "e": 2468, "s": 2280, "text": "from google.colab import drivedrive.mount('/content/drive')Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True)." }, { "code": null, "e": 2518, "s": 2468, "text": "Let us create a directory to save models locally." }, { "code": null, "e": 2704, "s": 2518, "text": "# Create directory on google drive to save models locally. You can use temp paths.import osmodel_dir = '/content/drive/My Drive/azure_deploy_model/'os.makedirs(model_dir, exist_ok=True)" }, { "code": null, "e": 2933, "s": 2704, "text": "You can download the data from the original source found here and load it using pandas (Learn How) or you can use PyCaret’s data respository to load the data using the get_data() function (This will require internet connection)." }, { "code": null, "e": 3000, "s": 2933, "text": "from pycaret.datasets import get_datadataset = get_data('diamond')" }, { "code": null, "e": 3354, "s": 3000, "text": "#check the shape of datadataset.shape(6000, 8)data = dataset.sample(frac=0.9, random_state=786).reset_index(drop=True)data_unseen = dataset.drop(data.index).reset_index(drop=True)print('Data for Modeling: ' + str(data.shape))print('Unseen Data For Predictions: ' + str(data_unseen.shape))Data for Modeling: (5400, 8)Unseen Data For Predictions: (600, 8)" }, { "code": null, "e": 3416, "s": 3354, "text": "Let us setup modelling pipeline using pycaret’s setup module." }, { "code": null, "e": 3543, "s": 3416, "text": "from pycaret.regression import *exp_reg101 = setup(data = data, target = 'Price', session_id=123)Setup Successfully Completed!" }, { "code": null, "e": 3718, "s": 3543, "text": "For this tutorial, we model the data using Light GBM from many options implemented in pycaret. You can choose any model of your choice but that is not focus of this tutorial." }, { "code": null, "e": 3754, "s": 3718, "text": "lightgbm = create_model('lightgbm')" }, { "code": null, "e": 3836, "s": 3754, "text": "Let us train the model also called a tuning the model in pycaret’s terminologies." }, { "code": null, "e": 3876, "s": 3836, "text": "tuned_lightgbm = tune_model('lightgbm')" }, { "code": null, "e": 3937, "s": 3876, "text": "Below are the plots to see the residual errors for the model" }, { "code": null, "e": 3964, "s": 3937, "text": "plot_model(tuned_lightgbm)" }, { "code": null, "e": 4047, "s": 3964, "text": "Prediction Error Plot Let use plot the prediction errors vs true values of target." }, { "code": null, "e": 4090, "s": 4047, "text": "plot_model(tuned_lightgbm, plot = 'error')" }, { "code": null, "e": 4188, "s": 4090, "text": "feature importance is very informative plot to see the contribution of each feature in the model." }, { "code": null, "e": 4231, "s": 4188, "text": "plot_model(tuned_lightgbm, plot='feature')" }, { "code": null, "e": 4448, "s": 4231, "text": "Another way to analyze the performance of models is to use the evaluate_model() function which displays a user interface for all of the available plots for a given model. It internally uses the plot_model() function." }, { "code": null, "e": 4592, "s": 4448, "text": "evaluate_model(tuned_lightgbm)interactive(children=(ToggleButtons(description='Plot Type:', icons=('',), options=(('Hyperparameters', 'param..." }, { "code": null, "e": 4623, "s": 4592, "text": "predict_model(tuned_lightgbm);" }, { "code": null, "e": 5230, "s": 4623, "text": "final_lightgbm = finalize_model(tuned_lightgbm)#Final Light Gradient Boosting Machine parameters for deploymentprint(final_lightgbm)LGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0, importance_type='split', learning_rate=0.4, max_depth=10, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.9, n_estimators=90, n_jobs=-1, num_leaves=10, objective=None, random_state=123, reg_alpha=0.9, reg_lambda=0.2, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=0)predict_model(final_lightgbm)" }, { "code": null, "e": 5324, "s": 5230, "text": "unseen_predictions = predict_model(final_lightgbm, data=data_unseen)unseen_predictions.head()" }, { "code": null, "e": 5528, "s": 5324, "text": "The Label column is added onto the data_unseen set. Label is the predicted value using the final_lightgbm model. If you want predictions to be rounded, you can use round parameter inside predict_model()." }, { "code": null, "e": 5564, "s": 5528, "text": "Let us first save the model locally" }, { "code": null, "e": 5786, "s": 5564, "text": "model_dirmodel_name = 'Final_lightgbm_model''/content/drive/My Drive/azure_deploy_model/'# Saving model to google drivesave_model(final_lightgbm, model_dir + model_name)Transformation Pipeline and Model Successfully Saved" }, { "code": null, "e": 5986, "s": 5786, "text": "To load a saved model at a future date in the same or an alternative environment, we would use PyCaret’s load_model() function and then easily apply the saved model on new unseen data for prediction." }, { "code": null, "e": 6097, "s": 5986, "text": "saved_final_lightgbm = load_model(model_dir + model_name)Transformation Pipeline and Model Successfully Loaded" }, { "code": null, "e": 6337, "s": 6097, "text": "Once the model is loaded in the environment, you can simply use it to predict on any new data using the same predict_model() function. Below we have applied the loaded model to predict the same data_unseen that we used in section 13 above." }, { "code": null, "e": 6429, "s": 6337, "text": "new_prediction = predict_model(saved_final_lightgbm, data=data_unseen)new_prediction.head()" }, { "code": null, "e": 6509, "s": 6429, "text": "Notice that the results of unseen_predictions and new_prediction are identical." }, { "code": null, "e": 6752, "s": 6509, "text": "Microsoft Azure is one the biggest cloud providers and machine learning on cloud as a service. In my previous article, I have covered of deploying model to Google Cloud Platform. Library has already support for Amazon web services deployment." }, { "code": null, "e": 7045, "s": 6752, "text": "Once, we have the trained model the next task is to deploy it to serve the clients. There are various deployment options available however in this section I focus on deploying it on Microsoft Azure Platform. I try to use a similar approach as followed in pycaret library for deploying on AWS." }, { "code": null, "e": 7112, "s": 7045, "text": "The pre-requisite to deploy the ml model models on Azure cloud are" }, { "code": null, "e": 7154, "s": 7112, "text": "Familiarity with Microsoft Azure Platform" }, { "code": null, "e": 7178, "s": 7154, "text": "Microsoft Azure account" }, { "code": null, "e": 7246, "s": 7178, "text": "Basic understanding of storage containers and its command line tool" }, { "code": null, "e": 7281, "s": 7246, "text": "A Final Trained Model with pycaret" }, { "code": null, "e": 7344, "s": 7281, "text": "Read the Guide on Quickstart: Manage blobs with Python v12 SDK" }, { "code": null, "e": 7437, "s": 7344, "text": "import os, uuidfrom azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient" }, { "code": null, "e": 7684, "s": 7437, "text": "AZURE_STORAGE_CONNECTION_STRING is the authentication string to connect to the Azure storage blob. You can set this string in your environment and can use any one time. Another option is that you enter your string whenever a connection is needed." }, { "code": null, "e": 7763, "s": 7684, "text": "Microsoft Azure storage container is equivalent to Google Cloud Storage Bucket" }, { "code": null, "e": 8564, "s": 7763, "text": "# add the connection string in environment# Linux! export AZURE_STORAGE_CONNECTION_STRING=\"<yourconnectionstring>\"# After you add the environment variable, restart any running programs that will need to read the environment variable. For example, restart your development environment or editor before continuing.# Retrieve the connection string for use with the application. The storage# connection string is stored in an environment variable on the machine# running the application called AZURE_STORAGE_CONNECTION_STRING. If the environment variable is# created after the application is launched in a console or with Visual Studio,# the shell or application needs to be closed and reloaded to take the# environment variable into account.connect_str_env = os.getenv('AZURE_STORAGE_CONNECTION_STRING')" }, { "code": null, "e": 8634, "s": 8564, "text": "You can enter your connection string in google colab using below form" }, { "code": null, "e": 8776, "s": 8634, "text": "## Enter connection string when running in google colabconnect_str = 'Enter Connection String Here' #@param {type:\"string\"}print(connect_str)" }, { "code": null, "e": 8871, "s": 8776, "text": "To create the connection to blob container, use below command to create service client object." }, { "code": null, "e": 9032, "s": 8871, "text": "# Create the BlobServiceClient object which will be used to create a container clientblob_service_client = BlobServiceClient.from_connection_string(connect_str)" }, { "code": null, "e": 9109, "s": 9032, "text": "I have written/collected below utilities to upload/download data from blobs." }, { "code": null, "e": 10357, "s": 9109, "text": "def create_container(container_name): # Create the container container_client = blob_service_client.create_container(container_name) return container_clientdef upload_blob(container_name, source_file_name, destination_blob_name): # Create a blob client using the local file name as the name for the blob blob_client = blob_service_client.get_blob_client(container=container_name, blob=destination_blob_name) print(\"\\nUploading to Azure Storage as blob:\\n\\t\" + source_file_name) # Upload the created file with open(source_file_name, \"rb\") as data: blob_client.upload_blob(data)def download_blob(container_name, source_blob_name, destination_file_name): # Download the blob to a local file print(\"\\nDownloading blob to \\n\\t\" + destination_file_name) # Create a blob client using the local file name as the name for the blob blob_client = blob_service_client.get_blob_client(container=container_name, blob=source_blob_name) if destination_file_name is not None: with open(destination_file_name, \"wb\") as download_file: download_file.write(blob_client.download_blob().readall()) print( \"Blob {} downloaded to {}.\".format( source_blob_name, destination_file_name ) )" }, { "code": null, "e": 10497, "s": 10357, "text": "Using above utilities, use below code to upload the model to Azure-container. Before uploading, we create the container if not done before." }, { "code": null, "e": 10538, "s": 10497, "text": "Containers can be created using GUI too." }, { "code": null, "e": 11106, "s": 10538, "text": "# Create a unique name for the containercontainer_name = \"pycaret\" + str(uuid.uuid4())container_client = create_container(container_name)# Save Model Local/google drive and upload to Azuremodel_name_azure = 'lightgbm-reg101-azure'save_model(final_lightgbm, model_name= model_dir + model_name_azure, verbose=False)model_src = model_dir + model_name_azure +'.pkl'model_dst = str(model_name)+'.pkl'upload_blob(CLOUD_PROJECT, bucket_name, model_src, model_dst)File /content/drive/My Drive/azure_deploy_model/lightgbm-reg101-azure.pkl uploaded to Final_lightgbm_model.pkl." }, { "code": null, "e": 11332, "s": 11106, "text": "Once your model is upload to Azure, you can download anytime to perform the predictions. I follow a simple flow, where model is downloaded locally or in google drive first and then using load_model function to load the model." }, { "code": null, "e": 11653, "s": 11332, "text": "print(\"\\nListing blobs...\")# List the blobs in the containerblob_list = container_client.list_blobs()for blob in blob_list: print(\"\\t\" + blob.name)outfile_name = model_dir + 'lightgbm-reg101-azure-downloaded'model_azure_src = str(model_name)+'.pkl'download_blob(container_name, model_azure_src, outfile_name + '.pkl')" }, { "code": null, "e": 11725, "s": 11653, "text": "Use the recently downloaded model from Azure to perform the prediction." }, { "code": null, "e": 11997, "s": 11725, "text": "# Loading the model for predictionsazure_final_lightgbm = load_model(outfile_name)Transformation Pipeline and Model Successfully Loaded# Predictions from deployed modelnew_prediction_azure = predict_model(azure_final_lightgbm, data=data_unseen)new_prediction_azure.head()" }, { "code": null, "e": 12081, "s": 11997, "text": "Follow the below Google colaboratory notebook to reproduce and practice this guide." }, { "code": null, "e": 12186, "s": 12081, "text": "In this tutorial, we learned how to deploy a model to Microsoft Azure when trained with pycaret library." }, { "code": null, "e": 12307, "s": 12186, "text": "The main objective was to use built-in utils of pycaret to deploy and load a model from Azure. Below are some highlights" }, { "code": null, "e": 12344, "s": 12307, "text": "Mount google drive for saving models" }, { "code": null, "e": 12380, "s": 12344, "text": "Train Regression model with pycaret" }, { "code": null, "e": 12439, "s": 12380, "text": "Saving and loading trained/finalized model Microsoft Azure" }, { "code": null, "e": 12504, "s": 12439, "text": "Deploying trained/finalized model to Microsoft’s Azure container" } ]
How to Generate JSON with JsonGenerator in Java?
08 Jun, 2022 The JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is lightweight, flexible, and faster than XML, which is the reason that it is used widely for data interchange between server and client. If you ever work on Java Enterprise Applications then you will come across tasks where you might need to generate and parse JSON data for your application. For instance, RESTful web services use JSON extensively as the format for the data inside requests and responses. The following examples show a JSON object with name-value pairs: { "firstName": "Duke", "lastName": "Java", "age": 18, "streetAddress": "100 Internet Dr", "city": "JavaTown", "state": "JA", "postalCode": "12345", "phoneNumbers": [ { "Mobile": "111-111-1111" }, { "Home": "222-222-2222" } ] } Java provides an API to parse, transform, and query JSON data using either the object model or the streaming model. The object model works by creating a tree that represents the JSON data in memory. The object model generates JSON output by navigating the entire tree at once and hence, allows for processing that requires access to the entire contents of the tree at once. The tree can be navigated, analyzed, or modified. This approach is considered flexible but it is slower than the streaming model and requires more memory. Java API provides the javax.json package, it contains a reader interface, a writer interface, and a model builder interface for the object model. The package also contains other utility classes and Java types for JSON elements. In the object model, a JSON-object reference is created which represents the root of the tree and can be used to navigate the tree or to write it to a stream as JSON data. This JSON-object reference created can either be of type JsonObject or JsonArray, and both of them are the subtypes of JsonStructure. Which one it will depend on the format/content of the file. Let’s describe each of them to be precise and clear. Let us go through some traits of JsonObject Written in key-value pairs. Keys must be strings and values must be valid JSON type. JsonObject starts and ends with curly braces { }. Order is not important. Sample code for JSON object is as follows in below illustration { "name" : "GeeksforGeeks", "description" : "An educational website" } Let us go through some traits of JsonArray Used to organize a collection of related items. Values can be of type string, number, object, array, boolean, or null. JsonArray starts and ends with square brackets [ ]. Order is important. Illustration: [1, 2, 3, 4] JsonObject and JsonArray can also be used in a nested manner to represent some special kind of data. You can either use the object inside the array or the array inside the object. { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ], "positions" : [ {"department" : "Testing", "role" : "Junior"}, {"department" : "Testing", "role" : "Senior"}, {"department" : "Design", "role" : "Junior"} ] } Now that we are clear with the basics, we can learn how to code. Now let us come onto installing javax.json API. So, If you are using a Maven project then add this dependency to your pom.xml file: <dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> <version>1.1.4</version> </dependency> Otherwise, in case you are creating a normal project then add the javax.json jar to your Libraries else download the jar file from here and follow the below steps Step 1: Creating Object model from given JSON data if we assume that we already have some data in the JSON format, and thus want to convert that into a java JsonObject, then we can make use of the javax.json.JsonStructure. Let us assume we have a sample.txt that stores JSON data as follows: { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type":"home", "number":"212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] } Apart from just creating an object of the data, we need to have a way to read that data as well! Step 2: Navigate it. For navigating the data we will create a function navigateTree() that will take the JSON object/model that we created, as an input, and for every object or array that it encounters nested inside the JSON model, it will call the navigating function again, and if the element is a value, then it will print the standard output. Now we can proceed to code for creating a JsonStructure out of this sample.txt file which is as shown below Example Java // Java Program to create a JsonStructure of an already// existing data in the JSON format // Importing required classesimport java.io.FileNotFoundException;import java.io.FileReader;import javax.json.Json;import javax.json.JsonArray;import javax.json.JsonNumber;import javax.json.JsonObject;import javax.json.JsonReader;import javax.json.JsonString;import javax.json.JsonStructure;import javax.json.JsonValue; // Main classpublic class CreateObjectModelFromJSONData { // Main driver method public static void main(String args[]) throws FileNotFoundException { // JsonReader: an interface that reads a JSON object // or an array structure from an input source. JsonReader reader = Json.createReader( new FileReader("sample.txt")); // JsonStructure: an interface that is a super type // for the two structured types in JSON // (objects and arrays) JsonStructure jsonst = reader.read(); // navigateTree method takes two arguments: a JSON // element and a key. The key is used only to help // print the key-value pairs inside objects. // Elements in a tree are represented by the // JsonValue type. navigateTree(jsonst, null); } // A JsonValue is one of the following: an object // (JsonObject), an array (JsonArray), a number // (JsonNumber), a string (JsonString), true // (JsonValue.TRUE), false (JsonValue.FALSE), or null // (JsonValue.NULL). // Method 2 // To navigate through the model // and print the key-value pairs public static void navigateTree(JsonValue tree, String key) { if (key != null) System.out.print("Key " + key + ": "); // Switch case // Method 3 // getValueType() returns the value type of // this JSON value. switch (tree.getValueType()) { // Case 1 case OBJECT: System.out.println("OBJECT"); JsonObject object = (JsonObject)tree; for (String name : object.keySet()) navigateTree(object.get(name), name); break; // Case 2 case ARRAY: System.out.println("ARRAY"); JsonArray array = (JsonArray)tree; for (JsonValue val : array) navigateTree(val, null); break; // Case 3 case STRING: JsonString st = (JsonString)tree; System.out.println("STRING " + st.getString()); break; // Case 4 case NUMBER: JsonNumber num = (JsonNumber)tree; System.out.println("NUMBER " + num.toString()); break; // Case 5 case TRUE: // Case 6 case FALSE: // Case 7 case NULL: // Print statement System.out.println( tree.getValueType().toString()); break; } }} Output OBJECT Key firstName: STRING John Key lastName: STRING Smith Key age: NUMBER 25 Key address: OBJECT Key streetAddress: STRING 21 2nd Street Key city: STRING New York Key state: STRING NY Key postalCode: STRING 10021 Key phoneNumber: ARRAY OBJECT Key type: STRING home Key number: STRING 212 555-1234 OBJECT Key type: STRING fax Key number: STRING 646 555-4567 2. Creating an object model from code In order to create an object model of our own from scratch we will make use of the JSON class that provides a method createObjectBuilder() that creates a JSON object builder. The JsonObjectBuilder interface acts as a builder for creating JsonObject models from scratch. This interface initializes an empty JSON object model and provides methods to add name/value pairs to the object model and to return the resulting object. The methods in this class can be chained to add multiple name/value pairs to the object. Example Java // Java Program to create a Json object from scratch using// JsonObjectBuilder and navigate it. // Importing required classesimport javax.json.Json;import javax.json.JsonArray;import javax.json.JsonNumber;import javax.json.JsonObject;import javax.json.JsonString;import javax.json.JsonValue; // Main class// CreateObjectModelFromCodepublic class GFG { // Method 1 // Main driver method public static void main(String args[]) { // add() method adds a name/value pair to the JSON // object associated with this object builder. // build() method returns the JSON object associated // with this object builder. JsonObject model = Json.createObjectBuilder() .add("firstName", "Duke") .add("lastName", "Java") .add("age", 18) .add("streetAddress", "100 Internet Dr") .add("city", "JavaTown") .add("state", "JA") .add("postalCode", "12345") .add("phoneNumbers", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "mobile") .add("number", "111-111-1111")) .add(Json.createObjectBuilder() .add("type", "home") .add("number", "222-222-2222"))) .build(); // The same navigateTree() method can be used to // navigate this model. navigateTree(model, null); } // Method 2 public static void navigateTree(JsonValue tree, String key) { if (key != null) System.out.print("Key " + key + ": "); // Method 3- getValueType() // To get the value types // Switch case switch (tree.getValueType()) { // Case 1 case OBJECT: System.out.println("OBJECT"); JsonObject object = (JsonObject)tree; for (String name : object.keySet()) navigateTree(object.get(name), name); break; // Case 2 case ARRAY: System.out.println("ARRAY"); JsonArray array = (JsonArray)tree; for (JsonValue val : array) navigateTree(val, null); break; // Case 3 case STRING: JsonString st = (JsonString)tree; System.out.println("STRING " + st.getString()); break; // Case 4 case NUMBER: JsonNumber num = (JsonNumber)tree; System.out.println("NUMBER " + num.toString()); break; // Case 5 case TRUE: // Case 6 case FALSE: // Case 7 case NULL: System.out.println( tree.getValueType().toString()); break; } }} Output OBJECT Key firstName: STRING Duke Key lastName: STRING Java Key age: NUMBER 18 Key streetAddress: STRING 100 Internet Dr Key city: STRING JavaTown Key state: STRING JA Key postalCode: STRING 12345 Key phoneNumbers: ARRAY OBJECT Key type: STRING mobile Key number: STRING 111-111-1111 OBJECT Key type: STRING home Key number: STRING 222-222-2222 3. Writing Object model to a Stream The object models that we created in the above examples can be written to a stream using the JsonWriter class. JsonWriter writes a JSON object or array structure to an output source. This time we will write the contents of the sample.txt to an output stream after we have converted it to a JsonStructure. Example Java // Java Program to Write the Object Model to an Output Stream // Importing required classesimport java.io.FileNotFoundException;import java.io.FileReader;import java.io.StringWriter;import javax.json.Json;import javax.json.JsonObject;import javax.json.JsonReader;import javax.json.JsonStructure;import javax.json.JsonWriter; // Main class// WritingObjectModelToAStreampublic class GFG { // Main driver method public static void main(String args[]) throws FileNotFoundException { JsonReader reader = Json.createReader( new FileReader("sample.txt")); JsonStructure jsonst = reader.read(); StringWriter stWriter = new StringWriter(); // We use try-with-resources to close the JSON // writer automatically // Json.createWriter() method takes an output stream // as a parameter. JsonWriter.writeObject() method // writes the object to the stream. // Try block to check for exceptions try (JsonWriter jsonWriter = Json.createWriter(stWriter)) { jsonWriter.writeObject((JsonObject)jsonst); } // Creating variable jsonData to store the object // written to the stream in the form of a String String jsonData = stWriter.toString(); // Print the data string System.out.println(jsonData); }} Output: On the console, the following will be printed in a single line { "firstName":"John","lastName":"Smith","age":25, "address":{"streetAddress":"21 2nd Street","city":"New York","state":"NY","postalCode":"10021"}, "phoneNumber":[{"type":"home","number":"212 555-1234"},{"type":"fax","number":"646 555-4567"}] } Now dwelling onto next model, The streaming model uses an event-based parser that reads JSON data one element at a time. The streaming model generates JSON output to a given stream by making a function call with one element at a time. This approach is adequate for local processing, in which the processing of an element does not require information from the rest of the data. The way it works is that the parser generates events and stops for processing whenever it either finds a key, or finds a value, or reaches the beginning or end of an object or array. The element found can be processed or discarded based on the code and then the parser moves to the next event. The Java API provides the javax.json.stream package, it contains a parser interface, JsonParser, and a generator interface, JsonGenerator for the streaming model. The interface JsonParser contains methods to parse JSON in a streaming way. The interface JsonGenerator contains methods to write JSON to an output source in a streaming way. In the upcoming code, we will make use of the same sample.txt file to parse it. 1. Reading JSON data using a Parser: We will use the JsonParser that provides forward, read-only access to JSON data in a streaming way. JsonParser parses JSON using the pull parsing programming model. In this model, the client code controls the thread and calls the method next() to advance the parser to the next state after processing each element. The parser can generate the following events: START_OBJECT, END_OBJECT, START_ARRAY, END_ARRAY, KEY_NAME, VALUE_STRING, VALUE_NUMBER, VALUE_TRUE, VALUE_FALSE, and VALUE_NULL. In the following code we will perform the following steps: Get the JSON data in the form of a String, so that it can be passed to the parser object.Obtain a parser instance by calling the JSON.createParser static method and pass the string to it.Iterate over the parser events with the JsonParser.hasNext and the JsonParser.next methods.Perform local processing for each element. Get the JSON data in the form of a String, so that it can be passed to the parser object. Obtain a parser instance by calling the JSON.createParser static method and pass the string to it. Iterate over the parser events with the JsonParser.hasNext and the JsonParser.next methods. Perform local processing for each element. Implementation: Example Java // Java program to Read JSON data using a JsonParser // Importing required classesimport java.io.FileNotFoundException;import java.io.FileReader;import java.io.StringReader;import java.io.StringWriter;import javax.json.Json;import javax.json.JsonObject;import javax.json.JsonReader;import javax.json.JsonStructure;import javax.json.JsonWriter;import javax.json.stream.JsonParser; // Main class// ReadingJSONDataUsingAParserpublic class GFG { // Main driver method public static void main(String args[]) throws FileNotFoundException { // Creating object of JsonReader class // Creating object of JsonStructure class JsonReader reader = Json.createReader( new FileReader("sample.txt")); JsonStructure jsonst = reader.read(); StringWriter stWriter = new StringWriter(); // Try block to check for exceptions try (JsonWriter jsonWriter = Json.createWriter(stWriter)) { jsonWriter.writeObject((JsonObject)jsonst); } // Step 1 String jsonData = stWriter.toString(); // Step 2 // Json.createParser(): Creates a JSON parser from a // character stream. JsonParser parser = Json.createParser(new StringReader(jsonData)); // Step 3 // haNext(): Returns true if there are more parsing // states. This method returns false if the parser // reaches the end of the JSON text while (parser.hasNext()) { // JsonParser.Event: An event from JsonParser. // next(): Returns the event for the next // parsing state. JsonParser.Event event = parser.next(); // Step 4 // Switch case switch (event) { // Case 1 // Start of a JSON array. case START_ARRAY: // Case 2 // End of a JSON array. case END_ARRAY: // Case 3 // Start of a JSON object. case START_OBJECT: // Case 4 // End of a JSON object. case END_OBJECT: // Case 5 // False value in a JSON array or object. case VALUE_FALSE: // Case 6 // Null value in a JSON array or object. case VALUE_NULL: // Case 7 // True value in a JSON array or object. case VALUE_TRUE: System.out.println(event.toString()); break; // Case 8 // Name in a name/value pair of a JSON object. case KEY_NAME: System.out.print(event.toString() + " " + parser.getString() + " - "); break; // Case 9 // String value in a JSON array or object. case VALUE_STRING: // Case 10 // Number value in a JSON array or object. case VALUE_NUMBER: System.out.println(event.toString() + " " + parser.getString()); break; } } }} Output: START_OBJECT KEY_NAME firstName - VALUE_STRING John KEY_NAME lastName - VALUE_STRING Smith KEY_NAME age - VALUE_NUMBER 25 KEY_NAME address - START_OBJECT KEY_NAME streetAddress - VALUE_STRING 21 2nd Street KEY_NAME city - VALUE_STRING New York KEY_NAME state - VALUE_STRING NY KEY_NAME postalCode - VALUE_STRING 10021 END_OBJECT KEY_NAME phoneNumber - START_ARRAY START_OBJECT KEY_NAME type - VALUE_STRING home KEY_NAME number - VALUE_STRING 212 555-1234 END_OBJECT START_OBJECT KEY_NAME type - VALUE_STRING fax KEY_NAME number - VALUE_STRING 646 555-4567 END_OBJECT END_ARRAY END_OBJECT 2. Writing JSON Data using Generator Using the JsonGenerator we can write JSON data to an output source in a streaming way. Obtain a JSON generator by calling the Json.createGenerator static method, which takes a writer or an output stream as a parameter. We will write the JSON data to a details.txt file. Example Java // Java Program to Generate JSON data and Store it into a// file. // Importing required classesimport java.io.FileWriter;import java.io.IOException;import javax.json.Json;import javax.json.stream.JsonGenerator; // Main class// WriteJSONDataUsingGeneratorpublic class GFG { // Main driver method public static void main(String args[]) { FileWriter writer = null; // Try block to check for exceptions try { writer = new FileWriter("details.txt"); } // Catch block to handle i/o exceptions catch (IOException e) { // Print the exceptions along with line number // using printStackTrace() method e.printStackTrace(); } // Json.createGenerator(): Creates a JSON generator // for writing JSON to a character stream. JsonGenerator generator = Json.createGenerator(writer); // writeStartObject(): Writes the JSON name/start // object character pair in the current object // context. write(): Writes a JSON name/string value // pair in the current object context. writeEnd(): // Writes the end of the current context. // writeStartArray(): Writes the JSON name/start // array character pair with in the current object // context. generator.writeStartObject() .write("firstName", "John") .write("lastName", "Smith") .write("age", 25) .writeStartObject("address") .write("streetAddress", "21 2nd Street") .write("city", "New York") .write("state", "NY") .write("postalCode", "10021") .writeEnd() .writeStartArray("phoneNumber") .writeStartObject() .write("type", "home") .write("number", "212 555-1234") .writeEnd() .writeStartObject() .write("type", "fax") .write("number", "646 555-4567") .writeEnd() .writeEnd() .writeEnd(); // Closes this generator and frees any resources // associated with it using close() method generator.close(); }} Output: In the details.txt file the following data will be written in a single line: { "firstName":"John","lastName":"Smith","age":25, "address":{"streetAddress":"21 2nd Street","city":"New York","state":"NY","postalCode":"10021"}, "phoneNumber":[{"type":"home","number":"212 555-1234"},{"type":"fax","number":"646 555-4567"}] } gabaa406 simmytarika5 Code_r JSON Picked 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": "\n08 Jun, 2022" }, { "code": null, "e": 577, "s": 28, "text": "The JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is lightweight, flexible, and faster than XML, which is the reason that it is used widely for data interchange between server and client. If you ever work on Java Enterprise Applications then you will come across tasks where you might need to generate and parse JSON data for your application. For instance, RESTful web services use JSON extensively as the format for the data inside requests and responses." }, { "code": null, "e": 642, "s": 577, "text": "The following examples show a JSON object with name-value pairs:" }, { "code": null, "e": 908, "s": 642, "text": "{\n \"firstName\": \"Duke\",\n \"lastName\": \"Java\",\n \"age\": 18,\n \"streetAddress\": \"100 Internet Dr\",\n \"city\": \"JavaTown\",\n \"state\": \"JA\",\n \"postalCode\": \"12345\",\n \"phoneNumbers\": [\n { \"Mobile\": \"111-111-1111\" },\n { \"Home\": \"222-222-2222\" }\n ]\n}" }, { "code": null, "e": 1024, "s": 908, "text": "Java provides an API to parse, transform, and query JSON data using either the object model or the streaming model." }, { "code": null, "e": 1437, "s": 1024, "text": "The object model works by creating a tree that represents the JSON data in memory. The object model generates JSON output by navigating the entire tree at once and hence, allows for processing that requires access to the entire contents of the tree at once. The tree can be navigated, analyzed, or modified. This approach is considered flexible but it is slower than the streaming model and requires more memory." }, { "code": null, "e": 1665, "s": 1437, "text": "Java API provides the javax.json package, it contains a reader interface, a writer interface, and a model builder interface for the object model. The package also contains other utility classes and Java types for JSON elements." }, { "code": null, "e": 2032, "s": 1665, "text": "In the object model, a JSON-object reference is created which represents the root of the tree and can be used to navigate the tree or to write it to a stream as JSON data. This JSON-object reference created can either be of type JsonObject or JsonArray, and both of them are the subtypes of JsonStructure. Which one it will depend on the format/content of the file. " }, { "code": null, "e": 2085, "s": 2032, "text": "Let’s describe each of them to be precise and clear." }, { "code": null, "e": 2129, "s": 2085, "text": "Let us go through some traits of JsonObject" }, { "code": null, "e": 2157, "s": 2129, "text": "Written in key-value pairs." }, { "code": null, "e": 2214, "s": 2157, "text": "Keys must be strings and values must be valid JSON type." }, { "code": null, "e": 2264, "s": 2214, "text": "JsonObject starts and ends with curly braces { }." }, { "code": null, "e": 2288, "s": 2264, "text": "Order is not important." }, { "code": null, "e": 2352, "s": 2288, "text": "Sample code for JSON object is as follows in below illustration" }, { "code": null, "e": 2431, "s": 2352, "text": "{\n \"name\" : \"GeeksforGeeks\",\n \"description\" : \"An educational website\"\n}" }, { "code": null, "e": 2474, "s": 2431, "text": "Let us go through some traits of JsonArray" }, { "code": null, "e": 2522, "s": 2474, "text": "Used to organize a collection of related items." }, { "code": null, "e": 2593, "s": 2522, "text": "Values can be of type string, number, object, array, boolean, or null." }, { "code": null, "e": 2645, "s": 2593, "text": "JsonArray starts and ends with square brackets [ ]." }, { "code": null, "e": 2665, "s": 2645, "text": "Order is important." }, { "code": null, "e": 2679, "s": 2665, "text": "Illustration:" }, { "code": null, "e": 2692, "s": 2679, "text": "[1, 2, 3, 4]" }, { "code": null, "e": 2872, "s": 2692, "text": "JsonObject and JsonArray can also be used in a nested manner to represent some special kind of data. You can either use the object inside the array or the array inside the object." }, { "code": null, "e": 3239, "s": 2872, "text": "{\n \"employees\":[\n {\"firstName\":\"John\", \"lastName\":\"Doe\"},\n {\"firstName\":\"Anna\", \"lastName\":\"Smith\"},\n {\"firstName\":\"Peter\", \"lastName\":\"Jones\"}\n ],\n \"positions\" : [\n {\"department\" : \"Testing\", \"role\" : \"Junior\"},\n {\"department\" : \"Testing\", \"role\" : \"Senior\"},\n {\"department\" : \"Design\", \"role\" : \"Junior\"}\n ] \n}" }, { "code": null, "e": 3304, "s": 3239, "text": "Now that we are clear with the basics, we can learn how to code." }, { "code": null, "e": 3436, "s": 3304, "text": "Now let us come onto installing javax.json API. So, If you are using a Maven project then add this dependency to your pom.xml file:" }, { "code": null, "e": 3570, "s": 3436, "text": "<dependency>\n <groupId>javax.json</groupId>\n <artifactId>javax.json-api</artifactId>\n <version>1.1.4</version>\n</dependency>" }, { "code": null, "e": 3733, "s": 3570, "text": "Otherwise, in case you are creating a normal project then add the javax.json jar to your Libraries else download the jar file from here and follow the below steps" }, { "code": null, "e": 3784, "s": 3733, "text": "Step 1: Creating Object model from given JSON data" }, { "code": null, "e": 3956, "s": 3784, "text": "if we assume that we already have some data in the JSON format, and thus want to convert that into a java JsonObject, then we can make use of the javax.json.JsonStructure." }, { "code": null, "e": 4025, "s": 3956, "text": "Let us assume we have a sample.txt that stores JSON data as follows:" }, { "code": null, "e": 4355, "s": 4025, "text": "{\n \"firstName\": \"John\",\n \"lastName\": \"Smith\",\n \"age\": 25,\n \"address\": {\n \"streetAddress\": \"21 2nd Street\",\n \"city\": \"New York\",\n \"state\": \"NY\",\n \"postalCode\": \"10021\"\n },\n\n \"phoneNumber\":\n [\n\n {\n \"type\":\"home\",\n \"number\":\"212 555-1234\"\n },\n\n {\n \"type\": \"fax\",\n \"number\": \"646 555-4567\"\n }\n ]\n}" }, { "code": null, "e": 4453, "s": 4355, "text": "Apart from just creating an object of the data, we need to have a way to read that data as well! " }, { "code": null, "e": 4474, "s": 4453, "text": "Step 2: Navigate it." }, { "code": null, "e": 4800, "s": 4474, "text": "For navigating the data we will create a function navigateTree() that will take the JSON object/model that we created, as an input, and for every object or array that it encounters nested inside the JSON model, it will call the navigating function again, and if the element is a value, then it will print the standard output." }, { "code": null, "e": 4908, "s": 4800, "text": "Now we can proceed to code for creating a JsonStructure out of this sample.txt file which is as shown below" }, { "code": null, "e": 4917, "s": 4908, "text": "Example " }, { "code": null, "e": 4922, "s": 4917, "text": "Java" }, { "code": "// Java Program to create a JsonStructure of an already// existing data in the JSON format // Importing required classesimport java.io.FileNotFoundException;import java.io.FileReader;import javax.json.Json;import javax.json.JsonArray;import javax.json.JsonNumber;import javax.json.JsonObject;import javax.json.JsonReader;import javax.json.JsonString;import javax.json.JsonStructure;import javax.json.JsonValue; // Main classpublic class CreateObjectModelFromJSONData { // Main driver method public static void main(String args[]) throws FileNotFoundException { // JsonReader: an interface that reads a JSON object // or an array structure from an input source. JsonReader reader = Json.createReader( new FileReader(\"sample.txt\")); // JsonStructure: an interface that is a super type // for the two structured types in JSON // (objects and arrays) JsonStructure jsonst = reader.read(); // navigateTree method takes two arguments: a JSON // element and a key. The key is used only to help // print the key-value pairs inside objects. // Elements in a tree are represented by the // JsonValue type. navigateTree(jsonst, null); } // A JsonValue is one of the following: an object // (JsonObject), an array (JsonArray), a number // (JsonNumber), a string (JsonString), true // (JsonValue.TRUE), false (JsonValue.FALSE), or null // (JsonValue.NULL). // Method 2 // To navigate through the model // and print the key-value pairs public static void navigateTree(JsonValue tree, String key) { if (key != null) System.out.print(\"Key \" + key + \": \"); // Switch case // Method 3 // getValueType() returns the value type of // this JSON value. switch (tree.getValueType()) { // Case 1 case OBJECT: System.out.println(\"OBJECT\"); JsonObject object = (JsonObject)tree; for (String name : object.keySet()) navigateTree(object.get(name), name); break; // Case 2 case ARRAY: System.out.println(\"ARRAY\"); JsonArray array = (JsonArray)tree; for (JsonValue val : array) navigateTree(val, null); break; // Case 3 case STRING: JsonString st = (JsonString)tree; System.out.println(\"STRING \" + st.getString()); break; // Case 4 case NUMBER: JsonNumber num = (JsonNumber)tree; System.out.println(\"NUMBER \" + num.toString()); break; // Case 5 case TRUE: // Case 6 case FALSE: // Case 7 case NULL: // Print statement System.out.println( tree.getValueType().toString()); break; } }}", "e": 7882, "s": 4922, "text": null }, { "code": null, "e": 7891, "s": 7882, "text": " Output " }, { "code": null, "e": 8251, "s": 7891, "text": "OBJECT\nKey firstName: STRING John\nKey lastName: STRING Smith\nKey age: NUMBER 25\nKey address: OBJECT\nKey streetAddress: STRING 21 2nd Street\nKey city: STRING New York\nKey state: STRING NY\nKey postalCode: STRING 10021\nKey phoneNumber: ARRAY\nOBJECT\nKey type: STRING home\nKey number: STRING 212 555-1234\nOBJECT\nKey type: STRING fax\nKey number: STRING 646 555-4567" }, { "code": null, "e": 8289, "s": 8251, "text": "2. Creating an object model from code" }, { "code": null, "e": 8804, "s": 8289, "text": "In order to create an object model of our own from scratch we will make use of the JSON class that provides a method createObjectBuilder() that creates a JSON object builder. The JsonObjectBuilder interface acts as a builder for creating JsonObject models from scratch. This interface initializes an empty JSON object model and provides methods to add name/value pairs to the object model and to return the resulting object. The methods in this class can be chained to add multiple name/value pairs to the object." }, { "code": null, "e": 8813, "s": 8804, "text": "Example " }, { "code": null, "e": 8818, "s": 8813, "text": "Java" }, { "code": "// Java Program to create a Json object from scratch using// JsonObjectBuilder and navigate it. // Importing required classesimport javax.json.Json;import javax.json.JsonArray;import javax.json.JsonNumber;import javax.json.JsonObject;import javax.json.JsonString;import javax.json.JsonValue; // Main class// CreateObjectModelFromCodepublic class GFG { // Method 1 // Main driver method public static void main(String args[]) { // add() method adds a name/value pair to the JSON // object associated with this object builder. // build() method returns the JSON object associated // with this object builder. JsonObject model = Json.createObjectBuilder() .add(\"firstName\", \"Duke\") .add(\"lastName\", \"Java\") .add(\"age\", 18) .add(\"streetAddress\", \"100 Internet Dr\") .add(\"city\", \"JavaTown\") .add(\"state\", \"JA\") .add(\"postalCode\", \"12345\") .add(\"phoneNumbers\", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add(\"type\", \"mobile\") .add(\"number\", \"111-111-1111\")) .add(Json.createObjectBuilder() .add(\"type\", \"home\") .add(\"number\", \"222-222-2222\"))) .build(); // The same navigateTree() method can be used to // navigate this model. navigateTree(model, null); } // Method 2 public static void navigateTree(JsonValue tree, String key) { if (key != null) System.out.print(\"Key \" + key + \": \"); // Method 3- getValueType() // To get the value types // Switch case switch (tree.getValueType()) { // Case 1 case OBJECT: System.out.println(\"OBJECT\"); JsonObject object = (JsonObject)tree; for (String name : object.keySet()) navigateTree(object.get(name), name); break; // Case 2 case ARRAY: System.out.println(\"ARRAY\"); JsonArray array = (JsonArray)tree; for (JsonValue val : array) navigateTree(val, null); break; // Case 3 case STRING: JsonString st = (JsonString)tree; System.out.println(\"STRING \" + st.getString()); break; // Case 4 case NUMBER: JsonNumber num = (JsonNumber)tree; System.out.println(\"NUMBER \" + num.toString()); break; // Case 5 case TRUE: // Case 6 case FALSE: // Case 7 case NULL: System.out.println( tree.getValueType().toString()); break; } }}", "e": 11858, "s": 8818, "text": null }, { "code": null, "e": 11866, "s": 11858, "text": "Output " }, { "code": null, "e": 12211, "s": 11866, "text": "OBJECT\nKey firstName: STRING Duke\nKey lastName: STRING Java\nKey age: NUMBER 18\nKey streetAddress: STRING 100 Internet Dr\nKey city: STRING JavaTown\nKey state: STRING JA\nKey postalCode: STRING 12345\nKey phoneNumbers: ARRAY\nOBJECT\nKey type: STRING mobile\nKey number: STRING 111-111-1111\nOBJECT\nKey type: STRING home\nKey number: STRING 222-222-2222" }, { "code": null, "e": 12247, "s": 12211, "text": "3. Writing Object model to a Stream" }, { "code": null, "e": 12552, "s": 12247, "text": "The object models that we created in the above examples can be written to a stream using the JsonWriter class. JsonWriter writes a JSON object or array structure to an output source. This time we will write the contents of the sample.txt to an output stream after we have converted it to a JsonStructure." }, { "code": null, "e": 12561, "s": 12552, "text": "Example " }, { "code": null, "e": 12566, "s": 12561, "text": "Java" }, { "code": "// Java Program to Write the Object Model to an Output Stream // Importing required classesimport java.io.FileNotFoundException;import java.io.FileReader;import java.io.StringWriter;import javax.json.Json;import javax.json.JsonObject;import javax.json.JsonReader;import javax.json.JsonStructure;import javax.json.JsonWriter; // Main class// WritingObjectModelToAStreampublic class GFG { // Main driver method public static void main(String args[]) throws FileNotFoundException { JsonReader reader = Json.createReader( new FileReader(\"sample.txt\")); JsonStructure jsonst = reader.read(); StringWriter stWriter = new StringWriter(); // We use try-with-resources to close the JSON // writer automatically // Json.createWriter() method takes an output stream // as a parameter. JsonWriter.writeObject() method // writes the object to the stream. // Try block to check for exceptions try (JsonWriter jsonWriter = Json.createWriter(stWriter)) { jsonWriter.writeObject((JsonObject)jsonst); } // Creating variable jsonData to store the object // written to the stream in the form of a String String jsonData = stWriter.toString(); // Print the data string System.out.println(jsonData); }}", "e": 13920, "s": 12566, "text": null }, { "code": null, "e": 13993, "s": 13920, "text": " Output: On the console, the following will be printed in a single line " }, { "code": null, "e": 14237, "s": 13993, "text": "{\n\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":25,\n\"address\":{\"streetAddress\":\"21 2nd Street\",\"city\":\"New York\",\"state\":\"NY\",\"postalCode\":\"10021\"},\n\"phoneNumber\":[{\"type\":\"home\",\"number\":\"212 555-1234\"},{\"type\":\"fax\",\"number\":\"646 555-4567\"}]\n}" }, { "code": null, "e": 14268, "s": 14237, "text": "Now dwelling onto next model, " }, { "code": null, "e": 14909, "s": 14268, "text": "The streaming model uses an event-based parser that reads JSON data one element at a time. The streaming model generates JSON output to a given stream by making a function call with one element at a time. This approach is adequate for local processing, in which the processing of an element does not require information from the rest of the data. The way it works is that the parser generates events and stops for processing whenever it either finds a key, or finds a value, or reaches the beginning or end of an object or array. The element found can be processed or discarded based on the code and then the parser moves to the next event." }, { "code": null, "e": 15248, "s": 14909, "text": "The Java API provides the javax.json.stream package, it contains a parser interface, JsonParser, and a generator interface, JsonGenerator for the streaming model. The interface JsonParser contains methods to parse JSON in a streaming way. The interface JsonGenerator contains methods to write JSON to an output source in a streaming way. " }, { "code": null, "e": 15328, "s": 15248, "text": "In the upcoming code, we will make use of the same sample.txt file to parse it." }, { "code": null, "e": 15728, "s": 15328, "text": "1. Reading JSON data using a Parser: We will use the JsonParser that provides forward, read-only access to JSON data in a streaming way. JsonParser parses JSON using the pull parsing programming model. In this model, the client code controls the thread and calls the method next() to advance the parser to the next state after processing each element. The parser can generate the following events: " }, { "code": null, "e": 15857, "s": 15728, "text": "START_OBJECT, END_OBJECT, START_ARRAY, END_ARRAY, KEY_NAME, VALUE_STRING, VALUE_NUMBER, VALUE_TRUE, VALUE_FALSE, and VALUE_NULL." }, { "code": null, "e": 15917, "s": 15857, "text": "In the following code we will perform the following steps: " }, { "code": null, "e": 16238, "s": 15917, "text": "Get the JSON data in the form of a String, so that it can be passed to the parser object.Obtain a parser instance by calling the JSON.createParser static method and pass the string to it.Iterate over the parser events with the JsonParser.hasNext and the JsonParser.next methods.Perform local processing for each element." }, { "code": null, "e": 16328, "s": 16238, "text": "Get the JSON data in the form of a String, so that it can be passed to the parser object." }, { "code": null, "e": 16427, "s": 16328, "text": "Obtain a parser instance by calling the JSON.createParser static method and pass the string to it." }, { "code": null, "e": 16519, "s": 16427, "text": "Iterate over the parser events with the JsonParser.hasNext and the JsonParser.next methods." }, { "code": null, "e": 16562, "s": 16519, "text": "Perform local processing for each element." }, { "code": null, "e": 16578, "s": 16562, "text": "Implementation:" }, { "code": null, "e": 16587, "s": 16578, "text": "Example " }, { "code": null, "e": 16592, "s": 16587, "text": "Java" }, { "code": "// Java program to Read JSON data using a JsonParser // Importing required classesimport java.io.FileNotFoundException;import java.io.FileReader;import java.io.StringReader;import java.io.StringWriter;import javax.json.Json;import javax.json.JsonObject;import javax.json.JsonReader;import javax.json.JsonStructure;import javax.json.JsonWriter;import javax.json.stream.JsonParser; // Main class// ReadingJSONDataUsingAParserpublic class GFG { // Main driver method public static void main(String args[]) throws FileNotFoundException { // Creating object of JsonReader class // Creating object of JsonStructure class JsonReader reader = Json.createReader( new FileReader(\"sample.txt\")); JsonStructure jsonst = reader.read(); StringWriter stWriter = new StringWriter(); // Try block to check for exceptions try (JsonWriter jsonWriter = Json.createWriter(stWriter)) { jsonWriter.writeObject((JsonObject)jsonst); } // Step 1 String jsonData = stWriter.toString(); // Step 2 // Json.createParser(): Creates a JSON parser from a // character stream. JsonParser parser = Json.createParser(new StringReader(jsonData)); // Step 3 // haNext(): Returns true if there are more parsing // states. This method returns false if the parser // reaches the end of the JSON text while (parser.hasNext()) { // JsonParser.Event: An event from JsonParser. // next(): Returns the event for the next // parsing state. JsonParser.Event event = parser.next(); // Step 4 // Switch case switch (event) { // Case 1 // Start of a JSON array. case START_ARRAY: // Case 2 // End of a JSON array. case END_ARRAY: // Case 3 // Start of a JSON object. case START_OBJECT: // Case 4 // End of a JSON object. case END_OBJECT: // Case 5 // False value in a JSON array or object. case VALUE_FALSE: // Case 6 // Null value in a JSON array or object. case VALUE_NULL: // Case 7 // True value in a JSON array or object. case VALUE_TRUE: System.out.println(event.toString()); break; // Case 8 // Name in a name/value pair of a JSON object. case KEY_NAME: System.out.print(event.toString() + \" \" + parser.getString() + \" - \"); break; // Case 9 // String value in a JSON array or object. case VALUE_STRING: // Case 10 // Number value in a JSON array or object. case VALUE_NUMBER: System.out.println(event.toString() + \" \" + parser.getString()); break; } } }}", "e": 19734, "s": 16592, "text": null }, { "code": null, "e": 19744, "s": 19734, "text": " Output: " }, { "code": null, "e": 20332, "s": 19744, "text": "START_OBJECT\nKEY_NAME firstName - VALUE_STRING John\nKEY_NAME lastName - VALUE_STRING Smith\nKEY_NAME age - VALUE_NUMBER 25\nKEY_NAME address - START_OBJECT\nKEY_NAME streetAddress - VALUE_STRING 21 2nd Street\nKEY_NAME city - VALUE_STRING New York\nKEY_NAME state - VALUE_STRING NY\nKEY_NAME postalCode - VALUE_STRING 10021\nEND_OBJECT\nKEY_NAME phoneNumber - START_ARRAY\nSTART_OBJECT\nKEY_NAME type - VALUE_STRING home\nKEY_NAME number - VALUE_STRING 212 555-1234\nEND_OBJECT\nSTART_OBJECT\nKEY_NAME type - VALUE_STRING fax\nKEY_NAME number - VALUE_STRING 646 555-4567\nEND_OBJECT\nEND_ARRAY\nEND_OBJECT" }, { "code": null, "e": 20369, "s": 20332, "text": "2. Writing JSON Data using Generator" }, { "code": null, "e": 20639, "s": 20369, "text": "Using the JsonGenerator we can write JSON data to an output source in a streaming way. Obtain a JSON generator by calling the Json.createGenerator static method, which takes a writer or an output stream as a parameter. We will write the JSON data to a details.txt file." }, { "code": null, "e": 20647, "s": 20639, "text": "Example" }, { "code": null, "e": 20652, "s": 20647, "text": "Java" }, { "code": "// Java Program to Generate JSON data and Store it into a// file. // Importing required classesimport java.io.FileWriter;import java.io.IOException;import javax.json.Json;import javax.json.stream.JsonGenerator; // Main class// WriteJSONDataUsingGeneratorpublic class GFG { // Main driver method public static void main(String args[]) { FileWriter writer = null; // Try block to check for exceptions try { writer = new FileWriter(\"details.txt\"); } // Catch block to handle i/o exceptions catch (IOException e) { // Print the exceptions along with line number // using printStackTrace() method e.printStackTrace(); } // Json.createGenerator(): Creates a JSON generator // for writing JSON to a character stream. JsonGenerator generator = Json.createGenerator(writer); // writeStartObject(): Writes the JSON name/start // object character pair in the current object // context. write(): Writes a JSON name/string value // pair in the current object context. writeEnd(): // Writes the end of the current context. // writeStartArray(): Writes the JSON name/start // array character pair with in the current object // context. generator.writeStartObject() .write(\"firstName\", \"John\") .write(\"lastName\", \"Smith\") .write(\"age\", 25) .writeStartObject(\"address\") .write(\"streetAddress\", \"21 2nd Street\") .write(\"city\", \"New York\") .write(\"state\", \"NY\") .write(\"postalCode\", \"10021\") .writeEnd() .writeStartArray(\"phoneNumber\") .writeStartObject() .write(\"type\", \"home\") .write(\"number\", \"212 555-1234\") .writeEnd() .writeStartObject() .write(\"type\", \"fax\") .write(\"number\", \"646 555-4567\") .writeEnd() .writeEnd() .writeEnd(); // Closes this generator and frees any resources // associated with it using close() method generator.close(); }}", "e": 22834, "s": 20652, "text": null }, { "code": null, "e": 22920, "s": 22834, "text": "Output: In the details.txt file the following data will be written in a single line: " }, { "code": null, "e": 23164, "s": 22920, "text": "{\n\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":25,\n\"address\":{\"streetAddress\":\"21 2nd Street\",\"city\":\"New York\",\"state\":\"NY\",\"postalCode\":\"10021\"},\n\"phoneNumber\":[{\"type\":\"home\",\"number\":\"212 555-1234\"},{\"type\":\"fax\",\"number\":\"646 555-4567\"}]\n}" }, { "code": null, "e": 23175, "s": 23166, "text": "gabaa406" }, { "code": null, "e": 23188, "s": 23175, "text": "simmytarika5" }, { "code": null, "e": 23195, "s": 23188, "text": "Code_r" }, { "code": null, "e": 23200, "s": 23195, "text": "JSON" }, { "code": null, "e": 23207, "s": 23200, "text": "Picked" }, { "code": null, "e": 23212, "s": 23207, "text": "Java" }, { "code": null, "e": 23217, "s": 23212, "text": "Java" }, { "code": null, "e": 23315, "s": 23217, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23330, "s": 23315, "text": "Stream In Java" }, { "code": null, "e": 23351, "s": 23330, "text": "Introduction to Java" }, { "code": null, "e": 23372, "s": 23351, "text": "Constructors in Java" }, { "code": null, "e": 23391, "s": 23372, "text": "Exceptions in Java" }, { "code": null, "e": 23408, "s": 23391, "text": "Generics in Java" }, { "code": null, "e": 23438, "s": 23408, "text": "Functional Interfaces in Java" }, { "code": null, "e": 23464, "s": 23438, "text": "Java Programming Examples" }, { "code": null, "e": 23480, "s": 23464, "text": "Strings in Java" }, { "code": null, "e": 23517, "s": 23480, "text": "Differences between JDK, JRE and JVM" } ]
Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
10 Jul, 2022 Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-HeapExamples: Input : level = [10, 15, 14, 25, 30] Output : True The tree of the given level order traversal is 10 / \ 15 14 / \ 25 30 We see that each parent has a value less than its child, and hence satisfies the min-heap property Input : level = [30, 56, 22, 49, 30, 51, 2, 67] Output : False The tree of the given level order traversal is 30 / \ 56 22 / \ / \ 49 30 51 2 / 67 We observe that at level 0, 30 > 22, and hence min-heap property is not satisfied We need to check whether each non-leaf node (parent) satisfies the heap property. For this, we check whether each parent (at index i) is smaller than its children (at indices 2*i+1 and 2*i+2, if the parent has two children). If only one child, we only check the parent against index 2*i+1. C++ Java Python3 C# PHP Javascript // C++ program to check if a given tree is// Binary Heap or not#include <bits/stdc++.h>using namespace std; // Returns true if given level order traversal// is Min Heap.bool isMinHeap(int level[], int n){ // First non leaf node is at index (n/2-1). // Check whether each parent is greater than child for (int i=(n/2-1) ; i>=0 ; i--) { // Left child will be at index 2*i+1 // Right child will be at index 2*i+2 if (level[i] > level[2 * i + 1]) return false; if (2*i + 2 < n) { // If parent is greater than right child if (level[i] > level[2 * i + 2]) return false; } } return true;} // Driver codeint main(){ int level[] = {10, 15, 14, 25, 30}; int n = sizeof(level)/sizeof(level[0]); if (isMinHeap(level, n)) cout << "True"; else cout << "False"; return 0;} // Java program to check if a given tree is// Binary Heap or notimport java.io.*;import java.util.*; public class detheap{ // Returns true if given level order traversal // is Min Heap. static boolean isMinHeap(int []level) { int n = level.length - 1; // First non leaf node is at index (n/2-1). // Check whether each parent is greater than child for (int i=(n/2-1) ; i>=0 ; i--) { // Left child will be at index 2*i+1 // Right child will be at index 2*i+2 if (level[i] > level[2 * i + 1]) return false; if (2*i + 2 < n) { // If parent is greater than right child if (level[i] > level[2 * i + 2]) return false; } } return true; } // Driver code public static void main(String[] args) throws IOException { // Level order traversal int[] level = new int[]{10, 15, 14, 25, 30}; if (isMinHeap(level)) System.out.println("True"); else System.out.println("False"); }} # Python3 program to check if a given# tree is Binary Heap or not # Returns true if given level order# traversal is Min Heap.def isMinHeap(level, n): # First non leaf node is at index # (n/2-1). Check whether each parent # is greater than child for i in range(int(n / 2) - 1, -1, -1): # Left child will be at index 2*i+1 # Right child will be at index 2*i+2 if level[i] > level[2 * i + 1]: return False if 2 * i + 2 < n: # If parent is greater than right child if level[i] > level[2 * i + 2]: return False return True # Driver codeif __name__ == '__main__': level = [10, 15, 14, 25, 30] n = len(level) if isMinHeap(level, n): print("True") else: print("False") # This code is contributed by PranchalK // C# program to check if a given tree// is Binary Heap or notusing System; class GFG{// Returns true if given level// order traversal is Min Heap.public static bool isMinHeap(int[] level){ int n = level.Length - 1; // First non leaf node is at // index (n/2-1). Check whether // each parent is greater than child for (int i = (n / 2 - 1) ; i >= 0 ; i--) { // Left child will be at index 2*i+1 // Right child will be at index 2*i+2 if (level[i] > level[2 * i + 1]) { return false; } if (2 * i + 2 < n) { // If parent is greater than right child if (level[i] > level[2 * i + 2]) { return false; } } } return true;} // Driver codepublic static void Main(string[] args){ // Level order traversal int[] level = new int[]{10, 15, 14, 25, 30}; if (isMinHeap(level)) { Console.WriteLine("True"); } else { Console.WriteLine("False"); }}} // This code is contributed by Shrikant13 <?php// PHP program to check if a given tree// is Binary Heap or not // Returns true if given level order// traversal is Min Heap.function isMinHeap($level, $n){ // First non leaf node is at index // (n/2-1). Check whether each parent // is greater than child for ($i = ($n / 2 - 1); $i >= 0; $i--) { // Left child will be at index 2*i+1 // Right child will be at index 2*i+2 if ($level[$i] > $level[2 * $i + 1]) return false; if (2 * $i + 2 < $n) { // If parent is greater than right child if ($level[$i] > $level[2 * $i + 2]) return false; } } return true;} // Driver code$level = array(10, 15, 14, 25, 30);$n = sizeof($level);if (isMinHeap($level, $n)) echo "True";else echo "False"; // This code is contributed// by Akanksha Rai <script> // JavaScript program to check if a given tree// is Binary Heap or not // Returns true if given level// order traversal is Min Heap.function isMinHeap(level){ var n = level.length - 1; // First non leaf node is at // index (n/2-1). Check whether // each parent is greater than child for(var i = (n / 2 - 1) ; i >= 0 ; i--) { // Left child will be at index 2*i+1 // Right child will be at index 2*i+2 if (level[i] > level[2 * i + 1]) { return false; } if (2 * i + 2 < n) { // If parent is greater than right child if (level[i] > level[2 * i + 2]) { return false; } } } return true;} // Driver code// Level order traversalvar level = [10, 15, 14, 25, 30];if (isMinHeap(level)){ document.write("True");}else{ document.write("False");} </script> Output: True These algorithms run with worse case O(n) complexity Space complexity: O(1) since using constant variables This article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 Akanksha_Rai PranchalKatiyar famously polymatir3j tree-level-order Heap Tree Tree Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Priority Queue in Python Max Heap in Python Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Insertion and Deletion in Heaps Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Jul, 2022" }, { "code": null, "e": 176, "s": 52, "text": "Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-HeapExamples: " }, { "code": null, "e": 890, "s": 176, "text": "Input : level = [10, 15, 14, 25, 30]\nOutput : True\nThe tree of the given level order traversal is\n 10\n / \\\n 15 14\n / \\\n 25 30\nWe see that each parent has a value less than\nits child, and hence satisfies the min-heap \nproperty\n \nInput : level = [30, 56, 22, 49, 30, 51, 2, 67]\nOutput : False\nThe tree of the given level order traversal is\n 30\n / \\\n 56 22\n / \\ / \\\n 49 30 51 2\n /\n 67\nWe observe that at level 0, 30 > 22, and hence\nmin-heap property is not satisfied" }, { "code": null, "e": 1183, "s": 892, "text": "We need to check whether each non-leaf node (parent) satisfies the heap property. For this, we check whether each parent (at index i) is smaller than its children (at indices 2*i+1 and 2*i+2, if the parent has two children). If only one child, we only check the parent against index 2*i+1. " }, { "code": null, "e": 1187, "s": 1183, "text": "C++" }, { "code": null, "e": 1192, "s": 1187, "text": "Java" }, { "code": null, "e": 1200, "s": 1192, "text": "Python3" }, { "code": null, "e": 1203, "s": 1200, "text": "C#" }, { "code": null, "e": 1207, "s": 1203, "text": "PHP" }, { "code": null, "e": 1218, "s": 1207, "text": "Javascript" }, { "code": "// C++ program to check if a given tree is// Binary Heap or not#include <bits/stdc++.h>using namespace std; // Returns true if given level order traversal// is Min Heap.bool isMinHeap(int level[], int n){ // First non leaf node is at index (n/2-1). // Check whether each parent is greater than child for (int i=(n/2-1) ; i>=0 ; i--) { // Left child will be at index 2*i+1 // Right child will be at index 2*i+2 if (level[i] > level[2 * i + 1]) return false; if (2*i + 2 < n) { // If parent is greater than right child if (level[i] > level[2 * i + 2]) return false; } } return true;} // Driver codeint main(){ int level[] = {10, 15, 14, 25, 30}; int n = sizeof(level)/sizeof(level[0]); if (isMinHeap(level, n)) cout << \"True\"; else cout << \"False\"; return 0;}", "e": 2115, "s": 1218, "text": null }, { "code": "// Java program to check if a given tree is// Binary Heap or notimport java.io.*;import java.util.*; public class detheap{ // Returns true if given level order traversal // is Min Heap. static boolean isMinHeap(int []level) { int n = level.length - 1; // First non leaf node is at index (n/2-1). // Check whether each parent is greater than child for (int i=(n/2-1) ; i>=0 ; i--) { // Left child will be at index 2*i+1 // Right child will be at index 2*i+2 if (level[i] > level[2 * i + 1]) return false; if (2*i + 2 < n) { // If parent is greater than right child if (level[i] > level[2 * i + 2]) return false; } } return true; } // Driver code public static void main(String[] args) throws IOException { // Level order traversal int[] level = new int[]{10, 15, 14, 25, 30}; if (isMinHeap(level)) System.out.println(\"True\"); else System.out.println(\"False\"); }}", "e": 3266, "s": 2115, "text": null }, { "code": "# Python3 program to check if a given# tree is Binary Heap or not # Returns true if given level order# traversal is Min Heap.def isMinHeap(level, n): # First non leaf node is at index # (n/2-1). Check whether each parent # is greater than child for i in range(int(n / 2) - 1, -1, -1): # Left child will be at index 2*i+1 # Right child will be at index 2*i+2 if level[i] > level[2 * i + 1]: return False if 2 * i + 2 < n: # If parent is greater than right child if level[i] > level[2 * i + 2]: return False return True # Driver codeif __name__ == '__main__': level = [10, 15, 14, 25, 30] n = len(level) if isMinHeap(level, n): print(\"True\") else: print(\"False\") # This code is contributed by PranchalK", "e": 4112, "s": 3266, "text": null }, { "code": "// C# program to check if a given tree// is Binary Heap or notusing System; class GFG{// Returns true if given level// order traversal is Min Heap.public static bool isMinHeap(int[] level){ int n = level.Length - 1; // First non leaf node is at // index (n/2-1). Check whether // each parent is greater than child for (int i = (n / 2 - 1) ; i >= 0 ; i--) { // Left child will be at index 2*i+1 // Right child will be at index 2*i+2 if (level[i] > level[2 * i + 1]) { return false; } if (2 * i + 2 < n) { // If parent is greater than right child if (level[i] > level[2 * i + 2]) { return false; } } } return true;} // Driver codepublic static void Main(string[] args){ // Level order traversal int[] level = new int[]{10, 15, 14, 25, 30}; if (isMinHeap(level)) { Console.WriteLine(\"True\"); } else { Console.WriteLine(\"False\"); }}} // This code is contributed by Shrikant13", "e": 5171, "s": 4112, "text": null }, { "code": "<?php// PHP program to check if a given tree// is Binary Heap or not // Returns true if given level order// traversal is Min Heap.function isMinHeap($level, $n){ // First non leaf node is at index // (n/2-1). Check whether each parent // is greater than child for ($i = ($n / 2 - 1); $i >= 0; $i--) { // Left child will be at index 2*i+1 // Right child will be at index 2*i+2 if ($level[$i] > $level[2 * $i + 1]) return false; if (2 * $i + 2 < $n) { // If parent is greater than right child if ($level[$i] > $level[2 * $i + 2]) return false; } } return true;} // Driver code$level = array(10, 15, 14, 25, 30);$n = sizeof($level);if (isMinHeap($level, $n)) echo \"True\";else echo \"False\"; // This code is contributed// by Akanksha Rai", "e": 6022, "s": 5171, "text": null }, { "code": "<script> // JavaScript program to check if a given tree// is Binary Heap or not // Returns true if given level// order traversal is Min Heap.function isMinHeap(level){ var n = level.length - 1; // First non leaf node is at // index (n/2-1). Check whether // each parent is greater than child for(var i = (n / 2 - 1) ; i >= 0 ; i--) { // Left child will be at index 2*i+1 // Right child will be at index 2*i+2 if (level[i] > level[2 * i + 1]) { return false; } if (2 * i + 2 < n) { // If parent is greater than right child if (level[i] > level[2 * i + 2]) { return false; } } } return true;} // Driver code// Level order traversalvar level = [10, 15, 14, 25, 30];if (isMinHeap(level)){ document.write(\"True\");}else{ document.write(\"False\");} </script>", "e": 6928, "s": 6022, "text": null }, { "code": null, "e": 6938, "s": 6928, "text": "Output: " }, { "code": null, "e": 6943, "s": 6938, "text": "True" }, { "code": null, "e": 6996, "s": 6943, "text": "These algorithms run with worse case O(n) complexity" }, { "code": null, "e": 7050, "s": 6996, "text": "Space complexity: O(1) since using constant variables" }, { "code": null, "e": 7475, "s": 7050, "text": "This article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7487, "s": 7475, "text": "shrikanth13" }, { "code": null, "e": 7500, "s": 7487, "text": "Akanksha_Rai" }, { "code": null, "e": 7516, "s": 7500, "text": "PranchalKatiyar" }, { "code": null, "e": 7525, "s": 7516, "text": "famously" }, { "code": null, "e": 7537, "s": 7525, "text": "polymatir3j" }, { "code": null, "e": 7554, "s": 7537, "text": "tree-level-order" }, { "code": null, "e": 7559, "s": 7554, "text": "Heap" }, { "code": null, "e": 7564, "s": 7559, "text": "Tree" }, { "code": null, "e": 7569, "s": 7564, "text": "Tree" }, { "code": null, "e": 7574, "s": 7569, "text": "Heap" }, { "code": null, "e": 7672, "s": 7574, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7704, "s": 7672, "text": "Introduction to Data Structures" }, { "code": null, "e": 7729, "s": 7704, "text": "Priority Queue in Python" }, { "code": null, "e": 7748, "s": 7729, "text": "Max Heap in Python" }, { "code": null, "e": 7818, "s": 7748, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 7850, "s": 7818, "text": "Insertion and Deletion in Heaps" }, { "code": null, "e": 7900, "s": 7850, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 7935, "s": 7900, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 7969, "s": 7935, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 7998, "s": 7969, "text": "AVL Tree | Set 1 (Insertion)" } ]
How to process SQL statements with JDBC explain with an example?
To process an SQL statement, you need to follow the steps given below: Establish the connection. Establish the connection. Create a statement. Create a statement. Execute the statement/query. Execute the statement/query. Process the result. Process the result. Close the connection. Close the connection. To process SQL statements first of all you need to establish connection with the desired DBMS or, file System or, other data sources. To do so, Register the JDBC driver class, corresponding to the DataSource you need to the DriverManager using the registerDriver() method. To do so, Register the JDBC driver class, corresponding to the DataSource you need to the DriverManager using the registerDriver() method. Driver myDriver = new com.mysql.jdbc.Driver(); DriverManager.registerDriver(myDriver); This method accepts an object of the Driver class; it registers the specified Driver with the DriverManager. You can also register the driver using the forName() method. This method loads the specified class in to the memory and it automatically gets registered. Class.forName("com.mysql.jdbc.Driver"); After registering the Driver class, get the Connection object using the getConnection() method.This method accepts a database URL (an address that points to your database), Username and, password and, returns a connection object. After registering the Driver class, get the Connection object using the getConnection() method. This method accepts a database URL (an address that points to your database), Username and, password and, returns a connection object. String url = "jdbc:mysql://localhost/"; String user = "user_name"; String passwd = "password"; Connection conn = DriverManager.getConnection(url, user_name, password); The Statement interface represents an SQL statement and JDBC provides 3 kinds of Statements Statement: A general purpose statement which does not accept any parameters. Statement: A general purpose statement which does not accept any parameters. PreparedStatement: A precompiled SQL statement which accepts input parameters. PreparedStatement: A precompiled SQL statement which accepts input parameters. Callable Statement: This is used to call the stored procedures. Callable Statement: This is used to call the stored procedures. The Connection interface provides methods named createStatement(), prepareStatement() and, prepareCall() to create Statement, prepared statement and, CallableStatement respectively. You need to create any of these statements using the respective method. conn.createStatement(); conn.prepareStatement(query); conn.prepareCall(query); After creating the statement objects, you need to execute them. To execute the statements, the Statement interface provides three methods namely, execute(), executeUpdate() and, executeQuery(). execute(): Used to execute SQL DDL statements, it returns a boolean value specifying whether the ResultSet object can be retrieved. execute(): Used to execute SQL DDL statements, it returns a boolean value specifying whether the ResultSet object can be retrieved. executeUpdate(): Used to execute statements such as insert, update, delete. It returns an integer value representing the number of rows affected. executeUpdate(): Used to execute statements such as insert, update, delete. It returns an integer value representing the number of rows affected. executeQuery(): Used to execute statements that returns tabular data (example select). It returns an object of the class ResultSet. executeQuery(): Used to execute statements that returns tabular data (example select). It returns an object of the class ResultSet. Execute the created statement using one of these methods. stmt.execute(query); stmt.executeQuery(query); stmt.execute(query); Once you execute the statements/queries you will get the result of the respective query as a return value from execute() (boolean value) or, executeQuery() (ResultSet) or, executeUpdate() (integer value) methods. The ResultSet object holds tabular values and it has a pointer that points to the rows of the table, initially the pointer/cursor will be positioned before the first row. Once you get a ResultSet object you need to retrieve required values from it and process. You can move the pointer to the next row using the next() method. This returns a boolean value specifying whether the ResultSet contains next row. Therefore, using this method in the while loop you can iterate the contents of the result set and get the contents of the columns of that row using the getter methods of the Statement interface. while(rs.next()) { System.out.print("Brand: "+rs.getString("Mobile_Brand")+", "); System.out.print("Sale: "+rs.getString("Unit_Sale")); System.out.println(""); }
[ { "code": null, "e": 1258, "s": 1187, "text": "To process an SQL statement, you need to follow the steps given below:" }, { "code": null, "e": 1284, "s": 1258, "text": "Establish the connection." }, { "code": null, "e": 1310, "s": 1284, "text": "Establish the connection." }, { "code": null, "e": 1330, "s": 1310, "text": "Create a statement." }, { "code": null, "e": 1350, "s": 1330, "text": "Create a statement." }, { "code": null, "e": 1379, "s": 1350, "text": "Execute the statement/query." }, { "code": null, "e": 1408, "s": 1379, "text": "Execute the statement/query." }, { "code": null, "e": 1428, "s": 1408, "text": "Process the result." }, { "code": null, "e": 1448, "s": 1428, "text": "Process the result." }, { "code": null, "e": 1470, "s": 1448, "text": "Close the connection." }, { "code": null, "e": 1492, "s": 1470, "text": "Close the connection." }, { "code": null, "e": 1626, "s": 1492, "text": "To process SQL statements first of all you need to establish connection with the desired DBMS or, file System or, other data sources." }, { "code": null, "e": 1765, "s": 1626, "text": "To do so, Register the JDBC driver class, corresponding to the DataSource you need to the DriverManager using the registerDriver() method." }, { "code": null, "e": 1904, "s": 1765, "text": "To do so, Register the JDBC driver class, corresponding to the DataSource you need to the DriverManager using the registerDriver() method." }, { "code": null, "e": 1991, "s": 1904, "text": "Driver myDriver = new com.mysql.jdbc.Driver();\nDriverManager.registerDriver(myDriver);" }, { "code": null, "e": 2100, "s": 1991, "text": "This method accepts an object of the Driver class; it registers the specified Driver with the DriverManager." }, { "code": null, "e": 2254, "s": 2100, "text": "You can also register the driver using the forName() method. This method loads the specified class in to the memory and it automatically gets registered." }, { "code": null, "e": 2294, "s": 2254, "text": "Class.forName(\"com.mysql.jdbc.Driver\");" }, { "code": null, "e": 2524, "s": 2294, "text": "After registering the Driver class, get the Connection object using the getConnection() method.This method accepts a database URL (an address that points to your database), Username and, password and, returns a connection object." }, { "code": null, "e": 2620, "s": 2524, "text": "After registering the Driver class, get the Connection object using the getConnection() method." }, { "code": null, "e": 2755, "s": 2620, "text": "This method accepts a database URL (an address that points to your database), Username and, password and, returns a connection object." }, { "code": null, "e": 2923, "s": 2755, "text": "String url = \"jdbc:mysql://localhost/\";\nString user = \"user_name\";\nString passwd = \"password\";\nConnection conn = DriverManager.getConnection(url, user_name, password);" }, { "code": null, "e": 3015, "s": 2923, "text": "The Statement interface represents an SQL statement and JDBC provides 3 kinds of Statements" }, { "code": null, "e": 3092, "s": 3015, "text": "Statement: A general purpose statement which does not accept any parameters." }, { "code": null, "e": 3169, "s": 3092, "text": "Statement: A general purpose statement which does not accept any parameters." }, { "code": null, "e": 3248, "s": 3169, "text": "PreparedStatement: A precompiled SQL statement which accepts input parameters." }, { "code": null, "e": 3327, "s": 3248, "text": "PreparedStatement: A precompiled SQL statement which accepts input parameters." }, { "code": null, "e": 3391, "s": 3327, "text": "Callable Statement: This is used to call the stored procedures." }, { "code": null, "e": 3455, "s": 3391, "text": "Callable Statement: This is used to call the stored procedures." }, { "code": null, "e": 3709, "s": 3455, "text": "The Connection interface provides methods named createStatement(), prepareStatement() and, prepareCall() to create Statement, prepared statement and, CallableStatement respectively. You need to create any of these statements using the respective method." }, { "code": null, "e": 3788, "s": 3709, "text": "conn.createStatement();\nconn.prepareStatement(query);\nconn.prepareCall(query);" }, { "code": null, "e": 3982, "s": 3788, "text": "After creating the statement objects, you need to execute them. To execute the statements, the Statement interface provides three methods namely, execute(), executeUpdate() and, executeQuery()." }, { "code": null, "e": 4114, "s": 3982, "text": "execute(): Used to execute SQL DDL statements, it returns a boolean value specifying whether the ResultSet object can be retrieved." }, { "code": null, "e": 4246, "s": 4114, "text": "execute(): Used to execute SQL DDL statements, it returns a boolean value specifying whether the ResultSet object can be retrieved." }, { "code": null, "e": 4392, "s": 4246, "text": "executeUpdate(): Used to execute statements such as insert, update, delete. It returns an integer value representing the number of rows affected." }, { "code": null, "e": 4538, "s": 4392, "text": "executeUpdate(): Used to execute statements such as insert, update, delete. It returns an integer value representing the number of rows affected." }, { "code": null, "e": 4670, "s": 4538, "text": "executeQuery(): Used to execute statements that returns tabular data (example select). It returns an object of the class ResultSet." }, { "code": null, "e": 4802, "s": 4670, "text": "executeQuery(): Used to execute statements that returns tabular data (example select). It returns an object of the class ResultSet." }, { "code": null, "e": 4860, "s": 4802, "text": "Execute the created statement using one of these methods." }, { "code": null, "e": 4928, "s": 4860, "text": "stmt.execute(query);\nstmt.executeQuery(query);\nstmt.execute(query);" }, { "code": null, "e": 5141, "s": 4928, "text": "Once you execute the statements/queries you will get the result of the respective query as a return value from execute() (boolean value) or, executeQuery() (ResultSet) or, executeUpdate() (integer value) methods." }, { "code": null, "e": 5402, "s": 5141, "text": "The ResultSet object holds tabular values and it has a pointer that points to the rows of the table, initially the pointer/cursor will be positioned before the first row. Once you get a ResultSet object you need to retrieve required values from it and process." }, { "code": null, "e": 5549, "s": 5402, "text": "You can move the pointer to the next row using the next() method. This returns a boolean value specifying whether the ResultSet contains next row." }, { "code": null, "e": 5744, "s": 5549, "text": "Therefore, using this method in the while loop you can iterate the contents of the result set and get the contents of the columns of that row using the getter methods of the Statement interface." }, { "code": null, "e": 5915, "s": 5744, "text": "while(rs.next()) {\n System.out.print(\"Brand: \"+rs.getString(\"Mobile_Brand\")+\", \");\n System.out.print(\"Sale: \"+rs.getString(\"Unit_Sale\"));\n System.out.println(\"\");\n}" } ]
Image Classifier using CNN
29 Jun, 2022 The article is about creating an Image classifier for identifying cat-vs-dogs using TFLearn in Python. The problem is here hosted on kaggle. Machine Learning is now one of the hottest topics around the world. Well, it can even be said as the new electricity in today’s world. But to be precise what is Machine Learning, well it’s just one way of teaching the machine by feeding a large amount of data. To know more about Machine learning and its algorithms you can refer to some links that are provided in the Reference sections of this article. Today, we will create an Image Classifier of our own that can distinguish whether a given pic is of a dog or cat or something else depending upon your fed data. To achieve our goal, we will use one of the famous machine learning algorithms out there which are used for Image Classification i.e. Convolutional Neural Network(or CNN). So basically what is CNN – as we know it’s a machine learning algorithm for machines to understand the features of the image with foresight and remember the features to guess whether the name of the new image is fed to the machine. Since it’s not an article explaining CNN so I’ll add some links in the end if you guys are interested in how CNN works and behaves. So after going through all those links let us see how to create our very own cat-vs-dog image classifier. For the dataset we will use the Kaggle dataset of cat-vs-dog: train dataset- link test dataset- link Now after getting the data set, we need to preprocess the data a bit and provide labels to each of the images given there during training the data set. To do so we can see that name of each image of the training data set is either start with “cat” or “dog” so we will use that to our advantage then we use one hot encoder for the machine to understand the labels(cat[1, 0] or dog[0, 1]). def label_img(img): word_label = img.split('.')[-3] # DIY One hot encoder if word_label == 'cat': return [1, 0] elif word_label == 'dog': return [0, 1] Libraries Required : TFLearn – Deep learning library featuring a higher-level API for TensorFlow used to create layers of our CNN tqdm – Instantly make your loops show a smart progress meter, just for simple designing sake numpy – To process the image matrices open-cv – To process the image like converting them to grayscale and etc. os – To access the file system to read the image from the train and test directory from our machines random – To shuffle the data to overcome the biasing matplotlib – To display the result of our predictive outcome. tensorflow – Just to use the tensorboard to compare the loss and adam curve our result data or obtained log. TRAIN_DIR and TEST_DIR should be set according to the user convenience and play with the basic hyperparameters like epoch, learning rate, etc to improve the accuracy. I have converted the image to grayscale so that we will only have to deal with 2-d matrix otherwise 3-d matrix is tough to directly apply CNN to, especially not recommended for beginners. Below here is the code which is heavily commented or otherwise you can find the code here in my GitHub account from this link. Python3 # Python program to create# Image Classifier using CNN # Importing the required librariesimport cv2import osimport numpy as npfrom random import shufflefrom tqdm import tqdm '''Setting up the env''' TRAIN_DIR = 'E:/dataset / Cats_vs_Dogs / train'TEST_DIR = 'E:/dataset / Cats_vs_Dogs / test1'IMG_SIZE = 50LR = 1e-3 '''Setting up the model which will help with tensorflow models'''MODEL_NAME = 'dogsvscats-{}-{}.model'.format(LR, '6conv-basic') '''Labelling the dataset'''def label_img(img): word_label = img.split('.')[-3] # DIY One hot encoder if word_label == 'cat': return [1, 0] elif word_label == 'dog': return [0, 1] '''Creating the training data'''def create_train_data(): # Creating an empty list where we should store the training data # after a little preprocessing of the data training_data = [] # tqdm is only used for interactive loading # loading the training data for img in tqdm(os.listdir(TRAIN_DIR)): # labeling the images label = label_img(img) path = os.path.join(TRAIN_DIR, img) # loading the image from the path and then converting them into # grayscale for easier covnet prob img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) # resizing the image for processing them in the covnet img = cv2.resize(img, (IMG_SIZE, IMG_SIZE)) # final step-forming the training data list with numpy array of the images training_data.append([np.array(img), np.array(label)]) # shuffling of the training data to preserve the random state of our data shuffle(training_data) # saving our trained data for further uses if required np.save('train_data.npy', training_data) return training_data '''Processing the given test data'''# Almost same as processing the training data but# we dont have to label it.def process_test_data(): testing_data = [] for img in tqdm(os.listdir(TEST_DIR)): path = os.path.join(TEST_DIR, img) img_num = img.split('.')[0] img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (IMG_SIZE, IMG_SIZE)) testing_data.append([np.array(img), img_num]) shuffle(testing_data) np.save('test_data.npy', testing_data) return testing_data '''Running the training and the testing in the dataset for our model'''train_data = create_train_data()test_data = process_test_data() # train_data = np.load('train_data.npy')# test_data = np.load('test_data.npy')'''Creating the neural network using tensorflow'''# Importing the required librariesimport tflearnfrom tflearn.layers.conv import conv_2d, max_pool_2dfrom tflearn.layers.core import input_data, dropout, fully_connectedfrom tflearn.layers.estimator import regression import tensorflow as tftf.reset_default_graph()convnet = input_data(shape =[None, IMG_SIZE, IMG_SIZE, 1], name ='input') convnet = conv_2d(convnet, 32, 5, activation ='relu')convnet = max_pool_2d(convnet, 5) convnet = conv_2d(convnet, 64, 5, activation ='relu')convnet = max_pool_2d(convnet, 5) convnet = conv_2d(convnet, 128, 5, activation ='relu')convnet = max_pool_2d(convnet, 5) convnet = conv_2d(convnet, 64, 5, activation ='relu')convnet = max_pool_2d(convnet, 5) convnet = conv_2d(convnet, 32, 5, activation ='relu')convnet = max_pool_2d(convnet, 5) convnet = fully_connected(convnet, 1024, activation ='relu')convnet = dropout(convnet, 0.8) convnet = fully_connected(convnet, 2, activation ='softmax')convnet = regression(convnet, optimizer ='adam', learning_rate = LR, loss ='categorical_crossentropy', name ='targets') model = tflearn.DNN(convnet, tensorboard_dir ='log') # Splitting the testing data and training datatrain = train_data[:-500]test = train_data[-500:] '''Setting up the features and labels'''# X-Features & Y-Labels X = np.array([i[0] for i in train]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)Y = [i[1] for i in train]test_x = np.array([i[0] for i in test]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)test_y = [i[1] for i in test] '''Fitting the data into our model'''# epoch = 5 takenmodel.fit({'input': X}, {'targets': Y}, n_epoch = 5, validation_set =({'input': test_x}, {'targets': test_y}), snapshot_step = 500, show_metric = True, run_id = MODEL_NAME)model.save(MODEL_NAME) '''Testing the data'''import matplotlib.pyplot as plt# if you need to create the data:# test_data = process_test_data()# if you already have some saved:test_data = np.load('test_data.npy') fig = plt.figure() for num, data in enumerate(test_data[:20]): # cat: [1, 0] # dog: [0, 1] img_num = data[1] img_data = data[0] y = fig.add_subplot(4, 5, num + 1) orig = img_data data = img_data.reshape(IMG_SIZE, IMG_SIZE, 1) # model_out = model.predict([data])[0] model_out = model.predict([data])[0] if np.argmax(model_out) == 1: str_label ='Dog' else: str_label ='Cat' y.imshow(orig, cmap ='gray') plt.title(str_label) y.axes.get_xaxis().set_visible(False) y.axes.get_yaxis().set_visible(False)plt.show() The output image will not be very clear since all the image is reduced to 50X50 for a machine to process fast though the tradeoff between speed and loss. And to access the tensorboard use the following command in your cmd(Windows user). tensorboard --logdir=foo:C:\Users\knapseck\Desktop\Dev\Cov_Net\log Output: Reference Links for beginner to Machine Learning: Machine Learning GeeksforGeeks Siraj Raval – YouTube Andrew Ng Machine Learning Course on Coursera Machine Learning : A probabilistic Approach by Kevin Murphy Reddit community for Machine Learning. Reference Links for CNN : Jupyter Notebook – Conv_Net Wikipedia – Convolutional Neural Networks Stanford Course – cs231n mathemagic sagartomar9927 akshaysingh98088 Machine Learning Project Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Supervised and Unsupervised learning Decision Tree Introduction with example Search Algorithms in AI SDE SHEET - A Complete Guide for SDE Preparation Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Jun, 2022" }, { "code": null, "e": 194, "s": 52, "text": "The article is about creating an Image classifier for identifying cat-vs-dogs using TFLearn in Python. The problem is here hosted on kaggle. " }, { "code": null, "e": 599, "s": 194, "text": "Machine Learning is now one of the hottest topics around the world. Well, it can even be said as the new electricity in today’s world. But to be precise what is Machine Learning, well it’s just one way of teaching the machine by feeding a large amount of data. To know more about Machine learning and its algorithms you can refer to some links that are provided in the Reference sections of this article." }, { "code": null, "e": 1468, "s": 601, "text": "Today, we will create an Image Classifier of our own that can distinguish whether a given pic is of a dog or cat or something else depending upon your fed data. To achieve our goal, we will use one of the famous machine learning algorithms out there which are used for Image Classification i.e. Convolutional Neural Network(or CNN). So basically what is CNN – as we know it’s a machine learning algorithm for machines to understand the features of the image with foresight and remember the features to guess whether the name of the new image is fed to the machine. Since it’s not an article explaining CNN so I’ll add some links in the end if you guys are interested in how CNN works and behaves. So after going through all those links let us see how to create our very own cat-vs-dog image classifier. For the dataset we will use the Kaggle dataset of cat-vs-dog: " }, { "code": null, "e": 1488, "s": 1468, "text": "train dataset- link" }, { "code": null, "e": 1507, "s": 1488, "text": "test dataset- link" }, { "code": null, "e": 1895, "s": 1507, "text": "Now after getting the data set, we need to preprocess the data a bit and provide labels to each of the images given there during training the data set. To do so we can see that name of each image of the training data set is either start with “cat” or “dog” so we will use that to our advantage then we use one hot encoder for the machine to understand the labels(cat[1, 0] or dog[0, 1])." }, { "code": null, "e": 2064, "s": 1895, "text": "def label_img(img):\n word_label = img.split('.')[-3]\n \n # DIY One hot encoder\n if word_label == 'cat': return [1, 0]\n elif word_label == 'dog': return [0, 1]" }, { "code": null, "e": 2085, "s": 2064, "text": "Libraries Required :" }, { "code": null, "e": 2194, "s": 2085, "text": "TFLearn – Deep learning library featuring a higher-level API for TensorFlow used to create layers of our CNN" }, { "code": null, "e": 2287, "s": 2194, "text": "tqdm – Instantly make your loops show a smart progress meter, just for simple designing sake" }, { "code": null, "e": 2325, "s": 2287, "text": "numpy – To process the image matrices" }, { "code": null, "e": 2399, "s": 2325, "text": "open-cv – To process the image like converting them to grayscale and etc." }, { "code": null, "e": 2500, "s": 2399, "text": "os – To access the file system to read the image from the train and test directory from our machines" }, { "code": null, "e": 2553, "s": 2500, "text": "random – To shuffle the data to overcome the biasing" }, { "code": null, "e": 2615, "s": 2553, "text": "matplotlib – To display the result of our predictive outcome." }, { "code": null, "e": 2724, "s": 2615, "text": "tensorflow – Just to use the tensorboard to compare the loss and adam curve our result data or obtained log." }, { "code": null, "e": 3206, "s": 2724, "text": "TRAIN_DIR and TEST_DIR should be set according to the user convenience and play with the basic hyperparameters like epoch, learning rate, etc to improve the accuracy. I have converted the image to grayscale so that we will only have to deal with 2-d matrix otherwise 3-d matrix is tough to directly apply CNN to, especially not recommended for beginners. Below here is the code which is heavily commented or otherwise you can find the code here in my GitHub account from this link." }, { "code": null, "e": 3214, "s": 3206, "text": "Python3" }, { "code": "# Python program to create# Image Classifier using CNN # Importing the required librariesimport cv2import osimport numpy as npfrom random import shufflefrom tqdm import tqdm '''Setting up the env''' TRAIN_DIR = 'E:/dataset / Cats_vs_Dogs / train'TEST_DIR = 'E:/dataset / Cats_vs_Dogs / test1'IMG_SIZE = 50LR = 1e-3 '''Setting up the model which will help with tensorflow models'''MODEL_NAME = 'dogsvscats-{}-{}.model'.format(LR, '6conv-basic') '''Labelling the dataset'''def label_img(img): word_label = img.split('.')[-3] # DIY One hot encoder if word_label == 'cat': return [1, 0] elif word_label == 'dog': return [0, 1] '''Creating the training data'''def create_train_data(): # Creating an empty list where we should store the training data # after a little preprocessing of the data training_data = [] # tqdm is only used for interactive loading # loading the training data for img in tqdm(os.listdir(TRAIN_DIR)): # labeling the images label = label_img(img) path = os.path.join(TRAIN_DIR, img) # loading the image from the path and then converting them into # grayscale for easier covnet prob img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) # resizing the image for processing them in the covnet img = cv2.resize(img, (IMG_SIZE, IMG_SIZE)) # final step-forming the training data list with numpy array of the images training_data.append([np.array(img), np.array(label)]) # shuffling of the training data to preserve the random state of our data shuffle(training_data) # saving our trained data for further uses if required np.save('train_data.npy', training_data) return training_data '''Processing the given test data'''# Almost same as processing the training data but# we dont have to label it.def process_test_data(): testing_data = [] for img in tqdm(os.listdir(TEST_DIR)): path = os.path.join(TEST_DIR, img) img_num = img.split('.')[0] img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (IMG_SIZE, IMG_SIZE)) testing_data.append([np.array(img), img_num]) shuffle(testing_data) np.save('test_data.npy', testing_data) return testing_data '''Running the training and the testing in the dataset for our model'''train_data = create_train_data()test_data = process_test_data() # train_data = np.load('train_data.npy')# test_data = np.load('test_data.npy')'''Creating the neural network using tensorflow'''# Importing the required librariesimport tflearnfrom tflearn.layers.conv import conv_2d, max_pool_2dfrom tflearn.layers.core import input_data, dropout, fully_connectedfrom tflearn.layers.estimator import regression import tensorflow as tftf.reset_default_graph()convnet = input_data(shape =[None, IMG_SIZE, IMG_SIZE, 1], name ='input') convnet = conv_2d(convnet, 32, 5, activation ='relu')convnet = max_pool_2d(convnet, 5) convnet = conv_2d(convnet, 64, 5, activation ='relu')convnet = max_pool_2d(convnet, 5) convnet = conv_2d(convnet, 128, 5, activation ='relu')convnet = max_pool_2d(convnet, 5) convnet = conv_2d(convnet, 64, 5, activation ='relu')convnet = max_pool_2d(convnet, 5) convnet = conv_2d(convnet, 32, 5, activation ='relu')convnet = max_pool_2d(convnet, 5) convnet = fully_connected(convnet, 1024, activation ='relu')convnet = dropout(convnet, 0.8) convnet = fully_connected(convnet, 2, activation ='softmax')convnet = regression(convnet, optimizer ='adam', learning_rate = LR, loss ='categorical_crossentropy', name ='targets') model = tflearn.DNN(convnet, tensorboard_dir ='log') # Splitting the testing data and training datatrain = train_data[:-500]test = train_data[-500:] '''Setting up the features and labels'''# X-Features & Y-Labels X = np.array([i[0] for i in train]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)Y = [i[1] for i in train]test_x = np.array([i[0] for i in test]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)test_y = [i[1] for i in test] '''Fitting the data into our model'''# epoch = 5 takenmodel.fit({'input': X}, {'targets': Y}, n_epoch = 5, validation_set =({'input': test_x}, {'targets': test_y}), snapshot_step = 500, show_metric = True, run_id = MODEL_NAME)model.save(MODEL_NAME) '''Testing the data'''import matplotlib.pyplot as plt# if you need to create the data:# test_data = process_test_data()# if you already have some saved:test_data = np.load('test_data.npy') fig = plt.figure() for num, data in enumerate(test_data[:20]): # cat: [1, 0] # dog: [0, 1] img_num = data[1] img_data = data[0] y = fig.add_subplot(4, 5, num + 1) orig = img_data data = img_data.reshape(IMG_SIZE, IMG_SIZE, 1) # model_out = model.predict([data])[0] model_out = model.predict([data])[0] if np.argmax(model_out) == 1: str_label ='Dog' else: str_label ='Cat' y.imshow(orig, cmap ='gray') plt.title(str_label) y.axes.get_xaxis().set_visible(False) y.axes.get_yaxis().set_visible(False)plt.show()", "e": 8246, "s": 3214, "text": null }, { "code": null, "e": 8483, "s": 8246, "text": "The output image will not be very clear since all the image is reduced to 50X50 for a machine to process fast though the tradeoff between speed and loss. And to access the tensorboard use the following command in your cmd(Windows user)." }, { "code": null, "e": 8550, "s": 8483, "text": "tensorboard --logdir=foo:C:\\Users\\knapseck\\Desktop\\Dev\\Cov_Net\\log" }, { "code": null, "e": 8558, "s": 8550, "text": "Output:" }, { "code": null, "e": 8608, "s": 8558, "text": "Reference Links for beginner to Machine Learning:" }, { "code": null, "e": 8639, "s": 8608, "text": "Machine Learning GeeksforGeeks" }, { "code": null, "e": 8661, "s": 8639, "text": "Siraj Raval – YouTube" }, { "code": null, "e": 8707, "s": 8661, "text": "Andrew Ng Machine Learning Course on Coursera" }, { "code": null, "e": 8767, "s": 8707, "text": "Machine Learning : A probabilistic Approach by Kevin Murphy" }, { "code": null, "e": 8806, "s": 8767, "text": "Reddit community for Machine Learning." }, { "code": null, "e": 8833, "s": 8806, "text": "Reference Links for CNN : " }, { "code": null, "e": 8861, "s": 8833, "text": "Jupyter Notebook – Conv_Net" }, { "code": null, "e": 8903, "s": 8861, "text": "Wikipedia – Convolutional Neural Networks" }, { "code": null, "e": 8928, "s": 8903, "text": "Stanford Course – cs231n" }, { "code": null, "e": 8939, "s": 8928, "text": "mathemagic" }, { "code": null, "e": 8954, "s": 8939, "text": "sagartomar9927" }, { "code": null, "e": 8971, "s": 8954, "text": "akshaysingh98088" }, { "code": null, "e": 8988, "s": 8971, "text": "Machine Learning" }, { "code": null, "e": 8996, "s": 8988, "text": "Project" }, { "code": null, "e": 9003, "s": 8996, "text": "Python" }, { "code": null, "e": 9020, "s": 9003, "text": "Machine Learning" }, { "code": null, "e": 9118, "s": 9020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9141, "s": 9118, "text": "ML | Linear Regression" }, { "code": null, "e": 9164, "s": 9141, "text": "Reinforcement learning" }, { "code": null, "e": 9201, "s": 9164, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 9241, "s": 9201, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 9265, "s": 9241, "text": "Search Algorithms in AI" }, { "code": null, "e": 9314, "s": 9265, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 9369, "s": 9314, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 9402, "s": 9369, "text": "Working with zip files in Python" }, { "code": null, "e": 9424, "s": 9402, "text": "XML parsing in Python" } ]
Reorder the column of dataframe in R using Dplyr
02 Sep, 2021 In this article, we will discuss how to rearrange or reorder the column of the dataframe using dplyr package in R Programming Language. Creating Dataframe for demonstration: R # load the packagelibrary(dplyr) # create the dataframe with three columns# id , department and salary with 8 rowsdata = data.frame(id = c(7058, 7059, 7060, 7089, 7072, 7078, 7093, 7034), department = c('IT','sales','finance', 'IT','finance','sales', 'HR','HR'), salary = c(34500.00, 560890.78, 67000.78, 25000.00, 78900.00, 25000.00, 45000.00, 90000)) # display dataframedata Output: We are going to use a select() method to reorder columns. Syntax: select(dataframe,columns) where dataframe is the input dataframe columns are the input columns to be reordered Here we are rearranging the dataframe(id,department,salary) to (salary,id,department) R print("Before: ")data print("After: ") # reorder the columns using selectselect(data, salary, id, department) Output: Here, we will rearrange the columns using the index/position of the column. So we will use select method to do this. Note: index/position of the column starts with 1 Syntax: select(dataframe.index_positions) Where, dataframe is the input dataframe index_positions are column positions to be rearranged Here we are rearranging to different positions. R # display actual dataframeprint("actual dataframe")print(data) print("reorder the column with position") # reorder the columns with column positions# using selectprint(select(data,3,1,2)) Output: Here we are using order() function along with select() function to rearrange the columns in alphabetical order. So we will order the columns using colnames function. Syntax: dataframe %>% select(order(colnames(dataframe))) where, dataframe is the input dataframe %>% is the pipe operator to pass the result to the dataframe order() is used to rearrange the dataframe columns in alphabetical order colnames() is the function to get the columns in the dataframe Here we are rearranging the data based on column names in alphabetical order. R print("Actual dataframe") # display actual dataframeprint(data) print("Reorder dataframe") # rearrange the columns in alphabetic # orderdata %>% select(order(colnames(data))) Output: so we will order the columns using colnames function in reverse. Syntax: dataframe %>% select(order(colnames(dataframe),decreasing=TRUE)) where, dataframe is the input dataframe %>% is the pipe operator to pass the result to the dataframe order() is used to rearrange the dataframe columns in alphabetical order colnames() is the function to get the columns in the dataframe decreasing=TRUE parameter specifies to sort the dataframe in descending order Here we are rearranging the data based on column names in alphabetical order in reverse. R print("Actual dataframe") # display actual dataframeprint(data) print("Reorder dataframe") # rearrange the columns in reverse alphabetic orderdata %>% select(order(colnames(data), decreasing = TRUE)) Output: We are going to use everything() method to shift the column to first, so in this way, we can rearrange the dataframe. Syntax: dataframe %>% select(column_name, everything()) where, dataframe is the input dataframe column_name is the column to be shifted first R program to shift the department column as first R print("Actual dataframe") # display actual dataframeprint(data) print("Reorder dataframe") # getting department column as firstdata %>% select(department, everything()) Output: Here we are going to rearrange the rows based on a particular column in ascending order using arrange() function Syntax: dataframe %>% arrange(column_name) Where dataframe is the input dataframe column_name is the column in which dataframe rows are arranged based on this column R program to rearrange rows based on department column R print("Actual dataframe") # display actual dataframeprint(data) print("Reorder dataframe") # arrange the rows based on department columndata %>% arrange(department) Output: Here we are going to rearrange the rows based on a particular column in ascending order using arrange() function along with desc() function. Syntax: dataframe %>% arrange(desc(column_name)) Where dataframe is the input dataframe column_name is the column in which dataframe rows are arranged based on this column in descending order R print("Actual dataframe") # display actual dataframeprint(data) print("Reorder dataframe") # arrange the rows based on salary# column in descending orderdata %>% arrange(desc(salary)) Output: Here we are going to arrange/ reorder the rows based on multiple variables in the dataframe, so we are using arrange_all() function Syntax: arrange_all(dataframe) R print("Actual dataframe") # display actual dataframedata print("Reorder dataframe") # rearrange multiple columnsarrange_all(data) Output: Picked R Dplyr R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2021" }, { "code": null, "e": 164, "s": 28, "text": "In this article, we will discuss how to rearrange or reorder the column of the dataframe using dplyr package in R Programming Language." }, { "code": null, "e": 202, "s": 164, "text": "Creating Dataframe for demonstration:" }, { "code": null, "e": 204, "s": 202, "text": "R" }, { "code": "# load the packagelibrary(dplyr) # create the dataframe with three columns# id , department and salary with 8 rowsdata = data.frame(id = c(7058, 7059, 7060, 7089, 7072, 7078, 7093, 7034), department = c('IT','sales','finance', 'IT','finance','sales', 'HR','HR'), salary = c(34500.00, 560890.78, 67000.78, 25000.00, 78900.00, 25000.00, 45000.00, 90000)) # display dataframedata", "e": 802, "s": 204, "text": null }, { "code": null, "e": 810, "s": 802, "text": "Output:" }, { "code": null, "e": 868, "s": 810, "text": "We are going to use a select() method to reorder columns." }, { "code": null, "e": 902, "s": 868, "text": "Syntax: select(dataframe,columns)" }, { "code": null, "e": 908, "s": 902, "text": "where" }, { "code": null, "e": 941, "s": 908, "text": "dataframe is the input dataframe" }, { "code": null, "e": 987, "s": 941, "text": "columns are the input columns to be reordered" }, { "code": null, "e": 1073, "s": 987, "text": "Here we are rearranging the dataframe(id,department,salary) to (salary,id,department)" }, { "code": null, "e": 1075, "s": 1073, "text": "R" }, { "code": "print(\"Before: \")data print(\"After: \") # reorder the columns using selectselect(data, salary, id, department)", "e": 1187, "s": 1075, "text": null }, { "code": null, "e": 1195, "s": 1187, "text": "Output:" }, { "code": null, "e": 1312, "s": 1195, "text": "Here, we will rearrange the columns using the index/position of the column. So we will use select method to do this." }, { "code": null, "e": 1362, "s": 1312, "text": "Note: index/position of the column starts with 1" }, { "code": null, "e": 1404, "s": 1362, "text": "Syntax: select(dataframe.index_positions)" }, { "code": null, "e": 1411, "s": 1404, "text": "Where," }, { "code": null, "e": 1444, "s": 1411, "text": "dataframe is the input dataframe" }, { "code": null, "e": 1498, "s": 1444, "text": "index_positions are column positions to be rearranged" }, { "code": null, "e": 1546, "s": 1498, "text": "Here we are rearranging to different positions." }, { "code": null, "e": 1548, "s": 1546, "text": "R" }, { "code": "# display actual dataframeprint(\"actual dataframe\")print(data) print(\"reorder the column with position\") # reorder the columns with column positions# using selectprint(select(data,3,1,2))", "e": 1740, "s": 1548, "text": null }, { "code": null, "e": 1748, "s": 1740, "text": "Output:" }, { "code": null, "e": 1914, "s": 1748, "text": "Here we are using order() function along with select() function to rearrange the columns in alphabetical order. So we will order the columns using colnames function." }, { "code": null, "e": 1971, "s": 1914, "text": "Syntax: dataframe %>% select(order(colnames(dataframe)))" }, { "code": null, "e": 1978, "s": 1971, "text": "where," }, { "code": null, "e": 2011, "s": 1978, "text": "dataframe is the input dataframe" }, { "code": null, "e": 2072, "s": 2011, "text": "%>% is the pipe operator to pass the result to the dataframe" }, { "code": null, "e": 2145, "s": 2072, "text": "order() is used to rearrange the dataframe columns in alphabetical order" }, { "code": null, "e": 2208, "s": 2145, "text": "colnames() is the function to get the columns in the dataframe" }, { "code": null, "e": 2286, "s": 2208, "text": "Here we are rearranging the data based on column names in alphabetical order." }, { "code": null, "e": 2288, "s": 2286, "text": "R" }, { "code": "print(\"Actual dataframe\") # display actual dataframeprint(data) print(\"Reorder dataframe\") # rearrange the columns in alphabetic # orderdata %>% select(order(colnames(data)))", "e": 2467, "s": 2288, "text": null }, { "code": null, "e": 2475, "s": 2467, "text": "Output:" }, { "code": null, "e": 2540, "s": 2475, "text": "so we will order the columns using colnames function in reverse." }, { "code": null, "e": 2613, "s": 2540, "text": "Syntax: dataframe %>% select(order(colnames(dataframe),decreasing=TRUE))" }, { "code": null, "e": 2620, "s": 2613, "text": "where," }, { "code": null, "e": 2653, "s": 2620, "text": "dataframe is the input dataframe" }, { "code": null, "e": 2714, "s": 2653, "text": "%>% is the pipe operator to pass the result to the dataframe" }, { "code": null, "e": 2787, "s": 2714, "text": "order() is used to rearrange the dataframe columns in alphabetical order" }, { "code": null, "e": 2850, "s": 2787, "text": "colnames() is the function to get the columns in the dataframe" }, { "code": null, "e": 2928, "s": 2850, "text": "decreasing=TRUE parameter specifies to sort the dataframe in descending order" }, { "code": null, "e": 3017, "s": 2928, "text": "Here we are rearranging the data based on column names in alphabetical order in reverse." }, { "code": null, "e": 3019, "s": 3017, "text": "R" }, { "code": "print(\"Actual dataframe\") # display actual dataframeprint(data) print(\"Reorder dataframe\") # rearrange the columns in reverse alphabetic orderdata %>% select(order(colnames(data), decreasing = TRUE))", "e": 3244, "s": 3019, "text": null }, { "code": null, "e": 3252, "s": 3244, "text": "Output:" }, { "code": null, "e": 3370, "s": 3252, "text": "We are going to use everything() method to shift the column to first, so in this way, we can rearrange the dataframe." }, { "code": null, "e": 3426, "s": 3370, "text": "Syntax: dataframe %>% select(column_name, everything())" }, { "code": null, "e": 3433, "s": 3426, "text": "where," }, { "code": null, "e": 3466, "s": 3433, "text": "dataframe is the input dataframe" }, { "code": null, "e": 3512, "s": 3466, "text": "column_name is the column to be shifted first" }, { "code": null, "e": 3562, "s": 3512, "text": "R program to shift the department column as first" }, { "code": null, "e": 3564, "s": 3562, "text": "R" }, { "code": "print(\"Actual dataframe\") # display actual dataframeprint(data) print(\"Reorder dataframe\") # getting department column as firstdata %>% select(department, everything())", "e": 3737, "s": 3564, "text": null }, { "code": null, "e": 3745, "s": 3737, "text": "Output:" }, { "code": null, "e": 3858, "s": 3745, "text": "Here we are going to rearrange the rows based on a particular column in ascending order using arrange() function" }, { "code": null, "e": 3901, "s": 3858, "text": "Syntax: dataframe %>% arrange(column_name)" }, { "code": null, "e": 3907, "s": 3901, "text": "Where" }, { "code": null, "e": 3940, "s": 3907, "text": "dataframe is the input dataframe" }, { "code": null, "e": 4024, "s": 3940, "text": "column_name is the column in which dataframe rows are arranged based on this column" }, { "code": null, "e": 4079, "s": 4024, "text": "R program to rearrange rows based on department column" }, { "code": null, "e": 4081, "s": 4079, "text": "R" }, { "code": "print(\"Actual dataframe\") # display actual dataframeprint(data) print(\"Reorder dataframe\") # arrange the rows based on department columndata %>% arrange(department)", "e": 4250, "s": 4081, "text": null }, { "code": null, "e": 4258, "s": 4250, "text": "Output:" }, { "code": null, "e": 4399, "s": 4258, "text": "Here we are going to rearrange the rows based on a particular column in ascending order using arrange() function along with desc() function." }, { "code": null, "e": 4448, "s": 4399, "text": "Syntax: dataframe %>% arrange(desc(column_name))" }, { "code": null, "e": 4454, "s": 4448, "text": "Where" }, { "code": null, "e": 4487, "s": 4454, "text": "dataframe is the input dataframe" }, { "code": null, "e": 4591, "s": 4487, "text": "column_name is the column in which dataframe rows are arranged based on this column in descending order" }, { "code": null, "e": 4593, "s": 4591, "text": "R" }, { "code": "print(\"Actual dataframe\") # display actual dataframeprint(data) print(\"Reorder dataframe\") # arrange the rows based on salary# column in descending orderdata %>% arrange(desc(salary))", "e": 4781, "s": 4593, "text": null }, { "code": null, "e": 4789, "s": 4781, "text": "Output:" }, { "code": null, "e": 4921, "s": 4789, "text": "Here we are going to arrange/ reorder the rows based on multiple variables in the dataframe, so we are using arrange_all() function" }, { "code": null, "e": 4952, "s": 4921, "text": "Syntax: arrange_all(dataframe)" }, { "code": null, "e": 4954, "s": 4952, "text": "R" }, { "code": "print(\"Actual dataframe\") # display actual dataframedata print(\"Reorder dataframe\") # rearrange multiple columnsarrange_all(data)", "e": 5088, "s": 4954, "text": null }, { "code": null, "e": 5096, "s": 5088, "text": "Output:" }, { "code": null, "e": 5103, "s": 5096, "text": "Picked" }, { "code": null, "e": 5111, "s": 5103, "text": "R Dplyr" }, { "code": null, "e": 5122, "s": 5111, "text": "R Language" }, { "code": null, "e": 5220, "s": 5122, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5272, "s": 5220, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 5330, "s": 5272, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 5365, "s": 5330, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 5403, "s": 5365, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 5452, "s": 5403, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 5469, "s": 5452, "text": "R - if statement" }, { "code": null, "e": 5506, "s": 5469, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 5549, "s": 5506, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 5586, "s": 5549, "text": "How to import an Excel File into R ?" } ]
Java Program to Form coils in a matrix
13 Jun, 2022 Given a positive integer n which represents the dimensions of a 4n x 4n matrix with values from 1 to n filled from left to right and top to bottom. Form two coils from the matrix and print the coils. Examples: Input : n = 1; Output : Coil 1 : 10 6 2 3 4 8 12 16 Coil 2 : 7 11 15 14 13 9 5 1 Explanation : Matrix is 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Input : n = 2; Output : Coil 1 : 36 28 20 21 22 30 38 46 54 53 52 51 50 42 34 26 18 10 2 3 4 5 6 7 8 16 24 32 40 48 56 64 Coil 2 : 29 37 45 44 43 35 27 19 11 12 13 14 15 23 31 39 47 55 63 62 61 60 59 58 57 49 41 33 25 17 9 1 The total elements in the matrix are 16n2. All elements are divided into two coils. Every coil has 8n2 elements. We make two arrays of this size. We first fill elements in coil1 by traversing them in the given order. Once we have filled elements in coil1, we can get elements of other coil2 using formula coil2[i] = 16*n*n + 1 -coil1[i]. Java // Java program to print 2 coils// of a 4n x 4n matrix. class GFG { // Print coils in a matrix of size 4n x 4n static void printCoils(int n) { // Number of elements in each coil int m = 8 * n * n; // Let us fill elements in coil 1. int coil1[] = new int[m]; // First element of coil1 // 4*n*2*n + 2*n; coil1[0] = 8 * n * n + 2 * n; int curr = coil1[0]; int nflg = 1, step = 2; // Fill remaining m-1 elements in coil1[] int index = 1; while (index < m) { // Fill elements of current step from // down to up for (int i = 0; i < step; i++) { // Next element from current element curr = coil1[index++] = (curr - 4 * n * nflg); if (index >= m) break; } if (index >= m) break; // Fill elements of current step from // up to down. for (int i = 0; i < step; i++) { curr = coil1[index++] = curr + nflg; if (index >= m) break; } nflg = nflg * (-1); step += 2; } /* get coil2 from coil1 */ int coil2[] = new int[m]; for (int i = 0; i < 8 * n * n; i++) coil2[i] = 16 * n * n + 1 - coil1[i]; // Print both coils System.out.print("Coil 1 : "); for (int i = 0; i < 8 * n * n; i++) System.out.print(coil1[i] + " "); System.out.print("Coil 2 : "); for (int i = 0; i < 8 * n * n; i++) System.out.print(coil2[i] + " "); } // Driver code public static void main(String[] args) { int n = 1; printCoils(n); }} // This code is contributed by Anant Agarwal. Output: Coil 1 : 10 6 2 3 4 8 12 16 Coil 2 : 7 11 15 14 13 9 5 1 Time Complexity: O(n2), where n represents the given integer.Auxiliary Space: O(n2), where n represents the given integer. Please refer complete article on Form coils in a matrix for more details! tamanna17122007 Yahoo Java Java Programs Matrix Yahoo Matrix Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jun, 2022" }, { "code": null, "e": 228, "s": 28, "text": "Given a positive integer n which represents the dimensions of a 4n x 4n matrix with values from 1 to n filled from left to right and top to bottom. Form two coils from the matrix and print the coils." }, { "code": null, "e": 240, "s": 228, "text": "Examples: " }, { "code": null, "e": 753, "s": 240, "text": "Input : n = 1;\nOutput : Coil 1 : 10 6 2 3 4 8 12 16 \n Coil 2 : 7 11 15 14 13 9 5 1\nExplanation : Matrix is \n1 2 3 4 \n5 6 7 8 \n9 10 11 12 \n13 14 15 16\n\nInput : n = 2;\nOutput : Coil 1 : 36 28 20 21 22 30 38 46 54 \n 53 52 51 50 42 34 26 18 10 \n 2 3 4 5 6 7 8 16 24 32 40 \n 48 56 64 \n Coil 2 : 29 37 45 44 43 35 27 19 11 12 \n 13 14 15 23 31 39 47 55 63 62 \n 61 60 59 58 57 49 41 33 25 17\n 9 1 " }, { "code": null, "e": 1092, "s": 753, "text": "The total elements in the matrix are 16n2. All elements are divided into two coils. Every coil has 8n2 elements. We make two arrays of this size. We first fill elements in coil1 by traversing them in the given order. Once we have filled elements in coil1, we can get elements of other coil2 using formula coil2[i] = 16*n*n + 1 -coil1[i]. " }, { "code": null, "e": 1097, "s": 1092, "text": "Java" }, { "code": "// Java program to print 2 coils// of a 4n x 4n matrix. class GFG { // Print coils in a matrix of size 4n x 4n static void printCoils(int n) { // Number of elements in each coil int m = 8 * n * n; // Let us fill elements in coil 1. int coil1[] = new int[m]; // First element of coil1 // 4*n*2*n + 2*n; coil1[0] = 8 * n * n + 2 * n; int curr = coil1[0]; int nflg = 1, step = 2; // Fill remaining m-1 elements in coil1[] int index = 1; while (index < m) { // Fill elements of current step from // down to up for (int i = 0; i < step; i++) { // Next element from current element curr = coil1[index++] = (curr - 4 * n * nflg); if (index >= m) break; } if (index >= m) break; // Fill elements of current step from // up to down. for (int i = 0; i < step; i++) { curr = coil1[index++] = curr + nflg; if (index >= m) break; } nflg = nflg * (-1); step += 2; } /* get coil2 from coil1 */ int coil2[] = new int[m]; for (int i = 0; i < 8 * n * n; i++) coil2[i] = 16 * n * n + 1 - coil1[i]; // Print both coils System.out.print(\"Coil 1 : \"); for (int i = 0; i < 8 * n * n; i++) System.out.print(coil1[i] + \" \"); System.out.print(\"Coil 2 : \"); for (int i = 0; i < 8 * n * n; i++) System.out.print(coil2[i] + \" \"); } // Driver code public static void main(String[] args) { int n = 1; printCoils(n); }} // This code is contributed by Anant Agarwal.", "e": 3032, "s": 1097, "text": null }, { "code": null, "e": 3042, "s": 3032, "text": "Output: " }, { "code": null, "e": 3101, "s": 3042, "text": "Coil 1 : 10 6 2 3 4 8 12 16 \nCoil 2 : 7 11 15 14 13 9 5 1 " }, { "code": null, "e": 3224, "s": 3101, "text": "Time Complexity: O(n2), where n represents the given integer.Auxiliary Space: O(n2), where n represents the given integer." }, { "code": null, "e": 3298, "s": 3224, "text": "Please refer complete article on Form coils in a matrix for more details!" }, { "code": null, "e": 3314, "s": 3298, "text": "tamanna17122007" }, { "code": null, "e": 3320, "s": 3314, "text": "Yahoo" }, { "code": null, "e": 3325, "s": 3320, "text": "Java" }, { "code": null, "e": 3339, "s": 3325, "text": "Java Programs" }, { "code": null, "e": 3346, "s": 3339, "text": "Matrix" }, { "code": null, "e": 3352, "s": 3346, "text": "Yahoo" }, { "code": null, "e": 3359, "s": 3352, "text": "Matrix" }, { "code": null, "e": 3364, "s": 3359, "text": "Java" } ]
Find all the combinations of the array values in JavaScript
30 Jan, 2020 The task is to get the cartesian product of the arrays(Finding the all combination after concatenating them). Here, 2 approaches are discussed with the help of JavaScript. Approach 1: Get the all arrays in an array. Recursion is used to solve the problem. The base condition is, When the length of the array reduces to zero then return the string build till now. Else Reduce the first array element by .reduce() method and return the result returned from the recursion result(Recursion is called every time after leaving the first item of the array) plus the previous value in concatenation with every array element. Return the final ans array, which contains the all combinations. Example 1: This example implements the above approach. <!DOCTYPE html><html> <head> <title> All combinations of a JavaScript array values. </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP"> </p> <button id="button" onclick="GFG_Fun();"> click here </button> <p id="GFG_DOWN"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = [ ['m', 'n'], ['c'], ['d', 'e', 'f'] ]; up.innerHTML = "CLick on the button to get the "+ "all combinations of arrays.<br>Array - "+ "[[" + arr[0] + "], [" + arr[1] + "], [" + arr[2] + "]]"; function getCombn(arr, pre) { pre = pre || ''; if (!arr.length) { return pre; } var ans = arr[0].reduce(function(ans, value) { return ans.concat(getCombn(arr.slice(1), pre + value)); }, []); return ans; } function GFG_Fun() { down.innerHTML = getCombn(arr); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Get the all arrays in an array. Recursion is used to solve the problem. The base condition is, When the length of the array reduces to one then return that element of the array. Else Call recursion after leaving the first element of the array and store the result in variable(otherCases). Loop through every element of the Array(otherCases) and inside every element loop through the first element of the Array(arr). Concatenate every element of the Array(arr[0]) with the Array(otherCases) and push the result in answer array. Example 2: This example implements the above approach. <!DOCTYPE html><html> <head> <title> all combinations of a JavaScript array values. </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP"> </p> <button id="button" onclick="GFG_Fun();"> click here </button> <p id="GFG_DOWN"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = [ ['m', 'n'], ['c'], ['d', 'e', 'f'] ]; up.innerHTML = "CLick on the button to get the all "+ "combinations of arrays.<br>Array -"+ "[[" + arr[0] + "], [" + arr[1] + "], [" + arr[2] + "]]"; function getCombn(arr) { if (arr.length == 1) { return arr[0]; } else { var ans = []; // recur with the rest of the array. var otherCases = getCombn(arr.slice(1)); for (var i = 0; i < otherCases.length; i++) { for (var j = 0; j < arr[0].length; j++) { ans.push(arr[0][j] + otherCases[i]); } } return ans; } } function GFG_Fun() { down.innerHTML = getCombn(arr); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: javascript-array JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2020" }, { "code": null, "e": 200, "s": 28, "text": "The task is to get the cartesian product of the arrays(Finding the all combination after concatenating them). Here, 2 approaches are discussed with the help of JavaScript." }, { "code": null, "e": 212, "s": 200, "text": "Approach 1:" }, { "code": null, "e": 244, "s": 212, "text": "Get the all arrays in an array." }, { "code": null, "e": 396, "s": 244, "text": "Recursion is used to solve the problem. The base condition is, When the length of the array reduces to zero then return the string build till now. Else" }, { "code": null, "e": 645, "s": 396, "text": "Reduce the first array element by .reduce() method and return the result returned from the recursion result(Recursion is called every time after leaving the first item of the array) plus the previous value in concatenation with every array element." }, { "code": null, "e": 710, "s": 645, "text": "Return the final ans array, which contains the all combinations." }, { "code": null, "e": 765, "s": 710, "text": "Example 1: This example implements the above approach." }, { "code": "<!DOCTYPE html><html> <head> <title> All combinations of a JavaScript array values. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\"> </p> <button id=\"button\" onclick=\"GFG_Fun();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = [ ['m', 'n'], ['c'], ['d', 'e', 'f'] ]; up.innerHTML = \"CLick on the button to get the \"+ \"all combinations of arrays.<br>Array - \"+ \"[[\" + arr[0] + \"], [\" + arr[1] + \"], [\" + arr[2] + \"]]\"; function getCombn(arr, pre) { pre = pre || ''; if (!arr.length) { return pre; } var ans = arr[0].reduce(function(ans, value) { return ans.concat(getCombn(arr.slice(1), pre + value)); }, []); return ans; } function GFG_Fun() { down.innerHTML = getCombn(arr); } </script></body> </html>", "e": 1938, "s": 765, "text": null }, { "code": null, "e": 1946, "s": 1938, "text": "Output:" }, { "code": null, "e": 1977, "s": 1946, "text": "Before clicking on the button:" }, { "code": null, "e": 2007, "s": 1977, "text": "After clicking on the button:" }, { "code": null, "e": 2019, "s": 2007, "text": "Approach 2:" }, { "code": null, "e": 2051, "s": 2019, "text": "Get the all arrays in an array." }, { "code": null, "e": 2202, "s": 2051, "text": "Recursion is used to solve the problem. The base condition is, When the length of the array reduces to one then return that element of the array. Else" }, { "code": null, "e": 2308, "s": 2202, "text": "Call recursion after leaving the first element of the array and store the result in variable(otherCases)." }, { "code": null, "e": 2435, "s": 2308, "text": "Loop through every element of the Array(otherCases) and inside every element loop through the first element of the Array(arr)." }, { "code": null, "e": 2546, "s": 2435, "text": "Concatenate every element of the Array(arr[0]) with the Array(otherCases) and push the result in answer array." }, { "code": null, "e": 2601, "s": 2546, "text": "Example 2: This example implements the above approach." }, { "code": "<!DOCTYPE html><html> <head> <title> all combinations of a JavaScript array values. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p id=\"GFG_UP\"> </p> <button id=\"button\" onclick=\"GFG_Fun();\"> click here </button> <p id=\"GFG_DOWN\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = [ ['m', 'n'], ['c'], ['d', 'e', 'f'] ]; up.innerHTML = \"CLick on the button to get the all \"+ \"combinations of arrays.<br>Array -\"+ \"[[\" + arr[0] + \"], [\" + arr[1] + \"], [\" + arr[2] + \"]]\"; function getCombn(arr) { if (arr.length == 1) { return arr[0]; } else { var ans = []; // recur with the rest of the array. var otherCases = getCombn(arr.slice(1)); for (var i = 0; i < otherCases.length; i++) { for (var j = 0; j < arr[0].length; j++) { ans.push(arr[0][j] + otherCases[i]); } } return ans; } } function GFG_Fun() { down.innerHTML = getCombn(arr); } </script></body> </html>", "e": 3997, "s": 2601, "text": null }, { "code": null, "e": 4005, "s": 3997, "text": "Output:" }, { "code": null, "e": 4036, "s": 4005, "text": "Before clicking on the button:" }, { "code": null, "e": 4066, "s": 4036, "text": "After clicking on the button:" }, { "code": null, "e": 4083, "s": 4066, "text": "javascript-array" }, { "code": null, "e": 4099, "s": 4083, "text": "JavaScript-Misc" }, { "code": null, "e": 4110, "s": 4099, "text": "JavaScript" }, { "code": null, "e": 4127, "s": 4110, "text": "Web Technologies" } ]
How to calculate the Size of Folder using C#?
To calculate the size of a folder in C#, use the Directory.EnumerateFiles Method and get the files. To get the sub- directories, use the EnumerateDirectories method. Our folder is set using DirectoryInfo class − DirectoryInfo info = new DirectoryInfo(@"D:/new"); Now find the size − long totalSize = info.EnumerateFiles().Sum(file => file.Length); For the directories, use − info.EnumerateDirectories() Other manipulations you can perform on Directories in C# are:
[ { "code": null, "e": 1287, "s": 1187, "text": "To calculate the size of a folder in C#, use the Directory.EnumerateFiles Method and get the files." }, { "code": null, "e": 1399, "s": 1287, "text": "To get the sub- directories, use the EnumerateDirectories method. Our folder is set using DirectoryInfo class −" }, { "code": null, "e": 1450, "s": 1399, "text": "DirectoryInfo info = new DirectoryInfo(@\"D:/new\");" }, { "code": null, "e": 1470, "s": 1450, "text": "Now find the size −" }, { "code": null, "e": 1536, "s": 1470, "text": "long totalSize = info.EnumerateFiles().Sum(file => file.Length);\n" }, { "code": null, "e": 1563, "s": 1536, "text": "For the directories, use −" }, { "code": null, "e": 1591, "s": 1563, "text": "info.EnumerateDirectories()" }, { "code": null, "e": 1653, "s": 1591, "text": "Other manipulations you can perform on Directories in C# are:" } ]
Cognos - Report Functions
There are various Report functions that can be used in a Cognos report. Some of these different report functions include − This function is used to return a positive or a negative number representing the number of days between the two datetime expressions. If a timestamp_exp1 < timestamp_exp2 then the result will be a –ve number. _days_between(timestamp_exp1, timestamp_exp2) This function is used to return a number representing the number of days remaining in the month represented by the datetime expression timestamp_exp. _days_to_end_of_month(timestamp_exp) This function is used to return a datetime that is the first day of the month represented by timestamp_exp. This function is used to return the datetime resulting from adding integer_exp days to timestamp_exp. _add_days(timestamp_exp, integer_exp) This function is used to return the datetime resulting from adding integer_exp months to timestamp_exp. _add_months(timestamp_exp, integer_exp) This function is used to return the datetime resulting from adding integer_exp years to timestamp_exp. _add_years(timestamp_exp, integer_exp) This function is used to return a number that is obtained from subtracting timestamp_exp from today's date in YYYYMMDD format (years, months, days). _age(timestamp_exp) This function is used to return the day of week (between 1 and 7), where 1 is the first day of the week as indicated by integer_exp (between 1 and 7, 1 being Monday and 7 being Sunday). Note that in ISO 8601 standard, a week begins with Monday being day 1. In North America where Sunday is the first day of the week being day 7. _day_of_week(timestamp_exp, integer_exp) This function is used to return the ordinal for the day of the year in date_ exp (1 to 366). Also known as the Julian day. _day_of_year(timestamp_exp) Like these, there are various other Report functions as well that can be used.
[ { "code": null, "e": 2773, "s": 2701, "text": "There are various Report functions that can be used in a Cognos report." }, { "code": null, "e": 2824, "s": 2773, "text": "Some of these different report functions include −" }, { "code": null, "e": 3033, "s": 2824, "text": "This function is used to return a positive or a negative number representing the number of days between the two datetime expressions. If a timestamp_exp1 < timestamp_exp2 then the result will be a –ve number." }, { "code": null, "e": 3080, "s": 3033, "text": "_days_between(timestamp_exp1, timestamp_exp2)\n" }, { "code": null, "e": 3230, "s": 3080, "text": "This function is used to return a number representing the number of days remaining in the month represented by the datetime expression timestamp_exp." }, { "code": null, "e": 3268, "s": 3230, "text": "_days_to_end_of_month(timestamp_exp)\n" }, { "code": null, "e": 3376, "s": 3268, "text": "This function is used to return a datetime that is the first day of the month represented by timestamp_exp." }, { "code": null, "e": 3478, "s": 3376, "text": "This function is used to return the datetime resulting from adding integer_exp days to timestamp_exp." }, { "code": null, "e": 3517, "s": 3478, "text": "_add_days(timestamp_exp, integer_exp)\n" }, { "code": null, "e": 3621, "s": 3517, "text": "This function is used to return the datetime resulting from adding integer_exp months to timestamp_exp." }, { "code": null, "e": 3662, "s": 3621, "text": "_add_months(timestamp_exp, integer_exp)\n" }, { "code": null, "e": 3765, "s": 3662, "text": "This function is used to return the datetime resulting from adding integer_exp years to timestamp_exp." }, { "code": null, "e": 3805, "s": 3765, "text": "_add_years(timestamp_exp, integer_exp)\n" }, { "code": null, "e": 3954, "s": 3805, "text": "This function is used to return a number that is obtained from subtracting timestamp_exp from today's date in YYYYMMDD format (years, months, days)." }, { "code": null, "e": 3975, "s": 3954, "text": "_age(timestamp_exp)\n" }, { "code": null, "e": 4304, "s": 3975, "text": "This function is used to return the day of week (between 1 and 7), where 1 is the first day of the week as indicated by integer_exp (between 1 and 7, 1 being Monday and 7 being Sunday). Note that in ISO 8601 standard, a week begins with Monday being day 1. In North America where Sunday is the first day of the week being day 7." }, { "code": null, "e": 4346, "s": 4304, "text": "_day_of_week(timestamp_exp, integer_exp)\n" }, { "code": null, "e": 4469, "s": 4346, "text": "This function is used to return the ordinal for the day of the year in date_ exp (1 to 366). Also known as the Julian day." }, { "code": null, "e": 4498, "s": 4469, "text": "_day_of_year(timestamp_exp)\n" } ]
Getting Unique values from a column in Pandas dataframe
15 Jan, 2019 Let’s see how can we retrieve the unique values from pandas dataframe. Let’s create a dataframe from CSV file. We are using the past data of GDP from different countries. You can get the dataset from here. # import pandas as pdimport pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH'# load the data with pd.read_csvrecord = pd.read_csv(gapminder_csv_url) record.head() Method #1: Select the continent column from the record and apply the unique function to get the values as we want. # import pandas as pdimport pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH'# load the data with pd.read_csvrecord = pd.read_csv(gapminder_csv_url) print(record['continent'].unique()) Output: ['Asia' 'Europe' 'Africa' 'Americas' 'Oceania'] Method #2: Select unique values from the countrycolumn. # import pandas as pdimport pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH' # load the data with pd.read_csvrecord = pd.read_csv(gapminder_csv_url) print(record.country.unique()) Output: ['Afghanistan' 'Albania' 'Algeria' 'Angola' 'Argentina' 'Australia' 'Austria' 'Bahrain' 'Bangladesh' 'Belgium' 'Benin' 'Bolivia' 'Bosnia and Herzegovina' 'Botswana' 'Brazil' 'Bulgaria' 'Burkina Faso' 'Burundi' 'Cambodia' 'Cameroon' 'Canada' 'Central African Republic' 'Chad' 'Chile' 'China' 'Colombia' 'Comoros' 'Congo Dem. Rep.' 'Congo Rep.' 'Costa Rica' "Cote d'Ivoire" 'Croatia' 'Cuba' 'Czech Republic' 'Denmark' 'Djibouti' 'Dominican Republic' 'Ecuador' 'Egypt' 'El Salvador' 'Equatorial Guinea' 'Eritrea' 'Ethiopia' 'Finland' 'France' 'Gabon' 'Gambia' 'Germany' 'Ghana' 'Greece' 'Guatemala' 'Guinea' 'Guinea-Bissau' 'Haiti' 'Honduras' 'Hong Kong China' 'Hungary' 'Iceland' 'India' 'Indonesia' 'Iran' 'Iraq' 'Ireland' 'Israel' 'Italy' 'Jamaica' 'Japan' 'Jordan' 'Kenya' 'Korea Dem. Rep.' 'Korea Rep.' 'Kuwait' 'Lebanon' 'Lesotho' 'Liberia' 'Libya' 'Madagascar' 'Malawi' 'Malaysia' 'Mali' 'Mauritania' 'Mauritius' 'Mexico' 'Mongolia' 'Montenegro' 'Morocco' 'Mozambique' 'Myanmar' 'Namibia' 'Nepal' 'Netherlands' 'New Zealand' 'Nicaragua' 'Niger' 'Nigeria' 'Norway' 'Oman' 'Pakistan' 'Panama' 'Paraguay' 'Peru' 'Philippines' 'Poland' 'Portugal' 'Puerto Rico' 'Reunion' 'Romania' 'Rwanda' 'Sao Tome and Principe' 'Saudi Arabia' 'Senegal' 'Serbia' 'Sierra Leone' 'Singapore' 'Slovak Republic' 'Slovenia' 'Somalia' 'South Africa' 'Spain' 'Sri Lanka' 'Sudan' 'Swaziland' 'Sweden' 'Switzerland' 'Syria' 'Taiwan' 'Tanzania' 'Thailand' 'Togo' 'Trinidad and Tobago' 'Tunisia' 'Turkey' 'Uganda' 'United Kingdom' 'United States' 'Uruguay' 'Venezuela' 'Vietnam' 'West Bank and Gaza' 'Yemen Rep.' 'Zambia' 'Zimbabwe'] Method #3: In this method you can see that we use the dataframe inside the unique function as parameter although we select the same column as above so we get the same output. # Write Python3 code here# import pandas as pdimport pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH' # load the data with pd.read_csvrecord = pd.read_csv(gapminder_csv_url) print(pd.unique(record['continent'])) Output: ['Asia' 'Europe' 'Africa' 'Americas' 'Oceania'] 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.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jan, 2019" }, { "code": null, "e": 99, "s": 28, "text": "Let’s see how can we retrieve the unique values from pandas dataframe." }, { "code": null, "e": 234, "s": 99, "text": "Let’s create a dataframe from CSV file. We are using the past data of GDP from different countries. You can get the dataset from here." }, { "code": "# import pandas as pdimport pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH'# load the data with pd.read_csvrecord = pd.read_csv(gapminder_csv_url) record.head()", "e": 405, "s": 234, "text": null }, { "code": null, "e": 520, "s": 405, "text": "Method #1: Select the continent column from the record and apply the unique function to get the values as we want." }, { "code": "# import pandas as pdimport pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH'# load the data with pd.read_csvrecord = pd.read_csv(gapminder_csv_url) print(record['continent'].unique())", "e": 713, "s": 520, "text": null }, { "code": null, "e": 721, "s": 713, "text": "Output:" }, { "code": null, "e": 770, "s": 721, "text": "['Asia' 'Europe' 'Africa' 'Americas' 'Oceania']\n" }, { "code": null, "e": 826, "s": 770, "text": "Method #2: Select unique values from the countrycolumn." }, { "code": "# import pandas as pdimport pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH' # load the data with pd.read_csvrecord = pd.read_csv(gapminder_csv_url) print(record.country.unique())", "e": 1016, "s": 826, "text": null }, { "code": null, "e": 1024, "s": 1016, "text": "Output:" }, { "code": null, "e": 2656, "s": 1024, "text": "['Afghanistan' 'Albania' 'Algeria' 'Angola' 'Argentina' 'Australia'\n 'Austria' 'Bahrain' 'Bangladesh' 'Belgium' 'Benin' 'Bolivia'\n 'Bosnia and Herzegovina' 'Botswana' 'Brazil' 'Bulgaria' 'Burkina Faso'\n 'Burundi' 'Cambodia' 'Cameroon' 'Canada' 'Central African Republic'\n 'Chad' 'Chile' 'China' 'Colombia' 'Comoros' 'Congo Dem. Rep.'\n 'Congo Rep.' 'Costa Rica' \"Cote d'Ivoire\" 'Croatia' 'Cuba'\n 'Czech Republic' 'Denmark' 'Djibouti' 'Dominican Republic' 'Ecuador'\n 'Egypt' 'El Salvador' 'Equatorial Guinea' 'Eritrea' 'Ethiopia' 'Finland'\n 'France' 'Gabon' 'Gambia' 'Germany' 'Ghana' 'Greece' 'Guatemala' 'Guinea'\n 'Guinea-Bissau' 'Haiti' 'Honduras' 'Hong Kong China' 'Hungary' 'Iceland'\n 'India' 'Indonesia' 'Iran' 'Iraq' 'Ireland' 'Israel' 'Italy' 'Jamaica'\n 'Japan' 'Jordan' 'Kenya' 'Korea Dem. Rep.' 'Korea Rep.' 'Kuwait'\n 'Lebanon' 'Lesotho' 'Liberia' 'Libya' 'Madagascar' 'Malawi' 'Malaysia'\n 'Mali' 'Mauritania' 'Mauritius' 'Mexico' 'Mongolia' 'Montenegro'\n 'Morocco' 'Mozambique' 'Myanmar' 'Namibia' 'Nepal' 'Netherlands'\n 'New Zealand' 'Nicaragua' 'Niger' 'Nigeria' 'Norway' 'Oman' 'Pakistan'\n 'Panama' 'Paraguay' 'Peru' 'Philippines' 'Poland' 'Portugal'\n 'Puerto Rico' 'Reunion' 'Romania' 'Rwanda' 'Sao Tome and Principe'\n 'Saudi Arabia' 'Senegal' 'Serbia' 'Sierra Leone' 'Singapore'\n 'Slovak Republic' 'Slovenia' 'Somalia' 'South Africa' 'Spain' 'Sri Lanka'\n 'Sudan' 'Swaziland' 'Sweden' 'Switzerland' 'Syria' 'Taiwan' 'Tanzania'\n 'Thailand' 'Togo' 'Trinidad and Tobago' 'Tunisia' 'Turkey' 'Uganda'\n 'United Kingdom' 'United States' 'Uruguay' 'Venezuela' 'Vietnam'\n 'West Bank and Gaza' 'Yemen Rep.' 'Zambia' 'Zimbabwe']\n" }, { "code": null, "e": 2667, "s": 2656, "text": "Method #3:" }, { "code": null, "e": 2831, "s": 2667, "text": "In this method you can see that we use the dataframe inside the unique function as parameter although we select the same column as above so we get the same output." }, { "code": "# Write Python3 code here# import pandas as pdimport pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH' # load the data with pd.read_csvrecord = pd.read_csv(gapminder_csv_url) print(pd.unique(record['continent']))", "e": 3053, "s": 2831, "text": null }, { "code": null, "e": 3061, "s": 3053, "text": "Output:" }, { "code": null, "e": 3110, "s": 3061, "text": "['Asia' 'Europe' 'Africa' 'Americas' 'Oceania']\n" }, { "code": null, "e": 3135, "s": 3110, "text": "pandas-dataframe-program" }, { "code": null, "e": 3142, "s": 3135, "text": "Picked" }, { "code": null, "e": 3166, "s": 3142, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3180, "s": 3166, "text": "Python-pandas" }, { "code": null, "e": 3187, "s": 3180, "text": "Python" } ]
How to prevent line breaks in the list of items using CSS?
10 May, 2019 The display:inline-block property is used to show an element in the inline-level block container. It converts the block of elements into an inline element. Use height and width property to set an inline element. The display property is used to prevent a line break of a list of items. Syntax: element { display:inline-block; } Example: <!DOCTYPE html> <html> <head> <title>preventline break in list items</title> <style> li { display:inline-block; text-decoration:underline; } h1 { color:green; } h1, h2 { text-align:center; } body { width:70%; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>display:inline-block;</h2> <b>Subjects Of Computer science:</b> <ul> <li>Computer Network</li> <li>Operating System </li> <li>Data Structure using C</li> <li>Object Oriented Programming Concepts</li> <li>Digital Electronics</li> </ul> </body></html> Output: Supported Browsers: The browser supported by CSS display property are listed below: Apple Safari 3.1 Google Chrome 4.0 Firefox 3.0 Opera 7.6 Internet Explorer 8.0 Kirti_Mangal CSS-Misc Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2019" }, { "code": null, "e": 313, "s": 28, "text": "The display:inline-block property is used to show an element in the inline-level block container. It converts the block of elements into an inline element. Use height and width property to set an inline element. The display property is used to prevent a line break of a list of items." }, { "code": null, "e": 321, "s": 313, "text": "Syntax:" }, { "code": null, "e": 360, "s": 321, "text": "element {\n display:inline-block;\n} " }, { "code": null, "e": 369, "s": 360, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title>preventline break in list items</title> <style> li { display:inline-block; text-decoration:underline; } h1 { color:green; } h1, h2 { text-align:center; } body { width:70%; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>display:inline-block;</h2> <b>Subjects Of Computer science:</b> <ul> <li>Computer Network</li> <li>Operating System </li> <li>Data Structure using C</li> <li>Object Oriented Programming Concepts</li> <li>Digital Electronics</li> </ul> </body></html> ", "e": 1210, "s": 369, "text": null }, { "code": null, "e": 1218, "s": 1210, "text": "Output:" }, { "code": null, "e": 1302, "s": 1218, "text": "Supported Browsers: The browser supported by CSS display property are listed below:" }, { "code": null, "e": 1319, "s": 1302, "text": "Apple Safari 3.1" }, { "code": null, "e": 1337, "s": 1319, "text": "Google Chrome 4.0" }, { "code": null, "e": 1349, "s": 1337, "text": "Firefox 3.0" }, { "code": null, "e": 1359, "s": 1349, "text": "Opera 7.6" }, { "code": null, "e": 1381, "s": 1359, "text": "Internet Explorer 8.0" }, { "code": null, "e": 1394, "s": 1381, "text": "Kirti_Mangal" }, { "code": null, "e": 1403, "s": 1394, "text": "CSS-Misc" }, { "code": null, "e": 1410, "s": 1403, "text": "Picked" }, { "code": null, "e": 1414, "s": 1410, "text": "CSS" }, { "code": null, "e": 1419, "s": 1414, "text": "HTML" }, { "code": null, "e": 1436, "s": 1419, "text": "Web Technologies" }, { "code": null, "e": 1441, "s": 1436, "text": "HTML" } ]
Using Selenium in Python to click/select a radio button.
We can select/click the radio button with Selenium. In an html document, each radio button has an attribute type set to a value as radio. In order to select a radio button, we shall first identify it and then apply the click() method to it. Code Implementation. from selenium import webdriver driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe") # maximize with maximize_window() driver.maximize_window() driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm") # identify element and click() l=driver.find_element_by_xpath("//input[@value='2']") l.click() driver.close()
[ { "code": null, "e": 1428, "s": 1187, "text": "We can select/click the radio button with Selenium. In an html document, each radio button has an attribute type set to a value as radio. In order to select a radio button, we shall first identify it and then apply the click() method to it." }, { "code": null, "e": 1449, "s": 1428, "text": "Code Implementation." }, { "code": null, "e": 1803, "s": 1449, "text": "from selenium import webdriver\ndriver = webdriver.Chrome (executable_path=\"C:\\\\chromedriver.exe\")\n# maximize with maximize_window()\ndriver.maximize_window()\ndriver.get(\"https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm\")\n# identify element and click()\nl=driver.find_element_by_xpath(\"//input[@value='2']\")\nl.click()\ndriver.close()" } ]
How to create Hamburger Menu for mobile devices ?
20 Nov, 2020 The hamburger button is the button that placed on the top corner of the web page user interface. The hamburger button toggles the navigation menu bar on the screen. The icon which is associated with this widget, consisting of three horizontal bars, is also known as the collapsed menu icon. We will create: Hamburger Menu using html, CSS and JavaScript for mobile devices Hamburger Menu using Bootstrap Hamburger Menu using html, CSS and JavaScript for mobile devices: We will write all HTML and CSS of our own and add some JavaScript to handle click event. The basic approach is to mark the visibility of navigation bar to hidden. When a user clicks the icon, then JavaScript will remove the visibility from hidden. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font -awesome/4.7.0/css/font-awesome.min.css"> <title>GFG Hamburger Menu Tutorial</title> <style> .container { max-width: 480px; height: 500px; background: #5555; margin: auto; border: 2px solid green; } .navbar { background: white; position: relative; } .links { display: none; } .heading a:nth-child(2) { color: green; text-decoration: none; font-size: 20px; display: block; padding: 7px; margin-left: 150px; } .heading a i { color: green; padding: 10px; display: block; position: absolute; left: 0; top: 0; } .heading a i:hover { background-color: rgb(0, 0, 0); color: rgb(255, 255, 255); } .links { background-color: rgb(190, 196, 190); } .links a { color: green; padding: 5px 16px; text-decoration: none; font-size: 17px; display: block; text-align: center; border-bottom: 1px solid white; } .links a:hover { background-color: green; color: white; } </style></head> <body> <div class="container"> <div class="navbar"> <div class="heading"> <a href="#hamburger-icon" onclick="gfgMenu()"> <i class="fa fa-bars"></i> </a> <a href="#Home"> Geeks For Geeks </a> </div> <div class="links"> <a href="#gfg1"> Notes </a> <a href="#gfg2"> Algorithm </a> <a href="#gfg3"> Maths </a> <a href="#gfg4"> Data Structure </a> <a href="#gfg5"> Java </a> </div> </div> </div> <script> function gfgMenu() { const GFG = document.querySelector('.links'); if (GFG.style.display === "none") { GFG.style.display = "block"; } else { GFG.style.display = "none"; } } </script></body> </html> Output: Hamburger Menu using Bootstrap: In this approach, we will use bootstrap to design our page and JavaScript work is same as in above method. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>GFG Hamburger Menu</title> <style> .icon, h5 { color: green; } .links a:hover, .icon:hover { background-color: green; color: white; transition: 0.4s all linear; } </style></head> <body> <div class="container"> <div class="pt-2 pb-2 border-bottom"> <a class="icon pl-2 pr-2 p-1 float-right" href="#hamburger-icon" onclick="gfgMenu()"> <i class="fa fa-bars"></i> </a> <a class="pt-2 pb-2 text-success text-decoration-none font-weight -bold" href="#Home"> Geeks For Geeks </a> </div> <div class="links nav flex-column d-none"> <a class="nav-link border-bottom" href="#gfg1"> Notes </a> <a class="nav-link border-bottom" href="#gfg2"> Algorithm </a> <a class="nav-link border-bottom" href="#gfg3"> Maths </a> <a class="nav-link border-bottom" href="#gfg4"> Data Structure </a> <a class="nav-link border-bottom" href="#gfg5"> Java </a> </div> <div class="container"> <h5 class="my-2">Hamburger Menu</h5> <p> Click on the icon present at top left corner. </p> </div> </div> <script> function gfgMenu() { const GFG = document.querySelector('.links'); if (GFG.classList.contains('d-none')) { GFG.classList.remove('d-none'); } else { GFG.classList.add('d-none'); } } </script></body> </html> Output: Bootstrap-Misc CSS-Misc HTML-Misc JavaScript-Misc Bootstrap CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to set vertical alignment in Bootstrap ? How to toggle password visibility in forms using Bootstrap-icons ? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Nov, 2020" }, { "code": null, "e": 319, "s": 28, "text": "The hamburger button is the button that placed on the top corner of the web page user interface. The hamburger button toggles the navigation menu bar on the screen. The icon which is associated with this widget, consisting of three horizontal bars, is also known as the collapsed menu icon." }, { "code": null, "e": 335, "s": 319, "text": "We will create:" }, { "code": null, "e": 400, "s": 335, "text": "Hamburger Menu using html, CSS and JavaScript for mobile devices" }, { "code": null, "e": 431, "s": 400, "text": "Hamburger Menu using Bootstrap" }, { "code": null, "e": 746, "s": 431, "text": "Hamburger Menu using html, CSS and JavaScript for mobile devices: We will write all HTML and CSS of our own and add some JavaScript to handle click event. The basic approach is to mark the visibility of navigation bar to hidden. When a user clicks the icon, then JavaScript will remove the visibility from hidden. " }, { "code": null, "e": 751, "s": 746, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font -awesome/4.7.0/css/font-awesome.min.css\"> <title>GFG Hamburger Menu Tutorial</title> <style> .container { max-width: 480px; height: 500px; background: #5555; margin: auto; border: 2px solid green; } .navbar { background: white; position: relative; } .links { display: none; } .heading a:nth-child(2) { color: green; text-decoration: none; font-size: 20px; display: block; padding: 7px; margin-left: 150px; } .heading a i { color: green; padding: 10px; display: block; position: absolute; left: 0; top: 0; } .heading a i:hover { background-color: rgb(0, 0, 0); color: rgb(255, 255, 255); } .links { background-color: rgb(190, 196, 190); } .links a { color: green; padding: 5px 16px; text-decoration: none; font-size: 17px; display: block; text-align: center; border-bottom: 1px solid white; } .links a:hover { background-color: green; color: white; } </style></head> <body> <div class=\"container\"> <div class=\"navbar\"> <div class=\"heading\"> <a href=\"#hamburger-icon\" onclick=\"gfgMenu()\"> <i class=\"fa fa-bars\"></i> </a> <a href=\"#Home\"> Geeks For Geeks </a> </div> <div class=\"links\"> <a href=\"#gfg1\"> Notes </a> <a href=\"#gfg2\"> Algorithm </a> <a href=\"#gfg3\"> Maths </a> <a href=\"#gfg4\"> Data Structure </a> <a href=\"#gfg5\"> Java </a> </div> </div> </div> <script> function gfgMenu() { const GFG = document.querySelector('.links'); if (GFG.style.display === \"none\") { GFG.style.display = \"block\"; } else { GFG.style.display = \"none\"; } } </script></body> </html>", "e": 3261, "s": 751, "text": null }, { "code": null, "e": 3269, "s": 3261, "text": "Output:" }, { "code": null, "e": 3408, "s": 3269, "text": "Hamburger Menu using Bootstrap: In this approach, we will use bootstrap to design our page and JavaScript work is same as in above method." }, { "code": null, "e": 3413, "s": 3408, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" integrity=\"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2\" crossorigin=\"anonymous\"> <title>GFG Hamburger Menu</title> <style> .icon, h5 { color: green; } .links a:hover, .icon:hover { background-color: green; color: white; transition: 0.4s all linear; } </style></head> <body> <div class=\"container\"> <div class=\"pt-2 pb-2 border-bottom\"> <a class=\"icon pl-2 pr-2 p-1 float-right\" href=\"#hamburger-icon\" onclick=\"gfgMenu()\"> <i class=\"fa fa-bars\"></i> </a> <a class=\"pt-2 pb-2 text-success text-decoration-none font-weight -bold\" href=\"#Home\"> Geeks For Geeks </a> </div> <div class=\"links nav flex-column d-none\"> <a class=\"nav-link border-bottom\" href=\"#gfg1\"> Notes </a> <a class=\"nav-link border-bottom\" href=\"#gfg2\"> Algorithm </a> <a class=\"nav-link border-bottom\" href=\"#gfg3\"> Maths </a> <a class=\"nav-link border-bottom\" href=\"#gfg4\"> Data Structure </a> <a class=\"nav-link border-bottom\" href=\"#gfg5\"> Java </a> </div> <div class=\"container\"> <h5 class=\"my-2\">Hamburger Menu</h5> <p> Click on the icon present at top left corner. </p> </div> </div> <script> function gfgMenu() { const GFG = document.querySelector('.links'); if (GFG.classList.contains('d-none')) { GFG.classList.remove('d-none'); } else { GFG.classList.add('d-none'); } } </script></body> </html>", "e": 5716, "s": 3413, "text": null }, { "code": null, "e": 5724, "s": 5716, "text": "Output:" }, { "code": null, "e": 5739, "s": 5724, "text": "Bootstrap-Misc" }, { "code": null, "e": 5748, "s": 5739, "text": "CSS-Misc" }, { "code": null, "e": 5758, "s": 5748, "text": "HTML-Misc" }, { "code": null, "e": 5774, "s": 5758, "text": "JavaScript-Misc" }, { "code": null, "e": 5784, "s": 5774, "text": "Bootstrap" }, { "code": null, "e": 5788, "s": 5784, "text": "CSS" }, { "code": null, "e": 5793, "s": 5788, "text": "HTML" }, { "code": null, "e": 5804, "s": 5793, "text": "JavaScript" }, { "code": null, "e": 5821, "s": 5804, "text": "Web Technologies" }, { "code": null, "e": 5826, "s": 5821, "text": "HTML" }, { "code": null, "e": 5924, "s": 5826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5965, "s": 5924, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 5998, "s": 5965, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 6024, "s": 5998, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 6069, "s": 6024, "text": "How to set vertical alignment in Bootstrap ?" }, { "code": null, "e": 6136, "s": 6069, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 6184, "s": 6136, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 6246, "s": 6184, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6296, "s": 6246, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 6354, "s": 6296, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Rat in a Maze | Backtracking using Stack
06 May, 2022 Prerequisites – Recursion, Backtracking and Stack Data Structure.A Maze is given as N*M binary matrix of blocks and there is a rat initially at (0, 0) ie. maze[0][0] and the rat wants to eat food which is present at some given block in the maze (fx, fy). In a maze matrix, 0 means that the block is a dead end and 1 means that the block can be used in the path from source to destination. The rat can move in any direction (not diagonally) to any block provided the block is not a dead end. The task is to check if there exists any path so that the rat can reach the food or not. It is not needed to print the path.Examples: Input : maze[4][5] = { {1, 0, 1, 1, 0}, {1, 1, 1, 0, 1}, {0, 1, 0, 1, 1}, {1, 1, 1, 1, 1} } fx = 2, fy=3 Output : Path Found! The path can be: (0, 0) -> (1, 0) -> (1, 1) -> (2, 1) -> (3, 1) -> (3, 2) -> (3, 3) -> (2, 3) This is the famous Rat in a Maze problem asked in many interviews that can be solved using Recursion and Backtracking. We already have discussed a Backtracking solution to this problem using recursion in Rat in a Maze | Backtracking-2. In this an iterative solution using stack is discussed.In the previous article, Recursion uses a call stack to keep the store each recursive call and then pop as the function ends. We will eliminate recursion by using our own stack to do the same thing.A node structure is used to store the (i, j) coordinates and directions explored from this node and which direction to try out next. Structure Used: X : x coordinate of the node Y : y coordinate of the node dir : This variable will be used to tell which all directions we have tried and which to choose next. We will try all the directions in anti-clockwise manner starting from Up. Initially it will be assigned 0. If dir=0 try Up direction.If dir=1 try left direction.If dir=2 try down direction.If dir=3 try right direction. X : x coordinate of the node Y : y coordinate of the node dir : This variable will be used to tell which all directions we have tried and which to choose next. We will try all the directions in anti-clockwise manner starting from Up. Initially it will be assigned 0. If dir=0 try Up direction.If dir=1 try left direction.If dir=2 try down direction.If dir=3 try right direction. If dir=0 try Up direction. If dir=1 try left direction. If dir=2 try down direction. If dir=3 try right direction. Initially, we will push a node with indexes i=0, j=0 and dir=0 into the stack. We will move to all the direction of the topmost node one by one in an anti-clockwise manner and each time as we try out a new path we will push that node (block of the maze) in the stack. We will increase dir variable of the topmost node each time so that we can try a new direction each time unless all the directions are explored ie. dir=4. If dir equals to 4 we will pop that node from the stack that means we are retracting one step back to the path where we came from.We will also maintain a visited matrix which will maintain which blocks of the maze are already used in the path or in other words present in the stack. While trying out any direction we will also check if the block of the maze is not a dead end and is not out of the maze too.We will do this while either the topmost node coordinates become equal to the food’s coordinates that means we have reached the food or the stack becomes empty which means that there is no possible path to reach the food.Below is the implementation of the above approach: C++ Java C# Python3 Javascript // CPP program to solve Rat in a maze// problem with backtracking using stack #include <cstring>#include <iostream>#include <stack> using namespace std; #define N 4#define M 5 class node {public: int x, y; int dir; node(int i, int j) { x = i; y = j; // Initially direction // set to 0 dir = 0; }}; // maze of n*m matrixint n = N, m = M; // Coordinates of foodint fx, fy;bool visited[N][M]; bool isReachable(int maze[N][M]){ // Initially starting at (0, 0). int i = 0, j = 0; stack<node> s; node temp(i, j); s.push(temp); while (!s.empty()) { // Pop the top node and move to the // left, right, top, down or retract // back according the value of node's // dir variable. temp = s.top(); int d = temp.dir; i = temp.x, j = temp.y; // Increment the direction and // push the node in the stack again. temp.dir++; s.pop(); s.push(temp); // If we reach the Food coordinates // return true if (i == fx and j == fy) { return true; } // Checking the Up direction. if (d == 0) { if (i - 1 >= 0 and maze[i - 1][j] and visited[i - 1][j]) { node temp1(i - 1, j); visited[i - 1][j] = false; s.push(temp1); } } // Checking the left direction else if (d == 1) { if (j - 1 >= 0 and maze[i][j - 1] and visited[i][j - 1]) { node temp1(i, j - 1); visited[i][j - 1] = false; s.push(temp1); } } // Checking the down direction else if (d == 2) { if (i + 1 < n and maze[i + 1][j] and visited[i + 1][j]) { node temp1(i + 1, j); visited[i + 1][j] = false; s.push(temp1); } } // Checking the right direction else if (d == 3) { if (j + 1 < m and maze[i][j + 1] and visited[i][j + 1]) { node temp1(i, j + 1); visited[i][j + 1] = false; s.push(temp1); } } // If none of the direction can take // the rat to the Food, retract back // to the path where the rat came from. else { visited[temp.x][temp.y] = true; s.pop(); } } // If the stack is empty and // no path is found return false. return false;} // Driver codeint main(){ // Initially setting the visited // array to true (unvisited) memset(visited, true, sizeof(visited)); // Maze matrix int maze[N][M] = { { 1, 0, 1, 1, 0 }, { 1, 1, 1, 0, 1 }, { 0, 1, 0, 1, 1 }, { 1, 1, 1, 1, 1 } }; // Food coordinates fx = 2; fy = 3; if (isReachable(maze)) { cout << "Path Found!" << '\n'; } else cout << "No Path Found!" << '\n'; return 0;} // Java program to solve Rat in a maze// problem with backtracking using stackimport java.util.Stack; class Node{ private int x, y; private int dir; public Node(int i, int j) { this.x = i; this.y = j; // default value for direction set to 0 (Up) this.dir = 0; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getDir() { return dir; } public void setDir(int dir) { this.dir = dir; }} public class RatInMaze{ private static final int N = 4; private static final int M = 5; // maze of n*m matrix int n = N, m = M; private static boolean[][] visited = new boolean[N][M]; // Driver code public static void main(String[] args) { // Initially setting the visited // array to true (unvisited) setVisited(true); // Maze matrix int maze[][] = {{ 1, 0, 1, 1, 0 }, { 1, 1, 1, 0, 1 }, { 0, 1, 0, 1, 1 }, { 1, 1, 1, 1, 1 } }; if (isReachable(maze)) { System.out.println("Path Found!\n"); } else System.out.println("No Path Found!\n"); } private static void setVisited(boolean b) { for (int i = 0; i < visited.length; i++) { for (int j = 0; j < visited[i].length; j++) { visited[i][j] = b; } } } private static boolean isReachable(int maze[][]) { // Initially starting at (0, 0). int i = 0, j = 0; // Food coordinates // Coordinates of food int fx, fy; fx = 2; fy = 3; Stack<Node> s = new Stack<Node>(); Node temp = new Node(i, j); s.push(temp); while (!s.empty()) { // Pop the top node and move to the // left, right, top, down or retract // back according the value of node's // dir variable. temp = s.peek(); int d = temp.getDir(); i = temp.getX(); j = temp.getY(); // Increment the direction and // push the node in the stack again. temp.setDir(temp.getDir() + 1); s.pop(); s.push(temp); // If we reach the Food coordinates // return true if (i == fx && j == fy) { return true; } if (d == 0) { // Checking the Up direction. if (i - 1 >= 0 && maze[i - 1][j] == 1 && visited[i - 1][j]) { Node temp1 = new Node(i - 1, j); visited[i - 1][j] = false; s.push(temp1); } } else if (d == 1) { // Checking the left direction if (j - 1 >= 0 && maze[i][j - 1] == 1 && visited[i][j - 1]) { Node temp1 = new Node(i, j - 1); visited[i][j - 1] = false; s.push(temp1); } } else if (d == 2) { // Checking the down direction if (i + 1 < N && maze[i + 1][j] == 1 && visited[i + 1][j]) { Node temp1 = new Node(i + 1, j); visited[i + 1][j] = false; s.push(temp1); } } else if (d == 3) { // Checking the right direction if (j + 1 < M && maze[i][j + 1] == 1 && visited[i][j + 1]) { Node temp1 = new Node(i, j + 1); visited[i][j + 1] = false; s.push(temp1); } } // If none of the direction can take // the rat to the Food, retract back // to the path where the rat came from. else { visited[temp.getX()][temp.getY()] = true; s.pop(); } } // If the stack is empty and // no path is found return false. return false; }} // This code is contributed by nirajtechi // C# program to solve Rat in a maze// problem with backtracking using stackusing System;using System.Collections.Generic; public class Node{ private int x, y; private int dir; public Node(int i, int j) { this.x = i; this.y = j; // default value for direction set to 0 (Up) this.dir = 0; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getDir() { return dir; } public void setDir(int dir) { this.dir = dir; }} public class RatInMaze{ private static readonly int N = 4; private static readonly int M = 5; // maze of n*m matrix int n = N, m = M; private static bool [,]visited = new bool[N,M]; // Driver code public static void Main(String[] args) { // Initially setting the visited // array to true (unvisited) setVisited(true); // Maze matrix int [,]maze = {{ 1, 0, 1, 1, 0 }, { 1, 1, 1, 0, 1 }, { 0, 1, 0, 1, 1 }, { 1, 1, 1, 1, 1 } }; if (isReachable(maze)) { Console.WriteLine("Path Found!\n"); } else Console.WriteLine("No Path Found!\n"); } private static void setVisited(bool b) { for (int i = 0; i < visited.GetLength(0); i++) { for (int j = 0; j < visited.GetLength(0); j++) { visited[i,j] = b; } } } private static bool isReachable(int [,]maze) { // Initially starting at (0, 0). int i = 0, j = 0; // Food coordinates // Coordinates of food int fx, fy; fx = 2; fy = 3; Stack<Node> s = new Stack<Node>(); Node temp = new Node(i, j); s.Push(temp); while (s.Count!=0) { // Pop the top node and move to the // left, right, top, down or retract // back according the value of node's // dir variable. temp = s.Peek(); int d = temp.getDir(); i = temp.getX(); j = temp.getY(); // Increment the direction and // push the node in the stack again. temp.setDir(temp.getDir() + 1); s.Pop(); s.Push(temp); // If we reach the Food coordinates // return true if (i == fx && j == fy) { return true; } if (d == 0) { // Checking the Up direction. if (i - 1 >= 0 && maze[i - 1,j] == 1 && visited[i - 1,j]) { Node temp1 = new Node(i - 1, j); visited[i - 1,j] = false; s.Push(temp1); } } else if (d == 1) { // Checking the left direction if (j - 1 >= 0 && maze[i,j - 1] == 1 && visited[i,j - 1]) { Node temp1 = new Node(i, j - 1); visited[i,j - 1] = false; s.Push(temp1); } } else if (d == 2) { // Checking the down direction if (i + 1 < N && maze[i + 1,j] == 1 && visited[i + 1,j]) { Node temp1 = new Node(i + 1, j); visited[i + 1,j] = false; s.Push(temp1); } } else if (d == 3) { // Checking the right direction if (j + 1 < M && maze[i,j + 1] == 1 && visited[i,j + 1]) { Node temp1 = new Node(i, j + 1); visited[i,j + 1] = false; s.Push(temp1); } } // If none of the direction can take // the rat to the Food, retract back // to the path where the rat came from. else { visited[temp.getX(),temp.getY()] = true; s.Pop(); } } // If the stack is empty and // no path is found return false. return false; }} // This code contributed by Rajput-Ji # CPP program to solve Rat in a maze# problem with backtracking using stack N=4M=5 class node: def __init__(self,i,j): self.x=i self.y=j self.dirn=0 # maze of n*m matrixn = N; m = M # Coordinates of foodfx=0; fy=0visited=[[True]*N for _ in range(M)] def isReachable(maze): # Initially starting at (0, 0). i = 0; j = 0 s=[] temp=node(i, j) s.append(temp) while s: # Pop the top node and move to the # left, right, top, down or retract # back according the value of node's # dirn variable. temp = s.pop() d = temp.dirn i = temp.x; j = temp.y # Increment the direction and # push the node in the stack again. temp.dirn+=1 s.append(temp) # If we reach the Food coordinates # return true if (i == fx and j == fy): return True # Checking the Up direction. if (d == 0): if (i - 1 >= 0 and maze[i - 1][j] and visited[i - 1][j]): temp1=node(i - 1, j) visited[i - 1][j] = False s.append(temp1) # Checking the left direction elif (d == 1): if(j - 1 >= 0 and maze[i][j - 1] and visited[i][j - 1]): temp1=node(i, j - 1) visited[i][j - 1] = False s.append(temp1) # Checking the down direction elif (d == 2): if(i + 1 < n and maze[i + 1][j] and visited[i + 1][j]): temp1=node(i + 1, j) visited[i + 1][j] = False s.append(temp1) # Checking the right direction elif (d == 3): if (j + 1 < m and maze[i][j + 1] and visited[i][j + 1]): temp1=node(i, j + 1) visited[i][j + 1] = False s.append(temp1) # If none of the direction can take # the rat to the Food, retract back # to the path where the rat came from. else: visited[temp.x][temp.y] = True s.pop() # If the stack is empty and # no path is found return false. return False # Driver codeif __name__ == '__main__': # Initially setting the visited # array to true (unvisited) # Maze matrix maze = [ [ 1, 0, 1, 1, 0 ], [ 1, 1, 1, 0, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 1, 1, 1, 1 ] ] # Food coordinates fx = 2 fy = 3 if (isReachable(maze)): print("Path Found!") else: print("No Path Found!") <script> // JavaScript program to solve Rat in a maze// problem with backtracking using stack const N = 4const M = 5 class node{ constructor(i, j){ this.x = i this.y = j this.dirn = 0 }} // maze of n*m matrixlet n = N, m = M // Coordinates of foodlet fx = 0, fy = 0let visited = new Array(N);for(let i = 0; i < N; i++){ visited[i] = new Array(M).fill(true);} function isReachable(maze){ // Initially starting at (0, 0). let i = 0, j = 0 let s=[] let temp=new node(i, j) s.push(temp) while(s.length>0){ // Pop the top node && move to the // left, right, top, down or retract // back according the value of node's // dirn variable. temp = s[s.length - 1] s.pop() let d = temp.dirn i = temp.x, j = temp.y // Increment the direction && // push the node in the stack again. temp.dirn+=1 s.push(temp) // If we reach the Food coordinates // return true if (i == fx && j == fy) return true // Checking the Up direction. if (d == 0){ if (i - 1 >= 0 && maze[i - 1][j] && visited[i - 1][j]){ let temp1=new node(i - 1, j) visited[i - 1][j] = false s.push(temp1) } } // Checking the left direction else if (d == 1){ if(j - 1 >= 0 && maze[i][j - 1] && visited[i][j - 1]){ let temp1=new node(i, j - 1) visited[i][j - 1] = false s.push(temp1) } } // Checking the down direction else if (d == 2){ if(i + 1 < n && maze[i + 1][j] && visited[i + 1][j]){ let temp1=new node(i + 1, j) visited[i + 1][j] = false s.push(temp1) } } // Checking the right direction else if (d == 3){ if (j + 1 < m && maze[i][j + 1] && visited[i][j + 1]){ let temp1=new node(i, j + 1) visited[i][j + 1] = false s.push(temp1) } } // If none of the direction can take // the rat to the Food, retract back // to the path where the rat came from. else{ visited[temp.x][temp.y] = true s.pop() } } // If the stack is empty && // no path is found return false. return false} // Driver code // Initially setting the visited// array to true (unvisited) // Maze matrixlet maze = [ [ 1, 0, 1, 1, 0 ], [ 1, 1, 1, 0, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 1, 1, 1, 1 ]] // Food coordinatesfx = 2fy = 3 if (isReachable(maze)) document.write("Path Found!","</br>")else document.write("No Path Found!","</br>") // This code is contributed by shinjanpatra </script> Path Found! Note: We can also print the path by just popping the nodes out of the stacks and then print them in reverse order.Time Complexity : O().Auxiliary Space: O(). imdhruvgupta nirajtechi Rajput-Ji pankajsharmagfg amartyaghoshgfg shinjanpatra Algorithms-Backtracking Backtracking Data Structures Stack Data Structures Stack Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction m Coloring Problem | Backtracking-5 Hamiltonian Cycle | Backtracking-6 Backtracking to find all subsets Generate all the binary strings of N bits DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews Introduction to Data Structures Doubly Linked List | Set 1 (Introduction and Insertion)
[ { "code": null, "e": 54, "s": 26, "text": "\n06 May, 2022" }, { "code": null, "e": 681, "s": 54, "text": "Prerequisites – Recursion, Backtracking and Stack Data Structure.A Maze is given as N*M binary matrix of blocks and there is a rat initially at (0, 0) ie. maze[0][0] and the rat wants to eat food which is present at some given block in the maze (fx, fy). In a maze matrix, 0 means that the block is a dead end and 1 means that the block can be used in the path from source to destination. The rat can move in any direction (not diagonally) to any block provided the block is not a dead end. The task is to check if there exists any path so that the rat can reach the food or not. It is not needed to print the path.Examples: " }, { "code": null, "e": 968, "s": 681, "text": "Input : maze[4][5] = {\n {1, 0, 1, 1, 0},\n {1, 1, 1, 0, 1},\n {0, 1, 0, 1, 1},\n {1, 1, 1, 1, 1}\n }\n fx = 2, fy=3\nOutput : Path Found!\nThe path can be: (0, 0) -> (1, 0) -> (1, 1) -> (2, 1) -> (3, 1) -> (3, 2) -> (3, 3) -> (2, 3) " }, { "code": null, "e": 1594, "s": 970, "text": "This is the famous Rat in a Maze problem asked in many interviews that can be solved using Recursion and Backtracking. We already have discussed a Backtracking solution to this problem using recursion in Rat in a Maze | Backtracking-2. In this an iterative solution using stack is discussed.In the previous article, Recursion uses a call stack to keep the store each recursive call and then pop as the function ends. We will eliminate recursion by using our own stack to do the same thing.A node structure is used to store the (i, j) coordinates and directions explored from this node and which direction to try out next. " }, { "code": null, "e": 1612, "s": 1594, "text": "Structure Used: " }, { "code": null, "e": 1993, "s": 1612, "text": "X : x coordinate of the node Y : y coordinate of the node dir : This variable will be used to tell which all directions we have tried and which to choose next. We will try all the directions in anti-clockwise manner starting from Up. Initially it will be assigned 0. If dir=0 try Up direction.If dir=1 try left direction.If dir=2 try down direction.If dir=3 try right direction." }, { "code": null, "e": 2024, "s": 1993, "text": "X : x coordinate of the node " }, { "code": null, "e": 2055, "s": 2024, "text": "Y : y coordinate of the node " }, { "code": null, "e": 2376, "s": 2055, "text": "dir : This variable will be used to tell which all directions we have tried and which to choose next. We will try all the directions in anti-clockwise manner starting from Up. Initially it will be assigned 0. If dir=0 try Up direction.If dir=1 try left direction.If dir=2 try down direction.If dir=3 try right direction." }, { "code": null, "e": 2403, "s": 2376, "text": "If dir=0 try Up direction." }, { "code": null, "e": 2432, "s": 2403, "text": "If dir=1 try left direction." }, { "code": null, "e": 2461, "s": 2432, "text": "If dir=2 try down direction." }, { "code": null, "e": 2491, "s": 2461, "text": "If dir=3 try right direction." }, { "code": null, "e": 3597, "s": 2493, "text": "Initially, we will push a node with indexes i=0, j=0 and dir=0 into the stack. We will move to all the direction of the topmost node one by one in an anti-clockwise manner and each time as we try out a new path we will push that node (block of the maze) in the stack. We will increase dir variable of the topmost node each time so that we can try a new direction each time unless all the directions are explored ie. dir=4. If dir equals to 4 we will pop that node from the stack that means we are retracting one step back to the path where we came from.We will also maintain a visited matrix which will maintain which blocks of the maze are already used in the path or in other words present in the stack. While trying out any direction we will also check if the block of the maze is not a dead end and is not out of the maze too.We will do this while either the topmost node coordinates become equal to the food’s coordinates that means we have reached the food or the stack becomes empty which means that there is no possible path to reach the food.Below is the implementation of the above approach: " }, { "code": null, "e": 3601, "s": 3597, "text": "C++" }, { "code": null, "e": 3606, "s": 3601, "text": "Java" }, { "code": null, "e": 3609, "s": 3606, "text": "C#" }, { "code": null, "e": 3617, "s": 3609, "text": "Python3" }, { "code": null, "e": 3628, "s": 3617, "text": "Javascript" }, { "code": "// CPP program to solve Rat in a maze// problem with backtracking using stack #include <cstring>#include <iostream>#include <stack> using namespace std; #define N 4#define M 5 class node {public: int x, y; int dir; node(int i, int j) { x = i; y = j; // Initially direction // set to 0 dir = 0; }}; // maze of n*m matrixint n = N, m = M; // Coordinates of foodint fx, fy;bool visited[N][M]; bool isReachable(int maze[N][M]){ // Initially starting at (0, 0). int i = 0, j = 0; stack<node> s; node temp(i, j); s.push(temp); while (!s.empty()) { // Pop the top node and move to the // left, right, top, down or retract // back according the value of node's // dir variable. temp = s.top(); int d = temp.dir; i = temp.x, j = temp.y; // Increment the direction and // push the node in the stack again. temp.dir++; s.pop(); s.push(temp); // If we reach the Food coordinates // return true if (i == fx and j == fy) { return true; } // Checking the Up direction. if (d == 0) { if (i - 1 >= 0 and maze[i - 1][j] and visited[i - 1][j]) { node temp1(i - 1, j); visited[i - 1][j] = false; s.push(temp1); } } // Checking the left direction else if (d == 1) { if (j - 1 >= 0 and maze[i][j - 1] and visited[i][j - 1]) { node temp1(i, j - 1); visited[i][j - 1] = false; s.push(temp1); } } // Checking the down direction else if (d == 2) { if (i + 1 < n and maze[i + 1][j] and visited[i + 1][j]) { node temp1(i + 1, j); visited[i + 1][j] = false; s.push(temp1); } } // Checking the right direction else if (d == 3) { if (j + 1 < m and maze[i][j + 1] and visited[i][j + 1]) { node temp1(i, j + 1); visited[i][j + 1] = false; s.push(temp1); } } // If none of the direction can take // the rat to the Food, retract back // to the path where the rat came from. else { visited[temp.x][temp.y] = true; s.pop(); } } // If the stack is empty and // no path is found return false. return false;} // Driver codeint main(){ // Initially setting the visited // array to true (unvisited) memset(visited, true, sizeof(visited)); // Maze matrix int maze[N][M] = { { 1, 0, 1, 1, 0 }, { 1, 1, 1, 0, 1 }, { 0, 1, 0, 1, 1 }, { 1, 1, 1, 1, 1 } }; // Food coordinates fx = 2; fy = 3; if (isReachable(maze)) { cout << \"Path Found!\" << '\\n'; } else cout << \"No Path Found!\" << '\\n'; return 0;}", "e": 6764, "s": 3628, "text": null }, { "code": "// Java program to solve Rat in a maze// problem with backtracking using stackimport java.util.Stack; class Node{ private int x, y; private int dir; public Node(int i, int j) { this.x = i; this.y = j; // default value for direction set to 0 (Up) this.dir = 0; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getDir() { return dir; } public void setDir(int dir) { this.dir = dir; }} public class RatInMaze{ private static final int N = 4; private static final int M = 5; // maze of n*m matrix int n = N, m = M; private static boolean[][] visited = new boolean[N][M]; // Driver code public static void main(String[] args) { // Initially setting the visited // array to true (unvisited) setVisited(true); // Maze matrix int maze[][] = {{ 1, 0, 1, 1, 0 }, { 1, 1, 1, 0, 1 }, { 0, 1, 0, 1, 1 }, { 1, 1, 1, 1, 1 } }; if (isReachable(maze)) { System.out.println(\"Path Found!\\n\"); } else System.out.println(\"No Path Found!\\n\"); } private static void setVisited(boolean b) { for (int i = 0; i < visited.length; i++) { for (int j = 0; j < visited[i].length; j++) { visited[i][j] = b; } } } private static boolean isReachable(int maze[][]) { // Initially starting at (0, 0). int i = 0, j = 0; // Food coordinates // Coordinates of food int fx, fy; fx = 2; fy = 3; Stack<Node> s = new Stack<Node>(); Node temp = new Node(i, j); s.push(temp); while (!s.empty()) { // Pop the top node and move to the // left, right, top, down or retract // back according the value of node's // dir variable. temp = s.peek(); int d = temp.getDir(); i = temp.getX(); j = temp.getY(); // Increment the direction and // push the node in the stack again. temp.setDir(temp.getDir() + 1); s.pop(); s.push(temp); // If we reach the Food coordinates // return true if (i == fx && j == fy) { return true; } if (d == 0) { // Checking the Up direction. if (i - 1 >= 0 && maze[i - 1][j] == 1 && visited[i - 1][j]) { Node temp1 = new Node(i - 1, j); visited[i - 1][j] = false; s.push(temp1); } } else if (d == 1) { // Checking the left direction if (j - 1 >= 0 && maze[i][j - 1] == 1 && visited[i][j - 1]) { Node temp1 = new Node(i, j - 1); visited[i][j - 1] = false; s.push(temp1); } } else if (d == 2) { // Checking the down direction if (i + 1 < N && maze[i + 1][j] == 1 && visited[i + 1][j]) { Node temp1 = new Node(i + 1, j); visited[i + 1][j] = false; s.push(temp1); } } else if (d == 3) { // Checking the right direction if (j + 1 < M && maze[i][j + 1] == 1 && visited[i][j + 1]) { Node temp1 = new Node(i, j + 1); visited[i][j + 1] = false; s.push(temp1); } } // If none of the direction can take // the rat to the Food, retract back // to the path where the rat came from. else { visited[temp.getX()][temp.getY()] = true; s.pop(); } } // If the stack is empty and // no path is found return false. return false; }} // This code is contributed by nirajtechi", "e": 11327, "s": 6764, "text": null }, { "code": "// C# program to solve Rat in a maze// problem with backtracking using stackusing System;using System.Collections.Generic; public class Node{ private int x, y; private int dir; public Node(int i, int j) { this.x = i; this.y = j; // default value for direction set to 0 (Up) this.dir = 0; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getDir() { return dir; } public void setDir(int dir) { this.dir = dir; }} public class RatInMaze{ private static readonly int N = 4; private static readonly int M = 5; // maze of n*m matrix int n = N, m = M; private static bool [,]visited = new bool[N,M]; // Driver code public static void Main(String[] args) { // Initially setting the visited // array to true (unvisited) setVisited(true); // Maze matrix int [,]maze = {{ 1, 0, 1, 1, 0 }, { 1, 1, 1, 0, 1 }, { 0, 1, 0, 1, 1 }, { 1, 1, 1, 1, 1 } }; if (isReachable(maze)) { Console.WriteLine(\"Path Found!\\n\"); } else Console.WriteLine(\"No Path Found!\\n\"); } private static void setVisited(bool b) { for (int i = 0; i < visited.GetLength(0); i++) { for (int j = 0; j < visited.GetLength(0); j++) { visited[i,j] = b; } } } private static bool isReachable(int [,]maze) { // Initially starting at (0, 0). int i = 0, j = 0; // Food coordinates // Coordinates of food int fx, fy; fx = 2; fy = 3; Stack<Node> s = new Stack<Node>(); Node temp = new Node(i, j); s.Push(temp); while (s.Count!=0) { // Pop the top node and move to the // left, right, top, down or retract // back according the value of node's // dir variable. temp = s.Peek(); int d = temp.getDir(); i = temp.getX(); j = temp.getY(); // Increment the direction and // push the node in the stack again. temp.setDir(temp.getDir() + 1); s.Pop(); s.Push(temp); // If we reach the Food coordinates // return true if (i == fx && j == fy) { return true; } if (d == 0) { // Checking the Up direction. if (i - 1 >= 0 && maze[i - 1,j] == 1 && visited[i - 1,j]) { Node temp1 = new Node(i - 1, j); visited[i - 1,j] = false; s.Push(temp1); } } else if (d == 1) { // Checking the left direction if (j - 1 >= 0 && maze[i,j - 1] == 1 && visited[i,j - 1]) { Node temp1 = new Node(i, j - 1); visited[i,j - 1] = false; s.Push(temp1); } } else if (d == 2) { // Checking the down direction if (i + 1 < N && maze[i + 1,j] == 1 && visited[i + 1,j]) { Node temp1 = new Node(i + 1, j); visited[i + 1,j] = false; s.Push(temp1); } } else if (d == 3) { // Checking the right direction if (j + 1 < M && maze[i,j + 1] == 1 && visited[i,j + 1]) { Node temp1 = new Node(i, j + 1); visited[i,j + 1] = false; s.Push(temp1); } } // If none of the direction can take // the rat to the Food, retract back // to the path where the rat came from. else { visited[temp.getX(),temp.getY()] = true; s.Pop(); } } // If the stack is empty and // no path is found return false. return false; }} // This code contributed by Rajput-Ji", "e": 15892, "s": 11327, "text": null }, { "code": "# CPP program to solve Rat in a maze# problem with backtracking using stack N=4M=5 class node: def __init__(self,i,j): self.x=i self.y=j self.dirn=0 # maze of n*m matrixn = N; m = M # Coordinates of foodfx=0; fy=0visited=[[True]*N for _ in range(M)] def isReachable(maze): # Initially starting at (0, 0). i = 0; j = 0 s=[] temp=node(i, j) s.append(temp) while s: # Pop the top node and move to the # left, right, top, down or retract # back according the value of node's # dirn variable. temp = s.pop() d = temp.dirn i = temp.x; j = temp.y # Increment the direction and # push the node in the stack again. temp.dirn+=1 s.append(temp) # If we reach the Food coordinates # return true if (i == fx and j == fy): return True # Checking the Up direction. if (d == 0): if (i - 1 >= 0 and maze[i - 1][j] and visited[i - 1][j]): temp1=node(i - 1, j) visited[i - 1][j] = False s.append(temp1) # Checking the left direction elif (d == 1): if(j - 1 >= 0 and maze[i][j - 1] and visited[i][j - 1]): temp1=node(i, j - 1) visited[i][j - 1] = False s.append(temp1) # Checking the down direction elif (d == 2): if(i + 1 < n and maze[i + 1][j] and visited[i + 1][j]): temp1=node(i + 1, j) visited[i + 1][j] = False s.append(temp1) # Checking the right direction elif (d == 3): if (j + 1 < m and maze[i][j + 1] and visited[i][j + 1]): temp1=node(i, j + 1) visited[i][j + 1] = False s.append(temp1) # If none of the direction can take # the rat to the Food, retract back # to the path where the rat came from. else: visited[temp.x][temp.y] = True s.pop() # If the stack is empty and # no path is found return false. return False # Driver codeif __name__ == '__main__': # Initially setting the visited # array to true (unvisited) # Maze matrix maze = [ [ 1, 0, 1, 1, 0 ], [ 1, 1, 1, 0, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 1, 1, 1, 1 ] ] # Food coordinates fx = 2 fy = 3 if (isReachable(maze)): print(\"Path Found!\") else: print(\"No Path Found!\")", "e": 18442, "s": 15892, "text": null }, { "code": "<script> // JavaScript program to solve Rat in a maze// problem with backtracking using stack const N = 4const M = 5 class node{ constructor(i, j){ this.x = i this.y = j this.dirn = 0 }} // maze of n*m matrixlet n = N, m = M // Coordinates of foodlet fx = 0, fy = 0let visited = new Array(N);for(let i = 0; i < N; i++){ visited[i] = new Array(M).fill(true);} function isReachable(maze){ // Initially starting at (0, 0). let i = 0, j = 0 let s=[] let temp=new node(i, j) s.push(temp) while(s.length>0){ // Pop the top node && move to the // left, right, top, down or retract // back according the value of node's // dirn variable. temp = s[s.length - 1] s.pop() let d = temp.dirn i = temp.x, j = temp.y // Increment the direction && // push the node in the stack again. temp.dirn+=1 s.push(temp) // If we reach the Food coordinates // return true if (i == fx && j == fy) return true // Checking the Up direction. if (d == 0){ if (i - 1 >= 0 && maze[i - 1][j] && visited[i - 1][j]){ let temp1=new node(i - 1, j) visited[i - 1][j] = false s.push(temp1) } } // Checking the left direction else if (d == 1){ if(j - 1 >= 0 && maze[i][j - 1] && visited[i][j - 1]){ let temp1=new node(i, j - 1) visited[i][j - 1] = false s.push(temp1) } } // Checking the down direction else if (d == 2){ if(i + 1 < n && maze[i + 1][j] && visited[i + 1][j]){ let temp1=new node(i + 1, j) visited[i + 1][j] = false s.push(temp1) } } // Checking the right direction else if (d == 3){ if (j + 1 < m && maze[i][j + 1] && visited[i][j + 1]){ let temp1=new node(i, j + 1) visited[i][j + 1] = false s.push(temp1) } } // If none of the direction can take // the rat to the Food, retract back // to the path where the rat came from. else{ visited[temp.x][temp.y] = true s.pop() } } // If the stack is empty && // no path is found return false. return false} // Driver code // Initially setting the visited// array to true (unvisited) // Maze matrixlet maze = [ [ 1, 0, 1, 1, 0 ], [ 1, 1, 1, 0, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 1, 1, 1, 1 ]] // Food coordinatesfx = 2fy = 3 if (isReachable(maze)) document.write(\"Path Found!\",\"</br>\")else document.write(\"No Path Found!\",\"</br>\") // This code is contributed by shinjanpatra </script>", "e": 21265, "s": 18442, "text": null }, { "code": null, "e": 21277, "s": 21265, "text": "Path Found!" }, { "code": null, "e": 21438, "s": 21279, "text": "Note: We can also print the path by just popping the nodes out of the stacks and then print them in reverse order.Time Complexity : O().Auxiliary Space: O(). " }, { "code": null, "e": 21451, "s": 21438, "text": "imdhruvgupta" }, { "code": null, "e": 21462, "s": 21451, "text": "nirajtechi" }, { "code": null, "e": 21472, "s": 21462, "text": "Rajput-Ji" }, { "code": null, "e": 21488, "s": 21472, "text": "pankajsharmagfg" }, { "code": null, "e": 21504, "s": 21488, "text": "amartyaghoshgfg" }, { "code": null, "e": 21517, "s": 21504, "text": "shinjanpatra" }, { "code": null, "e": 21541, "s": 21517, "text": "Algorithms-Backtracking" }, { "code": null, "e": 21554, "s": 21541, "text": "Backtracking" }, { "code": null, "e": 21570, "s": 21554, "text": "Data Structures" }, { "code": null, "e": 21576, "s": 21570, "text": "Stack" }, { "code": null, "e": 21592, "s": 21576, "text": "Data Structures" }, { "code": null, "e": 21598, "s": 21592, "text": "Stack" }, { "code": null, "e": 21611, "s": 21598, "text": "Backtracking" }, { "code": null, "e": 21709, "s": 21611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 21737, "s": 21709, "text": "Backtracking | Introduction" }, { "code": null, "e": 21773, "s": 21737, "text": "m Coloring Problem | Backtracking-5" }, { "code": null, "e": 21808, "s": 21773, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 21841, "s": 21808, "text": "Backtracking to find all subsets" }, { "code": null, "e": 21883, "s": 21841, "text": "Generate all the binary strings of N bits" }, { "code": null, "e": 21908, "s": 21883, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 21957, "s": 21908, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 22001, "s": 21957, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 22033, "s": 22001, "text": "Introduction to Data Structures" } ]
randint() Function in Python
25 May, 2022 randint() is an inbuilt function of the random module in Python3. The random module gives access to various useful functions and one of them being able to generate random numbers, which is randint(). Syntax : randint(start, end) Parameters : (start, end) : Both of them must be integer type values. Returns : A random integer in range [start, end] including the end points. Errors and Exceptions : ValueError : Returns a ValueError when floating point values are passed as parameters. TypeError : Returns a TypeError when anything other than numeric values are passed as parameters. Code #1 : Python3 # Python3 program explaining work# of randint() function # imports random moduleimport random # Generates a random number between# a given positive ranger1 = random.randint(0, 10)print("Random number between 0 and 10 is % s" % (r1)) # Generates a random number between# two given negative ranger2 = random.randint(-10, -1)print("Random number between -10 and -1 is % d" % (r2)) # Generates a random number between# a positive and a negative ranger3 = random.randint(-5, 5)print("Random number between -5 and 5 is % d" % (r3)) Output : Random number between 0 and 10 is 5 Random number between -10 and -1 is -7 Random number between -5 and 5 is 2 Code #2 : Program demonstrating the ValueError. Python3 # imports random moduleimport random '''If we pass floating point values asparameters in the randint() function''' r1 = random.randint(1.23, 9.34)print(r1) Output : Traceback (most recent call last): File "/home/f813370b9ea61dd5d55d7dadc8ed5171.py", line 6, in r1=random.randint(1.23, 9.34) File "/usr/lib/python3.5/random.py", line 218, in randint return self.randrange(a, b+1) File "/usr/lib/python3.5/random.py", line 182, in randrange raise ValueError("non-integer arg 1 for randrange()") ValueError: non-integer arg 1 for randrange() Code #3 : Program demonstrating the TypeError. Python3 # imports randomimport random '''If we pass string or character literals asparameters in the randint() function''' r2 = random.randint('a', 'z')print(r2) Output : Traceback (most recent call last): File "/home/fb805b21fea0e29c6a65f62b99998953.py", line 5, in r2=random.randint('a', 'z') File "/usr/lib/python3.5/random.py", line 218, in randint return self.randrange(a, b+1) TypeError: Can't convert 'int' object to str implicitly Applications : The randint() function can be used to simulate a lucky draw situation. Let’s say User has participated in a lucky draw competition. The user gets three chances to guess the number between 1 and 10. If guess is correct user wins, else loses the competition. Python3 # importing randint function# from random modulefrom random import randint # Function which generates a new# random number everytime it executesdef generator(): return randint(1, 10) # Function takes user input and returns# true or false depending whether the# user wins the lucky draw!def rand_guess(): # calls generator() which returns a # random integer between 1 and 10 random_number = generator() # defining the number of # guesses the user gets guess_left = 3 # Setting a flag variable to check # the win-condition for user flag = 0 # looping the number of times # the user gets chances while guess_left > 0: # Taking a input from the user guess = int(input("Pick your number to " "enter the lucky draw\n")) # checking whether user's guess # matches the generated win-condition if guess == random_number: # setting flag as 1 if user guesses # correctly and then loop is broken flag = 1 break else: # If user's choice doesn't match # win-condition then it is printed print("Wrong Guess!!") # Decrementing number of # guesses left by 1 guess_left -= 1 # If win-condition is satisfied then, # the function rand_guess returns True if flag is 1: return True # Else the function returns False else: return False # Driver codeif __name__ == '__main__': if rand_guess() is True: print("Congrats!! You Win.") else : print("Sorry, You Lost!") Output : Pick your number to enter the lucky draw 8 Wrong Guess!! Pick your number to enter the lucky draw 9 Wrong Guess!! Pick your number to enter the lucky draw 0 Congrats!! You Win. kaladarchowdary surinderdawra388 Python-Built-in-functions python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python How to iterate through Excel rows in Python? Read JSON file using Python Python map() function Rotate axis tick labels in Seaborn and Matplotlib Enumerate() in Python Adding new column to existing DataFrame in Pandas Deque in Python Taking input in Python Queue in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n25 May, 2022" }, { "code": null, "e": 264, "s": 54, "text": "randint() is an inbuilt function of the random module in Python3. The random module gives access to various useful functions and one of them being able to generate random numbers, which is randint(). Syntax : " }, { "code": null, "e": 284, "s": 264, "text": "randint(start, end)" }, { "code": null, "e": 298, "s": 284, "text": "Parameters : " }, { "code": null, "e": 355, "s": 298, "text": "(start, end) : Both of them must be integer type values." }, { "code": null, "e": 366, "s": 355, "text": "Returns : " }, { "code": null, "e": 431, "s": 366, "text": "A random integer in range [start, end] including the end points." }, { "code": null, "e": 455, "s": 431, "text": "Errors and Exceptions :" }, { "code": null, "e": 667, "s": 455, "text": "ValueError : Returns a ValueError when floating\n point values are passed as parameters.\n\nTypeError : Returns a TypeError when anything other than \n numeric values are passed as parameters." }, { "code": null, "e": 680, "s": 667, "text": " Code #1 : " }, { "code": null, "e": 688, "s": 680, "text": "Python3" }, { "code": "# Python3 program explaining work# of randint() function # imports random moduleimport random # Generates a random number between# a given positive ranger1 = random.randint(0, 10)print(\"Random number between 0 and 10 is % s\" % (r1)) # Generates a random number between# two given negative ranger2 = random.randint(-10, -1)print(\"Random number between -10 and -1 is % d\" % (r2)) # Generates a random number between# a positive and a negative ranger3 = random.randint(-5, 5)print(\"Random number between -5 and 5 is % d\" % (r3))", "e": 1214, "s": 688, "text": null }, { "code": null, "e": 1223, "s": 1214, "text": "Output :" }, { "code": null, "e": 1334, "s": 1223, "text": "Random number between 0 and 10 is 5\nRandom number between -10 and -1 is -7\nRandom number between -5 and 5 is 2" }, { "code": null, "e": 1385, "s": 1334, "text": " Code #2 : Program demonstrating the ValueError. " }, { "code": null, "e": 1393, "s": 1385, "text": "Python3" }, { "code": "# imports random moduleimport random '''If we pass floating point values asparameters in the randint() function''' r1 = random.randint(1.23, 9.34)print(r1)", "e": 1549, "s": 1393, "text": null }, { "code": null, "e": 1558, "s": 1549, "text": "Output :" }, { "code": null, "e": 1951, "s": 1558, "text": "Traceback (most recent call last):\n File \"/home/f813370b9ea61dd5d55d7dadc8ed5171.py\", line 6, in \n r1=random.randint(1.23, 9.34)\n File \"/usr/lib/python3.5/random.py\", line 218, in randint\n return self.randrange(a, b+1)\n File \"/usr/lib/python3.5/random.py\", line 182, in randrange\n raise ValueError(\"non-integer arg 1 for randrange()\")\nValueError: non-integer arg 1 for randrange()" }, { "code": null, "e": 2001, "s": 1951, "text": " Code #3 : Program demonstrating the TypeError. " }, { "code": null, "e": 2009, "s": 2001, "text": "Python3" }, { "code": "# imports randomimport random '''If we pass string or character literals asparameters in the randint() function''' r2 = random.randint('a', 'z')print(r2)", "e": 2163, "s": 2009, "text": null }, { "code": null, "e": 2173, "s": 2163, "text": "Output : " }, { "code": null, "e": 2454, "s": 2173, "text": "Traceback (most recent call last):\n File \"/home/fb805b21fea0e29c6a65f62b99998953.py\", line 5, in \n r2=random.randint('a', 'z')\n File \"/usr/lib/python3.5/random.py\", line 218, in randint\n return self.randrange(a, b+1)\nTypeError: Can't convert 'int' object to str implicitly" }, { "code": null, "e": 2729, "s": 2454, "text": " Applications : The randint() function can be used to simulate a lucky draw situation. Let’s say User has participated in a lucky draw competition. The user gets three chances to guess the number between 1 and 10. If guess is correct user wins, else loses the competition. " }, { "code": null, "e": 2737, "s": 2729, "text": "Python3" }, { "code": "# importing randint function# from random modulefrom random import randint # Function which generates a new# random number everytime it executesdef generator(): return randint(1, 10) # Function takes user input and returns# true or false depending whether the# user wins the lucky draw!def rand_guess(): # calls generator() which returns a # random integer between 1 and 10 random_number = generator() # defining the number of # guesses the user gets guess_left = 3 # Setting a flag variable to check # the win-condition for user flag = 0 # looping the number of times # the user gets chances while guess_left > 0: # Taking a input from the user guess = int(input(\"Pick your number to \" \"enter the lucky draw\\n\")) # checking whether user's guess # matches the generated win-condition if guess == random_number: # setting flag as 1 if user guesses # correctly and then loop is broken flag = 1 break else: # If user's choice doesn't match # win-condition then it is printed print(\"Wrong Guess!!\") # Decrementing number of # guesses left by 1 guess_left -= 1 # If win-condition is satisfied then, # the function rand_guess returns True if flag is 1: return True # Else the function returns False else: return False # Driver codeif __name__ == '__main__': if rand_guess() is True: print(\"Congrats!! You Win.\") else : print(\"Sorry, You Lost!\")", "e": 4365, "s": 2737, "text": null }, { "code": null, "e": 4375, "s": 4365, "text": "Output : " }, { "code": null, "e": 4552, "s": 4375, "text": "Pick your number to enter the lucky draw\n8\nWrong Guess!!\nPick your number to enter the lucky draw\n9\nWrong Guess!!\nPick your number to enter the lucky draw\n0\nCongrats!! You Win." }, { "code": null, "e": 4568, "s": 4552, "text": "kaladarchowdary" }, { "code": null, "e": 4585, "s": 4568, "text": "surinderdawra388" }, { "code": null, "e": 4611, "s": 4585, "text": "Python-Built-in-functions" }, { "code": null, "e": 4626, "s": 4611, "text": "python-modules" }, { "code": null, "e": 4633, "s": 4626, "text": "Python" }, { "code": null, "e": 4731, "s": 4633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4761, "s": 4731, "text": "Iterate over a list in Python" }, { "code": null, "e": 4806, "s": 4761, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 4834, "s": 4806, "text": "Read JSON file using Python" }, { "code": null, "e": 4856, "s": 4834, "text": "Python map() function" }, { "code": null, "e": 4906, "s": 4856, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 4928, "s": 4906, "text": "Enumerate() in Python" }, { "code": null, "e": 4978, "s": 4928, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4994, "s": 4978, "text": "Deque in Python" }, { "code": null, "e": 5017, "s": 4994, "text": "Taking input in Python" } ]
Collection isEmpty() method in Java with Examples
29 Nov, 2018 The isEmpty() of java.util.Collection interface is used to check if the Collection upon which it is called is empty or not. This method does not take any parameter and does not returns any value. Syntax: Collection.isEmpty() Parameters: This method do not accept any parameter Return Value: This method does not return any value. Below examples illustrate the Collection isEmpty() method: Example 1: Using LinkedList Class // Java code to illustrate boolean isEmpty() method import java.io.*;import java.util.*; public class GFG { public static void main(String args[]) { // creating an empty LinkedList Collection<String> list = new LinkedList<String>(); // use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); // Output the present list System.out.println("The list is: " + list); // Check if list is empty // using isEmpty() method System.out.println("Is the LinkedList empty: " + list.isEmpty()); // Clearing the LinkedList list.clear(); // printing the new list System.out.println("The new List is: " + list); // Check if list is empty // using isEmpty() method System.out.println("Is the LinkedList empty: " + list.isEmpty()); }} The list is: [Geeks, for, Geeks] Is the LinkedList empty: false The new List is: [] Is the LinkedList empty: true Example 2: Using ArrayDeque Class // Java code to illustrate isEmpty() method import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Collection<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("4"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("ArrayDeque: " + de_que); // Check if ArrayDeque is empty // using isEmpty() method System.out.println("Is the ArrayDeque empty: " + de_que.isEmpty()); // Clearing the ArrayDeque de_que.clear(); // printing the new ArrayDeque System.out.println("The new ArrayDeque is: " + de_que); // Check if ArrayDeque is empty // using isEmpty() method System.out.println("Is the ArrayDeque empty: " + de_que.isEmpty()); }} ArrayDeque: [Welcome, To, Geeks, 4, Geeks] Is the ArrayDeque empty: false The new ArrayDeque is: [] Is the ArrayDeque empty: true Example 3: Using ArrayList Class // Java code to illustrate isEmpty() method import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String[] args) { // create an empty array list with an initial capacity Collection<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // prints all the elements available in list System.out.println("ArrayList: " + arrlist); // Check if list is empty // using isEmpty() method System.out.println("Is the ArrayList empty: " + arrlist.isEmpty()); // Clearing the ArrayList arrlist.clear(); // printing the new ArrayList System.out.println("The new ArrayList is: " + arrlist); // Check if ArrayList is empty // using isEmpty() method System.out.println("Is the ArrayList empty: " + arrlist.isEmpty()); }} ArrayList: [15, 20, 25] Is the ArrayList empty: false The new ArrayList is: [] Is the ArrayList empty: true Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Collection.html#isEmpty– Java - util package Java-Collections Java-Functions Java Java Java-Collections 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": "\n29 Nov, 2018" }, { "code": null, "e": 224, "s": 28, "text": "The isEmpty() of java.util.Collection interface is used to check if the Collection upon which it is called is empty or not. This method does not take any parameter and does not returns any value." }, { "code": null, "e": 232, "s": 224, "text": "Syntax:" }, { "code": null, "e": 254, "s": 232, "text": "Collection.isEmpty()\n" }, { "code": null, "e": 306, "s": 254, "text": "Parameters: This method do not accept any parameter" }, { "code": null, "e": 359, "s": 306, "text": "Return Value: This method does not return any value." }, { "code": null, "e": 418, "s": 359, "text": "Below examples illustrate the Collection isEmpty() method:" }, { "code": null, "e": 452, "s": 418, "text": "Example 1: Using LinkedList Class" }, { "code": "// Java code to illustrate boolean isEmpty() method import java.io.*;import java.util.*; public class GFG { public static void main(String args[]) { // creating an empty LinkedList Collection<String> list = new LinkedList<String>(); // use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); // Output the present list System.out.println(\"The list is: \" + list); // Check if list is empty // using isEmpty() method System.out.println(\"Is the LinkedList empty: \" + list.isEmpty()); // Clearing the LinkedList list.clear(); // printing the new list System.out.println(\"The new List is: \" + list); // Check if list is empty // using isEmpty() method System.out.println(\"Is the LinkedList empty: \" + list.isEmpty()); }}", "e": 1415, "s": 452, "text": null }, { "code": null, "e": 1530, "s": 1415, "text": "The list is: [Geeks, for, Geeks]\nIs the LinkedList empty: false\nThe new List is: []\nIs the LinkedList empty: true\n" }, { "code": null, "e": 1564, "s": 1530, "text": "Example 2: Using ArrayDeque Class" }, { "code": "// Java code to illustrate isEmpty() method import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Collection<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"4\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"ArrayDeque: \" + de_que); // Check if ArrayDeque is empty // using isEmpty() method System.out.println(\"Is the ArrayDeque empty: \" + de_que.isEmpty()); // Clearing the ArrayDeque de_que.clear(); // printing the new ArrayDeque System.out.println(\"The new ArrayDeque is: \" + de_que); // Check if ArrayDeque is empty // using isEmpty() method System.out.println(\"Is the ArrayDeque empty: \" + de_que.isEmpty()); }}", "e": 2636, "s": 1564, "text": null }, { "code": null, "e": 2767, "s": 2636, "text": "ArrayDeque: [Welcome, To, Geeks, 4, Geeks]\nIs the ArrayDeque empty: false\nThe new ArrayDeque is: []\nIs the ArrayDeque empty: true\n" }, { "code": null, "e": 2800, "s": 2767, "text": "Example 3: Using ArrayList Class" }, { "code": "// Java code to illustrate isEmpty() method import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String[] args) { // create an empty array list with an initial capacity Collection<Integer> arrlist = new ArrayList<Integer>(5); // use add() method to add elements in the list arrlist.add(15); arrlist.add(20); arrlist.add(25); // prints all the elements available in list System.out.println(\"ArrayList: \" + arrlist); // Check if list is empty // using isEmpty() method System.out.println(\"Is the ArrayList empty: \" + arrlist.isEmpty()); // Clearing the ArrayList arrlist.clear(); // printing the new ArrayList System.out.println(\"The new ArrayList is: \" + arrlist); // Check if ArrayList is empty // using isEmpty() method System.out.println(\"Is the ArrayList empty: \" + arrlist.isEmpty()); }}", "e": 3869, "s": 2800, "text": null }, { "code": null, "e": 3978, "s": 3869, "text": "ArrayList: [15, 20, 25]\nIs the ArrayList empty: false\nThe new ArrayList is: []\nIs the ArrayList empty: true\n" }, { "code": null, "e": 4066, "s": 3978, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Collection.html#isEmpty–" }, { "code": null, "e": 4086, "s": 4066, "text": "Java - util package" }, { "code": null, "e": 4103, "s": 4086, "text": "Java-Collections" }, { "code": null, "e": 4118, "s": 4103, "text": "Java-Functions" }, { "code": null, "e": 4123, "s": 4118, "text": "Java" }, { "code": null, "e": 4128, "s": 4123, "text": "Java" }, { "code": null, "e": 4145, "s": 4128, "text": "Java-Collections" }, { "code": null, "e": 4243, "s": 4145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4258, "s": 4243, "text": "Stream In Java" }, { "code": null, "e": 4279, "s": 4258, "text": "Introduction to Java" }, { "code": null, "e": 4300, "s": 4279, "text": "Constructors in Java" }, { "code": null, "e": 4319, "s": 4300, "text": "Exceptions in Java" }, { "code": null, "e": 4336, "s": 4319, "text": "Generics in Java" }, { "code": null, "e": 4366, "s": 4336, "text": "Functional Interfaces in Java" }, { "code": null, "e": 4392, "s": 4366, "text": "Java Programming Examples" }, { "code": null, "e": 4408, "s": 4392, "text": "Strings in Java" }, { "code": null, "e": 4445, "s": 4408, "text": "Differences between JDK, JRE and JVM" } ]
Image Compression using Huffman Coding
21 Nov, 2019 Huffman coding is one of the basic compression methods, that have proven useful in image and video compression standards. When applying Huffman encoding technique on an Image, the source symbols can be either pixel intensities of the Image, or the output of an intensity mapping function. Prerequisites : Huffman Coding | File Handling The first step of Huffman coding technique is to reduce the input image to a ordered histogram, where the probability of occurrence of a certain pixel intensity value is as prob_pixel = numpix/totalnum where numpix is the number of occurrence of a pixel with a certain intensity value and totalnum is the total number of pixels in the input Image. Let us take a 8 X 8 Image The pixel intensity values are :This image contains 46 distinct pixel intensity values, hence we will have 46 unique Huffman code words. It is evident that, not all pixel intensity values may be present in the image and hence will not have non-zero probability of occurrence. From here on, the pixel intensity values in the input Image will be addressed as leaf nodes. Now, there are 2 essential steps to build a Huffman Tree : Build a Huffman Tree :Combine the two lowest probability leaf nodes into a new node.Replace the two leaf nodes by the new node and sort the nodes according to the new probability values.Continue the steps (a) and (b) until we get a single node with probability value 1.0. We will call this node as rootBacktrack from the root, assigning ‘0’ or ‘1’ to each intermediate node, till we reach the leaf nodes Build a Huffman Tree : Combine the two lowest probability leaf nodes into a new node.Replace the two leaf nodes by the new node and sort the nodes according to the new probability values.Continue the steps (a) and (b) until we get a single node with probability value 1.0. We will call this node as root Combine the two lowest probability leaf nodes into a new node. Replace the two leaf nodes by the new node and sort the nodes according to the new probability values. Continue the steps (a) and (b) until we get a single node with probability value 1.0. We will call this node as root Backtrack from the root, assigning ‘0’ or ‘1’ to each intermediate node, till we reach the leaf nodes In this example, we will assign ‘0’ to the left child node and ‘1’ to the right one. Now, let’s look into the implementation :Step 1 :Read the Image into a 2D array(image)If the Image is in .bmp format, then the Image can be read into the 2D array, by using this code given in this link here. int i, j;char filename[] = "Input_Image.bmp";int data = 0, offset, bpp = 0, width, height;long bmpsize = 0, bmpdataoff = 0;int** image;int temp = 0; // Reading the BMP FileFILE* image_file;image_file = fopen(filename, "rb");if (image_file == NULL){ printf("Error Opening File!!"); exit(1);}else { // Set file position of the // stream to the beginning // Contains file signature // or ID "BM" offset = 0; // Set offset to 2, which // contains size of BMP File offset = 2; fseek(image_file, offset, SEEK_SET); // Getting size of BMP File fread(&bmpsize, 4, 1, image_file); // Getting offset where the // pixel array starts // Since the information // is at offset 10 from // the start, as given // in BMP Header offset = 10; fseek(image_file, offset, SEEK_SET); // Bitmap data offset fread(&bmpdataoff, 4, 1, image_file); // Getting height and width of the image // Width is stored at offset 18 and height // at offset 22, each of 4 bytes fseek(image_file, 18, SEEK_SET); fread(&width, 4, 1, image_file); fread(&height, 4, 1, image_file); // Number of bits per pixel fseek(image_file, 2, SEEK_CUR); fread(&bpp, 2, 1, image_file); // Setting offset to start of pixel data fseek(image_file, bmpdataoff, SEEK_SET); // Creating Image array image = (int**)malloc(height * sizeof(int*)); for (i = 0; i < height; i++) { image[i] = (int*)malloc(width * sizeof(int)); } // int image[height][width] // can also be done // Number of bytes in the // Image pixel array int numbytes = (bmpsize - bmpdataoff) / 3; // Reading the BMP File // into Image Array for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { fread(&temp, 3, 1, image_file); // the Image is a // 24-bit BMP Image temp = temp & 0x0000FF; image[i][j] = temp; } }} Create a Histogram of the pixel intensity values present in the Image // Creating the Histogramint hist[256]; for (i = 0; i < 256; i++) hist[i] = 0; for (i = 0; i < height; i++) for (j = 0; j < width; j++) hist[image[i][j]] += 1; Find the number of pixel intensity values having non-zero probability of occurrenceSince, the values of pixel intensities range from 0 to 255, and not all pixel intensity values may be present in the image (as evident from the histogram and also the image matrix) and hence will not have non-zero probability of occurrence. Also another purpose this step serves, is that the number of pixel intensity values having non-zero probability values will give us the number of leaf nodes in the Image. // Finding number of // non-zero occurrencesint nodes = 0;for (i = 0; i < 256; i++) { if (hist[i] != 0) nodes += 1;} Calculating the maximum length of Huffman code wordsAs shown by Y.S.Abu-Mostafa and R.J.McEliece in their paper “Maximal codeword lengths in Huffman codes”, that, If , then in any efficient prefix code for a source whose least probability is p, the longest codeword length is at most K & If , there exists a source whose smallest probability is p, and which has a Huffman code whose longest word has length K. If , there exists such a source for which every optimal code has a longest word of length K.Here, is the Fibonacci number. Gallager [1] noted that every Huffman tree is efficient, but in fact it is easy to see more generally that every optimal tree is efficient Fibonacci Series is : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... In our example, lowest probability(p) is 0.015625 Hence, 1/p = 64 For K = 9, F(K+2) = F(11) = 55 F(K+3) = F(12) = 89 Therefore, 1/F(K+3) < p < 1/F(K+2) Hence optimal length of code is K=9 // Calculating max length // of Huffman code wordi = 0;while ((1 / p) < fib(i)) i++;int maxcodelen = i - 3; // Function for getting Fibonacci// numbers defined outside mainint fib(int n){ if (n <= 1) return n; return fib(n - 1) + fib(n - 2);} Step 2Define a struct which will contain the pixel intensity values(pix), their corresponding probabilities(freq), the pointer to the left(*left) and right(*right) child nodes and also the string array for the Huffman code word(code). These structs is defined inside main(), so as to use the maximum length of code(maxcodelen) to declare the code array field of the struct pixfreq // Defining Structures pixfreqstruct pixfreq { int pix; float freq; struct pixfreq *left, *right; char code[maxcodelen];}; Step 3Define another Struct which will contain the pixel intensity values(pix), their corresponding probabilities(freq) and an additional field, which will be used for storing the position of new generated nodes(arrloc). // Defining Structures huffcodestruct huffcode { int pix, arrloc; float freq;}; Step 4Declaring an array of structs. Each element of the array corresponds to a node in the Huffman Tree. // Declaring structsstruct pixfreq* pix_freq;struct huffcode* huffcodes; Why use two struct arrays? Initially, the struct array pix_freq, as well as the struct array huffcodes will only contain the information of all the leaf nodes in the Huffman Tree. The struct array pix_freq will be used to store all the nodes of the Huffman Tree and the array huffcodes will be used as the updated (and sorted) tree. Remember that, only huffcodes will be sorted in each iteration, and not pix_freq The new nodes created by combining two nodes of lowest frequency, in each iteration, will be appended to the end of the pix_freq array, and also to huffcodes array. But the array huffcodes will be sorted again according to the probability of occurrence, after the new node is added to it. The position of the new node in the array pix_freq will be stored in the arrloc field of the struct huffcode.The arrloc field will be used when assigning the pointer to the left and right child of a new node. Step 4 continued... Now, if there are N number of leaf nodes, the total number of nodes in the whole Huffman Tree will be equal to 2N-1 And after two nodes are combined and replaced by the new parent node, the number of nodes decreases by 1 at each iteration. Hence, it is sufficient to have a length of nodes for the array huffcodes, which will be used as the updated and sorted Huffman nodes. int totalnodes = 2 * nodes - 1;pix_freq = (struct pixfreq*)malloc(sizeof(struct pixfreq) * totalnodes);huffcodes = (struct huffcode*)malloc(sizeof(struct huffcode) * nodes); Step 5Initialize the two arrays pix_freq and huffcodes with information of the leaf nodes. j = 0;int totpix = height * width;float tempprob;for (i = 0; i < 256; i++) { if (hist[i] != 0) { // pixel intensity value huffcodes[j].pix = i; pix_freq[j].pix = i; // location of the node // in the pix_freq array huffcodes[j].arrloc = j; // probability of occurrence tempprob = (float)hist[i] / (float)totpix; pix_freq[j].freq = tempprob; huffcodes[j].freq = tempprob; // Declaring the child of // leaf node as NULL pointer pix_freq[j].left = NULL; pix_freq[j].right = NULL; // initializing the code // word as end of line pix_freq[j].code[0] = '\0'; j++; }} Step 6Sorting the huffcodes array according to the probability of occurrence of the pixel intensity values Note that, it is necessary to sort the huffcodes array, but not the pix_freq array, since we are already storing the location of the pixel values in the arrloc field of the huffcodes array. // Sorting the histogramstruct huffcode temphuff; // Sorting w.r.t probability // of occurrencefor (i = 0; i < nodes; i++) { for (j = i + 1; j < nodes; j++) { if (huffcodes[i].freq < huffcodes[j].freq) { temphuff = huffcodes[i]; huffcodes[i] = huffcodes[j]; huffcodes[j] = temphuff; } }} Step 7Building the Huffman Tree We start by combining the two nodes with lowest probabilities of occurrence and then replacing the two nodes by the new node. This process continues until we have a root node. The first parent node formed will be stored at index nodes in the array pix_freq and the subsequent parent nodes obtained will be stored at higher values of index. // Building Huffman Tree float sumprob;int sumpix;int n = 0, k = 0;int nextnode = nodes; // Since total number of // nodes in Huffman Tree // is 2*nodes-1while (n < nodes - 1) { // Adding the lowest // two probabilities sumprob = huffcodes[nodes - n - 1].freq + huffcodes[nodes - n - 2].freq; sumpix = huffcodes[nodes - n - 1].pix + huffcodes[nodes - n - 2].pix; // Appending to the pix_freq Array pix_freq[nextnode].pix = sumpix; pix_freq[nextnode].freq = sumprob; pix_freq[nextnode].left = &pix_freq[huffcodes[nodes - n - 2].arrloc]; // arrloc points to the location // of the child node in the // pix_freq array pix_freq[nextnode].right = &pix_freq[huffcodes[nodes - n - 1].arrloc]; pix_freq[nextnode].code[0] = '\0'; // Using sum of the pixel values as // new representation for the new node // since unlike strings, we cannot // concatenate because the pixel values // are stored as integers. However, if we // store the pixel values as strings // we can use the concatenated string as // a representation of the new node. i = 0; // Sorting and Updating the huffcodes // array simultaneously New position // of the combined node while (sumprob <= huffcodes[i].freq) i++; // Inserting the new node in // the huffcodes array for (k = nnz; k >= 0; k--) { if (k == i) { huffcodes[k].pix = sumpix; huffcodes[k].freq = sumprob; huffcodes[k].arrloc = nextnode; } else if (k > i) // Shifting the nodes below // the new node by 1 // For inserting the new node // at the updated position k huffcodes[k] = huffcodes[k - 1]; } n += 1; nextnode += 1;} How does this code work? Let’s see that by an example: Initially After the First Iteration As you can see, after first iteration, the new node has been appended to the pix_freq array, and it’s index is 46. And in the huffcode the new node has been added at its new position after sorting, and the arrloc points to the index of the new node in the pix_freq array. Also, notice that, all array elements after the new node (at index 11) in huffcodes array has been shifted by 1 and the array element with pixel value 188 gets excluded in the updated array. Now, in the next(2nd) iteration 170 and 174 will be combined, since 175 and 188 has already been combined.Index of the lowest two nodes in terms of the variable nodes and n is left_child_index=(nodes-n-2) and right_child_index=(nodes-n-1) In 2nd iteration, value of n is 1 (since n starts from 0). For node having value 170 left_child_index=46-1-2=43 For node having value 174 right_child_index=46-1-1=44 Hence, even if 175 remains the last element of the updated array, it will get excluded. Another thing to notice in this code, is that, if in any subsequent iteration, the new node formed in the first iteration is the child of another new node, then the pointer to the new node obtained in the first iteration, can be accessed using the arrloc stored in huffcodes array, as is done in this line of code pix_freq[nextnode].right = &pix_freq[huffcodes[nodes - n - 1].arrloc]; Step 8Backtrack from the root to the leaf nodes to assign code words Starting from the root, we assign ‘0’ to the left child node and ‘1’ to the right child node. Now, since we were appending the newly formed nodes to the array pix_freq, hence it is expected that the root will be the last element of the array at index totalnodes-1. Hence, we start from the last index and iterate over the array, assigning code words to the left and right child nodes, till we reach the first parent node formed at index nodes. We don’t iterate over the leaf nodes since those nodes has NULL pointers as their left and right child. // Assigning Code through backtrackingchar left = '0';char right = '1';int index;for (i = totalnodes - 1; i >= nodes; i--) { if (pix_freq[i].left != NULL) { strconcat(pix_freq[i].left->code, pix_freq[i].code, left); } if (pix_freq[i].right != NULL) { strconcat(pix_freq[i].right->code, pix_freq[i].code, right); }} void strconcat(char* str, char* parentcode, char add){ int i = 0; while (*(parentcode + i) != '\0') { *(str + i) = *(parentcode + i); i++; } str[i] = add; str[i + 1] = '\0';} Final StepEncode the Image // Encode the Imageint pix_val; // Writing the Huffman encoded// Image into a text fileFILE* imagehuff = fopen("encoded_image.txt", "wb");for (r = 0; r < height; r++) for (c = 0; c < width; c++) { pix_val = image[r]; for (i = 0; i < nodes; i++) if (pix_val == pix_freq[i].pix) fprintf(imagehuff, "%s", pix_freq[i].code); }fclose(imagehuff); // Printing Huffman Codesprintf("Huffmann Codes::\n\n");printf("pixel values -> Code\n\n");for (i = 0; i < nodes; i++) { if (snprintf(NULL, 0, "%d", pix_freq[i].pix) == 2) printf(" %d -> %s\n", pix_freq[i].pix, pix_freq[i].code); else printf(" %d -> %s\n", pix_freq[i].pix, pix_freq[i].code);} Another important point to noteAverage number of bits required to represent each pixel. // Calculating Average number of bitsfloat avgbitnum = 0;for (i = 0; i < nodes; i++) avgbitnum += pix_freq[i].freq * codelen(pix_freq[i].code); The function codelen calculates the length of codewords OR, the number of bits required to represent the pixel. int codelen(char* code){ int l = 0; while (*(code + l) != '\0') l++; return l;} For this specific example image Average number of bits = 5.343750 The printed results for the example image pixel values -> Code 72 -> 011001 75 -> 010100 79 -> 110111 83 -> 011010 84 -> 00100 87 -> 011100 89 -> 010000 93 -> 010111 94 -> 00011 96 -> 101010 98 -> 101110 100 -> 000101 102 -> 0001000 103 -> 0001001 105 -> 110110 106 -> 00110 110 -> 110100 114 -> 110101 115 -> 1100 118 -> 011011 119 -> 011000 122 -> 1110 124 -> 011110 125 -> 011111 127 -> 0000 128 -> 011101 130 -> 010010 131 -> 010011 136 -> 00111 138 -> 010001 139 -> 010110 140 -> 1111 142 -> 00101 143 -> 010101 146 -> 10010 148 -> 101011 149 -> 101000 153 -> 101001 155 -> 10011 163 -> 101111 167 -> 101100 169 -> 101101 170 -> 100010 174 -> 100011 175 -> 100000 188 -> 100001 Encoded Image : 0111010101000110011101101010001011010000000101111 00010001101000100100100100010010101011001101110111001 00000001100111101010010101100001111000110110111110010 10110001000000010110000001100001100001110011011110000 10011001101111111000100101111100010100011110000111000 01101001110101111100000111101100001110010010110101000 0111101001100101101001010111 This encoded Image is 342 bits in length, where as the total number of bits in the original image is 512 bits. (64 pixels each of 8 bits). // C Code for// Image Compression#include <stdio.h>#include <stdlib.h> // function to calculate word length int codelen(char* code){ int l = 0; while (*(code + l) != '\0') l++; return l;} // function to concatenate the wordsvoid strconcat(char* str, char* parentcode, char add){ int i = 0; while (*(parentcode + i) != '\0') { *(str + i) = *(parentcode + i); i++; } if (add != '2') { str[i] = add; str[i + 1] = '\0'; } else str[i] = '\0';} // function to find fibonacci number int fib(int n){ if (n <= 1) return n; return fib(n - 1) + fib(n - 2);} // Driver codeint main(){ int i, j; char filename[] = "Input_Image.bmp"; int data = 0, offset, bpp = 0, width, height; long bmpsize = 0, bmpdataoff = 0; int** image; int temp = 0; // Reading the BMP File FILE* image_file; image_file = fopen(filename, "rb"); if (image_file == NULL) { printf("Error Opening File!!"); exit(1); } else { // Set file position of the // stream to the beginning // Contains file signature // or ID "BM" offset = 0; // Set offset to 2, which // contains size of BMP File offset = 2; fseek(image_file, offset, SEEK_SET); // Getting size of BMP File fread(&bmpsize, 4, 1, image_file); // Getting offset where the // pixel array starts // Since the information is // at offset 10 from the start, // as given in BMP Header offset = 10; fseek(image_file, offset, SEEK_SET); // Bitmap data offset fread(&bmpdataoff, 4, 1, image_file); // Getting height and width of the image // Width is stored at offset 18 and // height at offset 22, each of 4 bytes fseek(image_file, 18, SEEK_SET); fread(&width, 4, 1, image_file); fread(&height, 4, 1, image_file); // Number of bits per pixel fseek(image_file, 2, SEEK_CUR); fread(&bpp, 2, 1, image_file); // Setting offset to start of pixel data fseek(image_file, bmpdataoff, SEEK_SET); // Creating Image array image = (int**)malloc(height * sizeof(int*)); for (i = 0; i < height; i++) { image[i] = (int*)malloc(width * sizeof(int)); } // int image[height][width] // can also be done // Number of bytes in // the Image pixel array int numbytes = (bmpsize - bmpdataoff) / 3; // Reading the BMP File // into Image Array for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { fread(&temp, 3, 1, image_file); // the Image is a // 24-bit BMP Image temp = temp & 0x0000FF; image[i][j] = temp; } } } // Finding the probability // of occurrence int hist[256]; for (i = 0; i < 256; i++) hist[i] = 0; for (i = 0; i < height; i++) for (j = 0; j < width; j++) hist[image[i][j]] += 1; // Finding number of // non-zero occurrences int nodes = 0; for (i = 0; i < 256; i++) if (hist[i] != 0) nodes += 1; // Calculating minimum probability float p = 1.0, ptemp; for (i = 0; i < 256; i++) { ptemp = (hist[i] / (float)(height * width)); if (ptemp > 0 && ptemp <= p) p = ptemp; } // Calculating max length // of code word i = 0; while ((1 / p) > fib(i)) i++; int maxcodelen = i - 3; // Defining Structures pixfreq struct pixfreq { int pix, larrloc, rarrloc; float freq; struct pixfreq *left, *right; char code[maxcodelen]; }; // Defining Structures // huffcode struct huffcode { int pix, arrloc; float freq; }; // Declaring structs struct pixfreq* pix_freq; struct huffcode* huffcodes; int totalnodes = 2 * nodes - 1; pix_freq = (struct pixfreq*)malloc(sizeof(struct pixfreq) * totalnodes); huffcodes = (struct huffcode*)malloc(sizeof(struct huffcode) * nodes); // Initializing j = 0; int totpix = height * width; float tempprob; for (i = 0; i < 256; i++) { if (hist[i] != 0) { // pixel intensity value huffcodes[j].pix = i; pix_freq[j].pix = i; // location of the node // in the pix_freq array huffcodes[j].arrloc = j; // probability of occurrence tempprob = (float)hist[i] / (float)totpix; pix_freq[j].freq = tempprob; huffcodes[j].freq = tempprob; // Declaring the child of leaf // node as NULL pointer pix_freq[j].left = NULL; pix_freq[j].right = NULL; // initializing the code // word as end of line pix_freq[j].code[0] = '\0'; j++; } } // Sorting the histogram struct huffcode temphuff; // Sorting w.r.t probability // of occurrence for (i = 0; i < nodes; i++) { for (j = i + 1; j < nodes; j++) { if (huffcodes[i].freq < huffcodes[j].freq) { temphuff = huffcodes[i]; huffcodes[i] = huffcodes[j]; huffcodes[j] = temphuff; } } } // Building Huffman Tree float sumprob; int sumpix; int n = 0, k = 0; int nextnode = nodes; // Since total number of // nodes in Huffman Tree // is 2*nodes-1 while (n < nodes - 1) { // Adding the lowest two probabilities sumprob = huffcodes[nodes - n - 1].freq + huffcodes[nodes - n - 2].freq; sumpix = huffcodes[nodes - n - 1].pix + huffcodes[nodes - n - 2].pix; // Appending to the pix_freq Array pix_freq[nextnode].pix = sumpix; pix_freq[nextnode].freq = sumprob; pix_freq[nextnode].left = &pix_freq[huffcodes[nodes - n - 2].arrloc]; pix_freq[nextnode].right = &pix_freq[huffcodes[nodes - n - 1].arrloc]; pix_freq[nextnode].code[0] = '\0'; i = 0; // Sorting and Updating the // huffcodes array simultaneously // New position of the combined node while (sumprob <= huffcodes[i].freq) i++; // Inserting the new node // in the huffcodes array for (k = nodes; k >= 0; k--) { if (k == i) { huffcodes[k].pix = sumpix; huffcodes[k].freq = sumprob; huffcodes[k].arrloc = nextnode; } else if (k > i) // Shifting the nodes below // the new node by 1 // For inserting the new node // at the updated position k huffcodes[k] = huffcodes[k - 1]; } n += 1; nextnode += 1; } // Assigning Code through // backtracking char left = '0'; char right = '1'; int index; for (i = totalnodes - 1; i >= nodes; i--) { if (pix_freq[i].left != NULL) strconcat(pix_freq[i].left->code, pix_freq[i].code, left); if (pix_freq[i].right != NULL) strconcat(pix_freq[i].right->code, pix_freq[i].code, right); } // Encode the Image int pix_val; int l; // Writing the Huffman encoded // Image into a text file FILE* imagehuff = fopen("encoded_image.txt", "wb"); for (i = 0; i < height; i++) for (j = 0; j < width; j++) { pix_val = image[i][j]; for (l = 0; l < nodes; l++) if (pix_val == pix_freq[l].pix) fprintf(imagehuff, "%s", pix_freq[l].code); } // Printing Huffman Codes printf("Huffmann Codes::\n\n"); printf("pixel values -> Code\n\n"); for (i = 0; i < nodes; i++) { if (snprintf(NULL, 0, "%d", pix_freq[i].pix) == 2) printf(" %d -> %s\n", pix_freq[i].pix, pix_freq[i].code); else printf(" %d -> %s\n", pix_freq[i].pix, pix_freq[i].code); } // Calculating Average Bit Length float avgbitnum = 0; for (i = 0; i < nodes; i++) avgbitnum += pix_freq[i].freq * codelen(pix_freq[i].code); printf("Average number of bits:: %f", avgbitnum);} Code Compilation and Execution :First, save the file as “huffman.c“.For compiling the C file, Open terminal (Ctrl + Alt + T) and enter the following line of code :gcc -o huffman huffman.cFor executing the code enter./huffman Image Compression Code Output : Huffman Tree : nidhi_biet Huffman Coding Image-Processing Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Markov Decision Process Basics of API Testing Using Postman Copying Files to and from Docker Containers Getting Started with System Design Principal Component Analysis with Python How to create a REST API using Java Spring Boot Monolithic vs Microservices architecture Fuzzy Logic | Introduction OpenCV - Overview
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Nov, 2019" }, { "code": null, "e": 343, "s": 54, "text": "Huffman coding is one of the basic compression methods, that have proven useful in image and video compression standards. When applying Huffman encoding technique on an Image, the source symbols can be either pixel intensities of the Image, or the output of an intensity mapping function." }, { "code": null, "e": 390, "s": 343, "text": "Prerequisites : Huffman Coding | File Handling" }, { "code": null, "e": 563, "s": 390, "text": "The first step of Huffman coding technique is to reduce the input image to a ordered histogram, where the probability of occurrence of a certain pixel intensity value is as" }, { "code": null, "e": 593, "s": 563, "text": " prob_pixel = numpix/totalnum" }, { "code": null, "e": 739, "s": 593, "text": "where numpix is the number of occurrence of a pixel with a certain intensity value and totalnum is the total number of pixels in the input Image." }, { "code": null, "e": 765, "s": 739, "text": "Let us take a 8 X 8 Image" }, { "code": null, "e": 902, "s": 765, "text": "The pixel intensity values are :This image contains 46 distinct pixel intensity values, hence we will have 46 unique Huffman code words." }, { "code": null, "e": 1041, "s": 902, "text": "It is evident that, not all pixel intensity values may be present in the image and hence will not have non-zero probability of occurrence." }, { "code": null, "e": 1134, "s": 1041, "text": "From here on, the pixel intensity values in the input Image will be addressed as leaf nodes." }, { "code": null, "e": 1193, "s": 1134, "text": "Now, there are 2 essential steps to build a Huffman Tree :" }, { "code": null, "e": 1597, "s": 1193, "text": "Build a Huffman Tree :Combine the two lowest probability leaf nodes into a new node.Replace the two leaf nodes by the new node and sort the nodes according to the new probability values.Continue the steps (a) and (b) until we get a single node with probability value 1.0. We will call this node as rootBacktrack from the root, assigning ‘0’ or ‘1’ to each intermediate node, till we reach the leaf nodes" }, { "code": null, "e": 1620, "s": 1597, "text": "Build a Huffman Tree :" }, { "code": null, "e": 1901, "s": 1620, "text": "Combine the two lowest probability leaf nodes into a new node.Replace the two leaf nodes by the new node and sort the nodes according to the new probability values.Continue the steps (a) and (b) until we get a single node with probability value 1.0. We will call this node as root" }, { "code": null, "e": 1964, "s": 1901, "text": "Combine the two lowest probability leaf nodes into a new node." }, { "code": null, "e": 2067, "s": 1964, "text": "Replace the two leaf nodes by the new node and sort the nodes according to the new probability values." }, { "code": null, "e": 2184, "s": 2067, "text": "Continue the steps (a) and (b) until we get a single node with probability value 1.0. We will call this node as root" }, { "code": null, "e": 2286, "s": 2184, "text": "Backtrack from the root, assigning ‘0’ or ‘1’ to each intermediate node, till we reach the leaf nodes" }, { "code": null, "e": 2371, "s": 2286, "text": "In this example, we will assign ‘0’ to the left child node and ‘1’ to the right one." }, { "code": null, "e": 2579, "s": 2371, "text": "Now, let’s look into the implementation :Step 1 :Read the Image into a 2D array(image)If the Image is in .bmp format, then the Image can be read into the 2D array, by using this code given in this link here." }, { "code": "int i, j;char filename[] = \"Input_Image.bmp\";int data = 0, offset, bpp = 0, width, height;long bmpsize = 0, bmpdataoff = 0;int** image;int temp = 0; // Reading the BMP FileFILE* image_file;image_file = fopen(filename, \"rb\");if (image_file == NULL){ printf(\"Error Opening File!!\"); exit(1);}else { // Set file position of the // stream to the beginning // Contains file signature // or ID \"BM\" offset = 0; // Set offset to 2, which // contains size of BMP File offset = 2; fseek(image_file, offset, SEEK_SET); // Getting size of BMP File fread(&bmpsize, 4, 1, image_file); // Getting offset where the // pixel array starts // Since the information // is at offset 10 from // the start, as given // in BMP Header offset = 10; fseek(image_file, offset, SEEK_SET); // Bitmap data offset fread(&bmpdataoff, 4, 1, image_file); // Getting height and width of the image // Width is stored at offset 18 and height // at offset 22, each of 4 bytes fseek(image_file, 18, SEEK_SET); fread(&width, 4, 1, image_file); fread(&height, 4, 1, image_file); // Number of bits per pixel fseek(image_file, 2, SEEK_CUR); fread(&bpp, 2, 1, image_file); // Setting offset to start of pixel data fseek(image_file, bmpdataoff, SEEK_SET); // Creating Image array image = (int**)malloc(height * sizeof(int*)); for (i = 0; i < height; i++) { image[i] = (int*)malloc(width * sizeof(int)); } // int image[height][width] // can also be done // Number of bytes in the // Image pixel array int numbytes = (bmpsize - bmpdataoff) / 3; // Reading the BMP File // into Image Array for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { fread(&temp, 3, 1, image_file); // the Image is a // 24-bit BMP Image temp = temp & 0x0000FF; image[i][j] = temp; } }}", "e": 4653, "s": 2579, "text": null }, { "code": null, "e": 4723, "s": 4653, "text": "Create a Histogram of the pixel intensity values present in the Image" }, { "code": "// Creating the Histogramint hist[256]; for (i = 0; i < 256; i++) hist[i] = 0; for (i = 0; i < height; i++) for (j = 0; j < width; j++) hist[image[i][j]] += 1;", "e": 4898, "s": 4723, "text": null }, { "code": null, "e": 5393, "s": 4898, "text": "Find the number of pixel intensity values having non-zero probability of occurrenceSince, the values of pixel intensities range from 0 to 255, and not all pixel intensity values may be present in the image (as evident from the histogram and also the image matrix) and hence will not have non-zero probability of occurrence. Also another purpose this step serves, is that the number of pixel intensity values having non-zero probability values will give us the number of leaf nodes in the Image." }, { "code": "// Finding number of // non-zero occurrencesint nodes = 0;for (i = 0; i < 256; i++) { if (hist[i] != 0) nodes += 1;}", "e": 5520, "s": 5393, "text": null }, { "code": null, "e": 6055, "s": 5520, "text": "Calculating the maximum length of Huffman code wordsAs shown by Y.S.Abu-Mostafa and R.J.McEliece in their paper “Maximal codeword lengths in Huffman codes”, that, If , then in any efficient prefix code for a source whose least probability is p, the longest codeword length is at most K & If , there exists a source whose smallest probability is p, and which has a Huffman code whose longest word has length K. If , there exists such a source for which every optimal code has a longest word of length K.Here, is the Fibonacci number." }, { "code": null, "e": 6194, "s": 6055, "text": "Gallager [1] noted that every Huffman tree is efficient, but in fact it is easy to see more\ngenerally that every optimal tree is efficient" }, { "code": null, "e": 6266, "s": 6194, "text": "Fibonacci Series is : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ..." }, { "code": null, "e": 6316, "s": 6266, "text": "In our example, lowest probability(p) is 0.015625" }, { "code": null, "e": 6323, "s": 6316, "text": "Hence," }, { "code": null, "e": 6333, "s": 6323, "text": " 1/p = 64" }, { "code": null, "e": 6384, "s": 6333, "text": "For K = 9,\nF(K+2) = F(11) = 55\nF(K+3) = F(12) = 89" }, { "code": null, "e": 6395, "s": 6384, "text": "Therefore," }, { "code": null, "e": 6455, "s": 6395, "text": "1/F(K+3) < p < 1/F(K+2)\nHence optimal length of code is K=9" }, { "code": "// Calculating max length // of Huffman code wordi = 0;while ((1 / p) < fib(i)) i++;int maxcodelen = i - 3;", "e": 6566, "s": 6455, "text": null }, { "code": "// Function for getting Fibonacci// numbers defined outside mainint fib(int n){ if (n <= 1) return n; return fib(n - 1) + fib(n - 2);}", "e": 6714, "s": 6566, "text": null }, { "code": null, "e": 6949, "s": 6714, "text": "Step 2Define a struct which will contain the pixel intensity values(pix), their corresponding probabilities(freq), the pointer to the left(*left) and right(*right) child nodes and also the string array for the Huffman code word(code)." }, { "code": null, "e": 7095, "s": 6949, "text": "These structs is defined inside main(), so as to use the maximum length of code(maxcodelen) to declare the code array field of the struct pixfreq" }, { "code": "// Defining Structures pixfreqstruct pixfreq { int pix; float freq; struct pixfreq *left, *right; char code[maxcodelen];};", "e": 7230, "s": 7095, "text": null }, { "code": null, "e": 7451, "s": 7230, "text": "Step 3Define another Struct which will contain the pixel intensity values(pix), their corresponding probabilities(freq) and an additional field, which will be used for storing the position of new generated nodes(arrloc)." }, { "code": "// Defining Structures huffcodestruct huffcode { int pix, arrloc; float freq;};", "e": 7537, "s": 7451, "text": null }, { "code": null, "e": 7643, "s": 7537, "text": "Step 4Declaring an array of structs. Each element of the array corresponds to a node in the Huffman Tree." }, { "code": "// Declaring structsstruct pixfreq* pix_freq;struct huffcode* huffcodes;", "e": 7716, "s": 7643, "text": null }, { "code": null, "e": 7743, "s": 7716, "text": "Why use two struct arrays?" }, { "code": null, "e": 7896, "s": 7743, "text": "Initially, the struct array pix_freq, as well as the struct array huffcodes will only contain the information of all the leaf nodes in the Huffman Tree." }, { "code": null, "e": 8049, "s": 7896, "text": "The struct array pix_freq will be used to store all the nodes of the Huffman Tree and the array huffcodes will be used as the updated (and sorted) tree." }, { "code": null, "e": 8130, "s": 8049, "text": "Remember that, only huffcodes will be sorted in each iteration, and not pix_freq" }, { "code": null, "e": 8295, "s": 8130, "text": "The new nodes created by combining two nodes of lowest frequency, in each iteration, will be appended to the end of the pix_freq array, and also to huffcodes array." }, { "code": null, "e": 8419, "s": 8295, "text": "But the array huffcodes will be sorted again according to the probability of occurrence, after the new node is added to it." }, { "code": null, "e": 8628, "s": 8419, "text": "The position of the new node in the array pix_freq will be stored in the arrloc field of the struct huffcode.The arrloc field will be used when assigning the pointer to the left and right child of a new node." }, { "code": null, "e": 8648, "s": 8628, "text": "Step 4 continued..." }, { "code": null, "e": 8764, "s": 8648, "text": "Now, if there are N number of leaf nodes, the total number of nodes in the whole Huffman Tree will be equal to 2N-1" }, { "code": null, "e": 9023, "s": 8764, "text": "And after two nodes are combined and replaced by the new parent node, the number of nodes decreases by 1 at each iteration. Hence, it is sufficient to have a length of nodes for the array huffcodes, which will be used as the updated and sorted Huffman nodes." }, { "code": "int totalnodes = 2 * nodes - 1;pix_freq = (struct pixfreq*)malloc(sizeof(struct pixfreq) * totalnodes);huffcodes = (struct huffcode*)malloc(sizeof(struct huffcode) * nodes);", "e": 9197, "s": 9023, "text": null }, { "code": null, "e": 9288, "s": 9197, "text": "Step 5Initialize the two arrays pix_freq and huffcodes with information of the leaf nodes." }, { "code": "j = 0;int totpix = height * width;float tempprob;for (i = 0; i < 256; i++) { if (hist[i] != 0) { // pixel intensity value huffcodes[j].pix = i; pix_freq[j].pix = i; // location of the node // in the pix_freq array huffcodes[j].arrloc = j; // probability of occurrence tempprob = (float)hist[i] / (float)totpix; pix_freq[j].freq = tempprob; huffcodes[j].freq = tempprob; // Declaring the child of // leaf node as NULL pointer pix_freq[j].left = NULL; pix_freq[j].right = NULL; // initializing the code // word as end of line pix_freq[j].code[0] = '\\0'; j++; }}", "e": 10039, "s": 9288, "text": null }, { "code": null, "e": 10146, "s": 10039, "text": "Step 6Sorting the huffcodes array according to the probability of occurrence of the pixel intensity values" }, { "code": null, "e": 10336, "s": 10146, "text": "Note that, it is necessary to sort the huffcodes array, but not the pix_freq array, since we are already storing the location of the pixel values in the arrloc field of the huffcodes array." }, { "code": "// Sorting the histogramstruct huffcode temphuff; // Sorting w.r.t probability // of occurrencefor (i = 0; i < nodes; i++) { for (j = i + 1; j < nodes; j++) { if (huffcodes[i].freq < huffcodes[j].freq) { temphuff = huffcodes[i]; huffcodes[i] = huffcodes[j]; huffcodes[j] = temphuff; } }}", "e": 10678, "s": 10336, "text": null }, { "code": null, "e": 10710, "s": 10678, "text": "Step 7Building the Huffman Tree" }, { "code": null, "e": 11050, "s": 10710, "text": "We start by combining the two nodes with lowest probabilities of occurrence and then replacing the two nodes by the new node. This process continues until we have a root node. The first parent node formed will be stored at index nodes in the array pix_freq and the subsequent parent nodes obtained will be stored at higher values of index." }, { "code": "// Building Huffman Tree float sumprob;int sumpix;int n = 0, k = 0;int nextnode = nodes; // Since total number of // nodes in Huffman Tree // is 2*nodes-1while (n < nodes - 1) { // Adding the lowest // two probabilities sumprob = huffcodes[nodes - n - 1].freq + huffcodes[nodes - n - 2].freq; sumpix = huffcodes[nodes - n - 1].pix + huffcodes[nodes - n - 2].pix; // Appending to the pix_freq Array pix_freq[nextnode].pix = sumpix; pix_freq[nextnode].freq = sumprob; pix_freq[nextnode].left = &pix_freq[huffcodes[nodes - n - 2].arrloc]; // arrloc points to the location // of the child node in the // pix_freq array pix_freq[nextnode].right = &pix_freq[huffcodes[nodes - n - 1].arrloc]; pix_freq[nextnode].code[0] = '\\0'; // Using sum of the pixel values as // new representation for the new node // since unlike strings, we cannot // concatenate because the pixel values // are stored as integers. However, if we // store the pixel values as strings // we can use the concatenated string as // a representation of the new node. i = 0; // Sorting and Updating the huffcodes // array simultaneously New position // of the combined node while (sumprob <= huffcodes[i].freq) i++; // Inserting the new node in // the huffcodes array for (k = nnz; k >= 0; k--) { if (k == i) { huffcodes[k].pix = sumpix; huffcodes[k].freq = sumprob; huffcodes[k].arrloc = nextnode; } else if (k > i) // Shifting the nodes below // the new node by 1 // For inserting the new node // at the updated position k huffcodes[k] = huffcodes[k - 1]; } n += 1; nextnode += 1;}", "e": 12876, "s": 11050, "text": null }, { "code": null, "e": 12901, "s": 12876, "text": "How does this code work?" }, { "code": null, "e": 12931, "s": 12901, "text": "Let’s see that by an example:" }, { "code": null, "e": 12941, "s": 12931, "text": "Initially" }, { "code": null, "e": 12967, "s": 12941, "text": "After the First Iteration" }, { "code": null, "e": 13430, "s": 12967, "text": "As you can see, after first iteration, the new node has been appended to the pix_freq array, and it’s index is 46. And in the huffcode the new node has been added at its new position after sorting, and the arrloc points to the index of the new node in the pix_freq array. Also, notice that, all array elements after the new node (at index 11) in huffcodes array has been shifted by 1 and the array element with pixel value 188 gets excluded in the updated array." }, { "code": null, "e": 13606, "s": 13430, "text": "Now, in the next(2nd) iteration 170 and 174 will be combined, since 175 and 188 has already been combined.Index of the lowest two nodes in terms of the variable nodes and n is" }, { "code": null, "e": 13635, "s": 13606, "text": "left_child_index=(nodes-n-2)" }, { "code": null, "e": 13639, "s": 13635, "text": "and" }, { "code": null, "e": 13669, "s": 13639, "text": "right_child_index=(nodes-n-1)" }, { "code": null, "e": 13728, "s": 13669, "text": "In 2nd iteration, value of n is 1 (since n starts from 0)." }, { "code": null, "e": 13754, "s": 13728, "text": "For node having value 170" }, { "code": null, "e": 13782, "s": 13754, "text": " left_child_index=46-1-2=43" }, { "code": null, "e": 13808, "s": 13782, "text": "For node having value 174" }, { "code": null, "e": 13837, "s": 13808, "text": " right_child_index=46-1-1=44" }, { "code": null, "e": 13925, "s": 13837, "text": "Hence, even if 175 remains the last element of the updated array, it will get excluded." }, { "code": null, "e": 14239, "s": 13925, "text": "Another thing to notice in this code, is that, if in any subsequent iteration, the new node formed in the first iteration is the child of another new node, then the pointer to the new node obtained in the first iteration, can be accessed using the arrloc stored in huffcodes array, as is done in this line of code" }, { "code": "pix_freq[nextnode].right = &pix_freq[huffcodes[nodes - n - 1].arrloc];", "e": 14310, "s": 14239, "text": null }, { "code": null, "e": 14379, "s": 14310, "text": "Step 8Backtrack from the root to the leaf nodes to assign code words" }, { "code": null, "e": 14473, "s": 14379, "text": "Starting from the root, we assign ‘0’ to the left child node and ‘1’ to the right child node." }, { "code": null, "e": 14644, "s": 14473, "text": "Now, since we were appending the newly formed nodes to the array pix_freq, hence it is expected that the root will be the last element of the array at index totalnodes-1." }, { "code": null, "e": 14927, "s": 14644, "text": "Hence, we start from the last index and iterate over the array, assigning code words to the left and right child nodes, till we reach the first parent node formed at index nodes. We don’t iterate over the leaf nodes since those nodes has NULL pointers as their left and right child." }, { "code": "// Assigning Code through backtrackingchar left = '0';char right = '1';int index;for (i = totalnodes - 1; i >= nodes; i--) { if (pix_freq[i].left != NULL) { strconcat(pix_freq[i].left->code, pix_freq[i].code, left); } if (pix_freq[i].right != NULL) { strconcat(pix_freq[i].right->code, pix_freq[i].code, right); }}", "e": 15268, "s": 14927, "text": null }, { "code": "void strconcat(char* str, char* parentcode, char add){ int i = 0; while (*(parentcode + i) != '\\0') { *(str + i) = *(parentcode + i); i++; } str[i] = add; str[i + 1] = '\\0';}", "e": 15472, "s": 15268, "text": null }, { "code": null, "e": 15499, "s": 15472, "text": "Final StepEncode the Image" }, { "code": "// Encode the Imageint pix_val; // Writing the Huffman encoded// Image into a text fileFILE* imagehuff = fopen(\"encoded_image.txt\", \"wb\");for (r = 0; r < height; r++) for (c = 0; c < width; c++) { pix_val = image[r]; for (i = 0; i < nodes; i++) if (pix_val == pix_freq[i].pix) fprintf(imagehuff, \"%s\", pix_freq[i].code); }fclose(imagehuff); // Printing Huffman Codesprintf(\"Huffmann Codes::\\n\\n\");printf(\"pixel values -> Code\\n\\n\");for (i = 0; i < nodes; i++) { if (snprintf(NULL, 0, \"%d\", pix_freq[i].pix) == 2) printf(\" %d -> %s\\n\", pix_freq[i].pix, pix_freq[i].code); else printf(\" %d -> %s\\n\", pix_freq[i].pix, pix_freq[i].code);}", "e": 16222, "s": 15499, "text": null }, { "code": null, "e": 16310, "s": 16222, "text": "Another important point to noteAverage number of bits required to represent each pixel." }, { "code": "// Calculating Average number of bitsfloat avgbitnum = 0;for (i = 0; i < nodes; i++) avgbitnum += pix_freq[i].freq * codelen(pix_freq[i].code);", "e": 16457, "s": 16310, "text": null }, { "code": null, "e": 16569, "s": 16457, "text": "The function codelen calculates the length of codewords OR, the number of bits required to represent the pixel." }, { "code": "int codelen(char* code){ int l = 0; while (*(code + l) != '\\0') l++; return l;}", "e": 16665, "s": 16569, "text": null }, { "code": null, "e": 16697, "s": 16665, "text": "For this specific example image" }, { "code": null, "e": 16731, "s": 16697, "text": "Average number of bits = 5.343750" }, { "code": null, "e": 16773, "s": 16731, "text": "The printed results for the example image" }, { "code": null, "e": 18028, "s": 16773, "text": " pixel values -> Code\n 72 -> 011001\n 75 -> 010100\n 79 -> 110111\n 83 -> 011010\n 84 -> 00100\n 87 -> 011100\n 89 -> 010000\n 93 -> 010111\n 94 -> 00011\n 96 -> 101010\n 98 -> 101110\n 100 -> 000101\n 102 -> 0001000\n 103 -> 0001001\n 105 -> 110110\n 106 -> 00110\n 110 -> 110100\n 114 -> 110101\n 115 -> 1100\n 118 -> 011011\n 119 -> 011000\n 122 -> 1110\n 124 -> 011110\n 125 -> 011111\n 127 -> 0000\n 128 -> 011101\n 130 -> 010010\n 131 -> 010011\n 136 -> 00111\n 138 -> 010001\n 139 -> 010110\n 140 -> 1111\n 142 -> 00101\n 143 -> 010101\n 146 -> 10010\n 148 -> 101011\n 149 -> 101000\n 153 -> 101001\n 155 -> 10011\n 163 -> 101111\n 167 -> 101100\n 169 -> 101101\n 170 -> 100010\n 174 -> 100011\n 175 -> 100000\n 188 -> 100001\n" }, { "code": null, "e": 18044, "s": 18028, "text": "Encoded Image :" }, { "code": null, "e": 18393, "s": 18044, "text": "0111010101000110011101101010001011010000000101111\n00010001101000100100100100010010101011001101110111001\n00000001100111101010010101100001111000110110111110010\n10110001000000010110000001100001100001110011011110000\n10011001101111111000100101111100010100011110000111000\n01101001110101111100000111101100001110010010110101000\n0111101001100101101001010111" }, { "code": null, "e": 18532, "s": 18393, "text": "This encoded Image is 342 bits in length, where as the total number of bits in the original image is 512 bits. (64 pixels each of 8 bits)." }, { "code": "// C Code for// Image Compression#include <stdio.h>#include <stdlib.h> // function to calculate word length int codelen(char* code){ int l = 0; while (*(code + l) != '\\0') l++; return l;} // function to concatenate the wordsvoid strconcat(char* str, char* parentcode, char add){ int i = 0; while (*(parentcode + i) != '\\0') { *(str + i) = *(parentcode + i); i++; } if (add != '2') { str[i] = add; str[i + 1] = '\\0'; } else str[i] = '\\0';} // function to find fibonacci number int fib(int n){ if (n <= 1) return n; return fib(n - 1) + fib(n - 2);} // Driver codeint main(){ int i, j; char filename[] = \"Input_Image.bmp\"; int data = 0, offset, bpp = 0, width, height; long bmpsize = 0, bmpdataoff = 0; int** image; int temp = 0; // Reading the BMP File FILE* image_file; image_file = fopen(filename, \"rb\"); if (image_file == NULL) { printf(\"Error Opening File!!\"); exit(1); } else { // Set file position of the // stream to the beginning // Contains file signature // or ID \"BM\" offset = 0; // Set offset to 2, which // contains size of BMP File offset = 2; fseek(image_file, offset, SEEK_SET); // Getting size of BMP File fread(&bmpsize, 4, 1, image_file); // Getting offset where the // pixel array starts // Since the information is // at offset 10 from the start, // as given in BMP Header offset = 10; fseek(image_file, offset, SEEK_SET); // Bitmap data offset fread(&bmpdataoff, 4, 1, image_file); // Getting height and width of the image // Width is stored at offset 18 and // height at offset 22, each of 4 bytes fseek(image_file, 18, SEEK_SET); fread(&width, 4, 1, image_file); fread(&height, 4, 1, image_file); // Number of bits per pixel fseek(image_file, 2, SEEK_CUR); fread(&bpp, 2, 1, image_file); // Setting offset to start of pixel data fseek(image_file, bmpdataoff, SEEK_SET); // Creating Image array image = (int**)malloc(height * sizeof(int*)); for (i = 0; i < height; i++) { image[i] = (int*)malloc(width * sizeof(int)); } // int image[height][width] // can also be done // Number of bytes in // the Image pixel array int numbytes = (bmpsize - bmpdataoff) / 3; // Reading the BMP File // into Image Array for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { fread(&temp, 3, 1, image_file); // the Image is a // 24-bit BMP Image temp = temp & 0x0000FF; image[i][j] = temp; } } } // Finding the probability // of occurrence int hist[256]; for (i = 0; i < 256; i++) hist[i] = 0; for (i = 0; i < height; i++) for (j = 0; j < width; j++) hist[image[i][j]] += 1; // Finding number of // non-zero occurrences int nodes = 0; for (i = 0; i < 256; i++) if (hist[i] != 0) nodes += 1; // Calculating minimum probability float p = 1.0, ptemp; for (i = 0; i < 256; i++) { ptemp = (hist[i] / (float)(height * width)); if (ptemp > 0 && ptemp <= p) p = ptemp; } // Calculating max length // of code word i = 0; while ((1 / p) > fib(i)) i++; int maxcodelen = i - 3; // Defining Structures pixfreq struct pixfreq { int pix, larrloc, rarrloc; float freq; struct pixfreq *left, *right; char code[maxcodelen]; }; // Defining Structures // huffcode struct huffcode { int pix, arrloc; float freq; }; // Declaring structs struct pixfreq* pix_freq; struct huffcode* huffcodes; int totalnodes = 2 * nodes - 1; pix_freq = (struct pixfreq*)malloc(sizeof(struct pixfreq) * totalnodes); huffcodes = (struct huffcode*)malloc(sizeof(struct huffcode) * nodes); // Initializing j = 0; int totpix = height * width; float tempprob; for (i = 0; i < 256; i++) { if (hist[i] != 0) { // pixel intensity value huffcodes[j].pix = i; pix_freq[j].pix = i; // location of the node // in the pix_freq array huffcodes[j].arrloc = j; // probability of occurrence tempprob = (float)hist[i] / (float)totpix; pix_freq[j].freq = tempprob; huffcodes[j].freq = tempprob; // Declaring the child of leaf // node as NULL pointer pix_freq[j].left = NULL; pix_freq[j].right = NULL; // initializing the code // word as end of line pix_freq[j].code[0] = '\\0'; j++; } } // Sorting the histogram struct huffcode temphuff; // Sorting w.r.t probability // of occurrence for (i = 0; i < nodes; i++) { for (j = i + 1; j < nodes; j++) { if (huffcodes[i].freq < huffcodes[j].freq) { temphuff = huffcodes[i]; huffcodes[i] = huffcodes[j]; huffcodes[j] = temphuff; } } } // Building Huffman Tree float sumprob; int sumpix; int n = 0, k = 0; int nextnode = nodes; // Since total number of // nodes in Huffman Tree // is 2*nodes-1 while (n < nodes - 1) { // Adding the lowest two probabilities sumprob = huffcodes[nodes - n - 1].freq + huffcodes[nodes - n - 2].freq; sumpix = huffcodes[nodes - n - 1].pix + huffcodes[nodes - n - 2].pix; // Appending to the pix_freq Array pix_freq[nextnode].pix = sumpix; pix_freq[nextnode].freq = sumprob; pix_freq[nextnode].left = &pix_freq[huffcodes[nodes - n - 2].arrloc]; pix_freq[nextnode].right = &pix_freq[huffcodes[nodes - n - 1].arrloc]; pix_freq[nextnode].code[0] = '\\0'; i = 0; // Sorting and Updating the // huffcodes array simultaneously // New position of the combined node while (sumprob <= huffcodes[i].freq) i++; // Inserting the new node // in the huffcodes array for (k = nodes; k >= 0; k--) { if (k == i) { huffcodes[k].pix = sumpix; huffcodes[k].freq = sumprob; huffcodes[k].arrloc = nextnode; } else if (k > i) // Shifting the nodes below // the new node by 1 // For inserting the new node // at the updated position k huffcodes[k] = huffcodes[k - 1]; } n += 1; nextnode += 1; } // Assigning Code through // backtracking char left = '0'; char right = '1'; int index; for (i = totalnodes - 1; i >= nodes; i--) { if (pix_freq[i].left != NULL) strconcat(pix_freq[i].left->code, pix_freq[i].code, left); if (pix_freq[i].right != NULL) strconcat(pix_freq[i].right->code, pix_freq[i].code, right); } // Encode the Image int pix_val; int l; // Writing the Huffman encoded // Image into a text file FILE* imagehuff = fopen(\"encoded_image.txt\", \"wb\"); for (i = 0; i < height; i++) for (j = 0; j < width; j++) { pix_val = image[i][j]; for (l = 0; l < nodes; l++) if (pix_val == pix_freq[l].pix) fprintf(imagehuff, \"%s\", pix_freq[l].code); } // Printing Huffman Codes printf(\"Huffmann Codes::\\n\\n\"); printf(\"pixel values -> Code\\n\\n\"); for (i = 0; i < nodes; i++) { if (snprintf(NULL, 0, \"%d\", pix_freq[i].pix) == 2) printf(\" %d -> %s\\n\", pix_freq[i].pix, pix_freq[i].code); else printf(\" %d -> %s\\n\", pix_freq[i].pix, pix_freq[i].code); } // Calculating Average Bit Length float avgbitnum = 0; for (i = 0; i < nodes; i++) avgbitnum += pix_freq[i].freq * codelen(pix_freq[i].code); printf(\"Average number of bits:: %f\", avgbitnum);}", "e": 27337, "s": 18532, "text": null }, { "code": null, "e": 27562, "s": 27337, "text": "Code Compilation and Execution :First, save the file as “huffman.c“.For compiling the C file, Open terminal (Ctrl + Alt + T) and enter the following line of code :gcc -o huffman huffman.cFor executing the code enter./huffman" }, { "code": null, "e": 27594, "s": 27562, "text": "Image Compression Code Output :" }, { "code": null, "e": 27609, "s": 27594, "text": "Huffman Tree :" }, { "code": null, "e": 27620, "s": 27609, "text": "nidhi_biet" }, { "code": null, "e": 27635, "s": 27620, "text": "Huffman Coding" }, { "code": null, "e": 27652, "s": 27635, "text": "Image-Processing" }, { "code": null, "e": 27678, "s": 27652, "text": "Advanced Computer Subject" }, { "code": null, "e": 27776, "s": 27678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27812, "s": 27776, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 27836, "s": 27812, "text": "Markov Decision Process" }, { "code": null, "e": 27872, "s": 27836, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 27916, "s": 27872, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 27951, "s": 27916, "text": "Getting Started with System Design" }, { "code": null, "e": 27992, "s": 27951, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 28040, "s": 27992, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 28081, "s": 28040, "text": "Monolithic vs Microservices architecture" }, { "code": null, "e": 28108, "s": 28081, "text": "Fuzzy Logic | Introduction" } ]
How to Use Firebase Firestore as a Realtime Database in Android?
20 Jan, 2021 Firebase Firestore is the backend database that is used to add, read, update and delete data from Android. But in Firebase Firestore there is a separate method that is used to read data from Firebase Firestore in Realtime Database. In this article, we will read data from Firebase Firestore in Realtime Database. Note that we are going to implement this project using the Java language. We will be building a simple application in which we will be showing a simple TextView. Inside that TextView, we will be updating the data from Firebase Firestore on a real-time basis. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Connect your app to Firebase After creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file. Check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. implementation ‘com.google.firebase:firebase-firestore:22.0.1’ After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. Step 3: Working with the AndroidManifest.xml file For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml. Inside that file add the below permissions to it. XML <!--Permissions for internet--><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> Step 4: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/idTVHead" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_margin="5dp" android:layout_marginTop="30dp" android:text="Firebase Firestore as Realtime Database" android:textAlignment="center" android:textAllCaps="false" android:textColor="@color/purple_500" android:textSize="20sp" /> <TextView android:id="@+id/idTVUpdate" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHead" android:layout_marginTop="50dp" android:text="Updated Text" android:textAlignment="center" android:textColor="@color/purple_500" android:textSize="30sp" /> </RelativeLayout> Step 5: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.DocumentSnapshot;import com.google.firebase.firestore.EventListener;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.FirebaseFirestoreException; public class MainActivity extends AppCompatActivity { // creating a variable for text view. TextView updatedTV; // initializing th variable for firebase firestore FirebaseFirestore db = FirebaseFirestore.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our text view. updatedTV = findViewById(R.id.idTVUpdate); // creating a variable for document reference. DocumentReference documentReference = db.collection("MyData").document("Data"); // adding snapshot listener to our document reference. documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { // inside the on event method. if (error != null) { // this method is called when error is not null // and we gt any error // in this cas we are displaying an error message. Toast.makeText(MainActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show(); return; } if (value != null && value.exists()) { // if th value from firestore is not null then we are getting // our data and setting that data to our text view. updatedTV.setText(value.getData().get("updateValue").toString()); } } }); }} Step 6: Adding data to the Firebase Firestore console Go to the browser and open Firebase in your browser. After opening Firebase you will get to see the below page and on this page Click on Go to Console option in the top right corner. After clicking on this screen you will get to see the below screen with your all project inside that select your project. Inside that screen click n Firebase Firestore Database in the left window. After clicking on the Create Database option you will get to see the below screen. Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside our app and click on the submit button. To add data just click on the Start Collection button and provide the Collection ID as MyData. After that provide the Document ID as Data and inside the Field write down updateValue, and inside the Value provide your Text you want to display. And click on the Save button. You will get to see the data added inside the Firebase Console. After adding the data to Firebase. Now run your app and see the output of the app. You can change the value in the updateValue field and you can get to see Realtime update on your device. In the below video we are updating the data when the app is running and it is showing the Realtime Updates in our app. android Firebase Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Arrays.sort() in Java with examples Reverse a string in Java Split() String method in Java with examples Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jan, 2021" }, { "code": null, "e": 416, "s": 28, "text": "Firebase Firestore is the backend database that is used to add, read, update and delete data from Android. But in Firebase Firestore there is a separate method that is used to read data from Firebase Firestore in Realtime Database. In this article, we will read data from Firebase Firestore in Realtime Database. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 602, "s": 416, "text": "We will be building a simple application in which we will be showing a simple TextView. Inside that TextView, we will be updating the data from Firebase Firestore on a real-time basis. " }, { "code": null, "e": 631, "s": 602, "text": "Step 1: Create a New Project" }, { "code": null, "e": 793, "s": 631, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 830, "s": 793, "text": "Step 2: Connect your app to Firebase" }, { "code": null, "e": 1035, "s": 830, "text": "After creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot." }, { "code": null, "e": 1444, "s": 1035, "text": "Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. " }, { "code": null, "e": 1778, "s": 1444, "text": "After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file. Check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. " }, { "code": null, "e": 1841, "s": 1778, "text": "implementation ‘com.google.firebase:firebase-firestore:22.0.1’" }, { "code": null, "e": 2078, "s": 1841, "text": "After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. " }, { "code": null, "e": 2128, "s": 2078, "text": "Step 3: Working with the AndroidManifest.xml file" }, { "code": null, "e": 2343, "s": 2128, "text": "For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml. Inside that file add the below permissions to it. " }, { "code": null, "e": 2347, "s": 2343, "text": "XML" }, { "code": "<!--Permissions for internet--><uses-permission android:name=\"android.permission.INTERNET\" /><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />", "e": 2515, "s": 2347, "text": null }, { "code": null, "e": 2563, "s": 2515, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 2679, "s": 2563, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 2683, "s": 2679, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/idTVHead\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_margin=\"5dp\" android:layout_marginTop=\"30dp\" android:text=\"Firebase Firestore as Realtime Database\" android:textAlignment=\"center\" android:textAllCaps=\"false\" android:textColor=\"@color/purple_500\" android:textSize=\"20sp\" /> <TextView android:id=\"@+id/idTVUpdate\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVHead\" android:layout_marginTop=\"50dp\" android:text=\"Updated Text\" android:textAlignment=\"center\" android:textColor=\"@color/purple_500\" android:textSize=\"30sp\" /> </RelativeLayout>", "e": 3862, "s": 2683, "text": null }, { "code": null, "e": 3910, "s": 3862, "text": "Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 4100, "s": 3910, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 4105, "s": 4100, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.DocumentSnapshot;import com.google.firebase.firestore.EventListener;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.FirebaseFirestoreException; public class MainActivity extends AppCompatActivity { // creating a variable for text view. TextView updatedTV; // initializing th variable for firebase firestore FirebaseFirestore db = FirebaseFirestore.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our text view. updatedTV = findViewById(R.id.idTVUpdate); // creating a variable for document reference. DocumentReference documentReference = db.collection(\"MyData\").document(\"Data\"); // adding snapshot listener to our document reference. documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { // inside the on event method. if (error != null) { // this method is called when error is not null // and we gt any error // in this cas we are displaying an error message. Toast.makeText(MainActivity.this, \"Error found is \" + error, Toast.LENGTH_SHORT).show(); return; } if (value != null && value.exists()) { // if th value from firestore is not null then we are getting // our data and setting that data to our text view. updatedTV.setText(value.getData().get(\"updateValue\").toString()); } } }); }}", "e": 6248, "s": 4105, "text": null }, { "code": null, "e": 6302, "s": 6248, "text": "Step 6: Adding data to the Firebase Firestore console" }, { "code": null, "e": 6488, "s": 6302, "text": "Go to the browser and open Firebase in your browser. After opening Firebase you will get to see the below page and on this page Click on Go to Console option in the top right corner. " }, { "code": null, "e": 6612, "s": 6488, "text": "After clicking on this screen you will get to see the below screen with your all project inside that select your project. " }, { "code": null, "e": 6689, "s": 6612, "text": "Inside that screen click n Firebase Firestore Database in the left window. " }, { "code": null, "e": 6774, "s": 6689, "text": "After clicking on the Create Database option you will get to see the below screen. " }, { "code": null, "e": 7062, "s": 6774, "text": "Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. " }, { "code": null, "e": 7567, "s": 7062, "text": "Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside our app and click on the submit button. To add data just click on the Start Collection button and provide the Collection ID as MyData. After that provide the Document ID as Data and inside the Field write down updateValue, and inside the Value provide your Text you want to display. And click on the Save button." }, { "code": null, "e": 7633, "s": 7567, "text": "You will get to see the data added inside the Firebase Console. " }, { "code": null, "e": 7822, "s": 7633, "text": "After adding the data to Firebase. Now run your app and see the output of the app. You can change the value in the updateValue field and you can get to see Realtime update on your device. " }, { "code": null, "e": 7942, "s": 7822, "text": "In the below video we are updating the data when the app is running and it is showing the Realtime Updates in our app. " }, { "code": null, "e": 7950, "s": 7942, "text": "android" }, { "code": null, "e": 7959, "s": 7950, "text": "Firebase" }, { "code": null, "e": 7983, "s": 7959, "text": "Technical Scripter 2020" }, { "code": null, "e": 7991, "s": 7983, "text": "Android" }, { "code": null, "e": 7996, "s": 7991, "text": "Java" }, { "code": null, "e": 8015, "s": 7996, "text": "Technical Scripter" }, { "code": null, "e": 8020, "s": 8015, "text": "Java" }, { "code": null, "e": 8028, "s": 8020, "text": "Android" }, { "code": null, "e": 8126, "s": 8028, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8195, "s": 8126, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 8227, "s": 8195, "text": "Android SDK and it's Components" }, { "code": null, "e": 8266, "s": 8227, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 8315, "s": 8266, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 8357, "s": 8315, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 8372, "s": 8357, "text": "Arrays in Java" }, { "code": null, "e": 8408, "s": 8372, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 8433, "s": 8408, "text": "Reverse a string in Java" }, { "code": null, "e": 8477, "s": 8433, "text": "Split() String method in Java with examples" } ]
scipy.rfft() in Python
29 Aug, 2020 With the help of scipy.rfft() method, we can compute the fast fourier transformation for real sequence and return the transformed vector by using this method. Syntax : scipy.fft.rfft(x) Return : Return the transformed vector. Example #1 : In this example we can see that by using scipy.rfft() method, we are able to compute the fast fourier transformation for real sequence and return the transformed vector by using this method. Python3 # import scipy and numpyimport scipyimport numpy as np x = np.arange(5)# Using scipy.fftfreq() methodgfg = scipy.fft.rfft(x) print(gfg) Output : [10. +0.j -2.5+3.4409548j -2.5+0.81229924j] Example #2 : Python3 # import scipy and numpyimport scipyimport numpy as np x = np.arange(10)# Using scipy.fftfreq() methodgfg = scipy.fft.rfft(x) print(gfg) Output : [45. +0.j -5.+15.38841769j -5. +6.8819096j -5. +3.63271264j -5. +1.62459848j -5. +0.j ] Python scipy-stats-functions Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 187, "s": 28, "text": "With the help of scipy.rfft() method, we can compute the fast fourier transformation for real sequence and return the transformed vector by using this method." }, { "code": null, "e": 214, "s": 187, "text": "Syntax : scipy.fft.rfft(x)" }, { "code": null, "e": 254, "s": 214, "text": "Return : Return the transformed vector." }, { "code": null, "e": 267, "s": 254, "text": "Example #1 :" }, { "code": null, "e": 458, "s": 267, "text": "In this example we can see that by using scipy.rfft() method, we are able to compute the fast fourier transformation for real sequence and return the transformed vector by using this method." }, { "code": null, "e": 466, "s": 458, "text": "Python3" }, { "code": "# import scipy and numpyimport scipyimport numpy as np x = np.arange(5)# Using scipy.fftfreq() methodgfg = scipy.fft.rfft(x) print(gfg)", "e": 604, "s": 466, "text": null }, { "code": null, "e": 613, "s": 604, "text": "Output :" }, { "code": null, "e": 666, "s": 613, "text": "[10. +0.j -2.5+3.4409548j -2.5+0.81229924j]" }, { "code": null, "e": 679, "s": 666, "text": "Example #2 :" }, { "code": null, "e": 687, "s": 679, "text": "Python3" }, { "code": "# import scipy and numpyimport scipyimport numpy as np x = np.arange(10)# Using scipy.fftfreq() methodgfg = scipy.fft.rfft(x) print(gfg)", "e": 826, "s": 687, "text": null }, { "code": null, "e": 835, "s": 826, "text": "Output :" }, { "code": null, "e": 904, "s": 835, "text": "[45. +0.j -5.+15.38841769j -5. +6.8819096j -5. +3.63271264j" }, { "code": null, "e": 939, "s": 904, "text": "-5. +1.62459848j -5. +0.j ]" }, { "code": null, "e": 968, "s": 939, "text": "Python scipy-stats-functions" }, { "code": null, "e": 981, "s": 968, "text": "Python-scipy" }, { "code": null, "e": 988, "s": 981, "text": "Python" } ]
Data Structures | Binary Trees | Question 8
10 Jul, 2018 The number of leaf nodes in a rooted tree of n nodes, with each node having 0 or 3 children is:(A) n/2(B) (n-1)/3(C) (n-1)/2(D) (2n+1)/3Answer: (D)Explanation: Let L be the number of leaf nodes and I be the number of internal nodes, then following relation holds for above given tree (For details, please see question 3 of this post) L = (3-1)I + 1 = 2I + 1 Total number of nodes(n) is sum of leaf nodes and internal nodes n = L + I After solving above two, we get L = (2n+1)/3Quiz of this Question Binary Trees Quiz Data Structures Data Structures-Binary Trees Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bit manipulation | Swap Endianness of a number Advantages of vector over array in C++ Amazon Interview Experience for SDE-II Binary Search Tree | Set 3 (Iterative Delete) Data Structures | Stack | Question 2 Data Structures | Linked List | Question 4 Data Structures | Balanced Binary Search Trees | Question 5 Difference between data type and data structure Data Structures | Linked List | Question 6 Improving Linear Search Technique
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jul, 2018" }, { "code": null, "e": 388, "s": 54, "text": "The number of leaf nodes in a rooted tree of n nodes, with each node having 0 or 3 children is:(A) n/2(B) (n-1)/3(C) (n-1)/2(D) (2n+1)/3Answer: (D)Explanation: Let L be the number of leaf nodes and I be the number of internal nodes, then following relation holds for above given tree (For details, please see question 3 of this post)" }, { "code": null, "e": 414, "s": 388, "text": " L = (3-1)I + 1 = 2I + 1" }, { "code": null, "e": 479, "s": 414, "text": "Total number of nodes(n) is sum of leaf nodes and internal nodes" }, { "code": null, "e": 491, "s": 479, "text": " n = L + I" }, { "code": null, "e": 557, "s": 491, "text": "After solving above two, we get L = (2n+1)/3Quiz of this Question" }, { "code": null, "e": 575, "s": 557, "text": "Binary Trees Quiz" }, { "code": null, "e": 591, "s": 575, "text": "Data Structures" }, { "code": null, "e": 620, "s": 591, "text": "Data Structures-Binary Trees" }, { "code": null, "e": 636, "s": 620, "text": "Data Structures" }, { "code": null, "e": 652, "s": 636, "text": "Data Structures" }, { "code": null, "e": 750, "s": 652, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 797, "s": 750, "text": "Bit manipulation | Swap Endianness of a number" }, { "code": null, "e": 836, "s": 797, "text": "Advantages of vector over array in C++" }, { "code": null, "e": 875, "s": 836, "text": "Amazon Interview Experience for SDE-II" }, { "code": null, "e": 921, "s": 875, "text": "Binary Search Tree | Set 3 (Iterative Delete)" }, { "code": null, "e": 958, "s": 921, "text": "Data Structures | Stack | Question 2" }, { "code": null, "e": 1001, "s": 958, "text": "Data Structures | Linked List | Question 4" }, { "code": null, "e": 1061, "s": 1001, "text": "Data Structures | Balanced Binary Search Trees | Question 5" }, { "code": null, "e": 1109, "s": 1061, "text": "Difference between data type and data structure" }, { "code": null, "e": 1152, "s": 1109, "text": "Data Structures | Linked List | Question 6" } ]
Web Search Bar Implementation Using Javascript Conditional Flow
05 Jun, 2020 Given a list of items and the task is to filter through the items and return the best match using the search bar. There are several approaches to implement this but, we will be using a simple if-else statement to implement our search bar. Approach: Create a folder called gfgSearchBar. Open the folder in your desired IDE or IDLE. Create a html file called approachOne.html Paste the below code into the html file. Example: <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <meta author="Emmanuel Onah" /> <title> GeeksforGeeks Search Bar </title></head> <style> * { margin: 0; padding: 0; } .container { box-sizing: border-box; } header { display: flex; align-content: center; align-items: center; justify-content: space-evenly; background: #d87093; padding: 0.5rem 1rem; } h3 { color: #000; font-family: Arial, Helvetica, sans-serif; font-size: 0.98rem; } input[type='search'] { padding: 0.5rem 2rem 0.5rem 0.4rem; border-radius: 4rem; font-size: 0.98rem; } .movieCollection { width: 100%; margin: 0 auto; padding: 1rem; box-sizing: border-box; display: flex; flex-wrap: wrap; justify-content: space-between; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } .movieWrapper { margin-top: 1.5rem; } img { width: 400px; height: 400px; display: block; }</style> <body> <div class="container"> <header> <h3>Geeks4Geeks Search Bar</h3> <input type="search" placeholder="search" id="searchBar" /> </header> <div class="movieCollection"> <div class="movieWrapper movieOne"> <h4>The city gate</h4> <time>01.02.1999</time> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png" alt="The city gate" /> </div> <div class="movieWrapper movieTwo"> <h4>Land of scientist</h4> <time>01.02.2000</time> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png" alt="Land of scientist" /> </div> <div class="movieWrapper movieThree"> <h4>Hidden treasure</h4> <time>01.02.2010</time> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png" alt="Hidden treasure" /> </div> <div class="movieWrapper movieFour"> <h4>Beautiful city of heroes</h4> <time>01.02.2020</time> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png" alt="Beautiful city of heroes" /> </div> <div class="movieWrapper movieFive"> <h4>The city gate</h4> <time>01.02.1999</time> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png" alt="The city gate" /> </div> <div class="movieWrapper movieSix"> <h4>Land of scientist</h4> <time>01.02.2000</time> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png" alt="Land of scientist" /> </div> </div> </div> <script> document.addEventListener('DOMContentLoaded', () => { const getSearchBar = document.querySelector('#searchBar'); const getAllMovies = document.querySelectorAll('.movieWrapper'); getSearchBar.addEventListener('keyup', e => { getAllMovies.forEach(movie => { if (movie.innerText.toLowerCase().includes( e.target.value.toLowerCase())) { movie.style.display = 'block'; return movie; } else { movie.style.display = 'none'; } }); }); }); </script></body> </html> Output: Explanation of the code inside the script tag: document.addEventListener(‘DOMContentLoaded’); This is a document event that gets executed or triggered immediately the html file gets loaded on your browser. Operations inside this event block doesn’t get executed until the html file is completely loaded to the DOM. const getSearchBar = document.querySelector(‘#searchBar’); We simply got the search bar element and pass it to getSearchBar variable. const getAllMovies = document.querySelectorAll(‘.movieWrapper’); We simply got all the movie divs and pass then to getAllMovies variable. Note that getAllMovies is a Nodelist of elements which is an Array look alike not an Array. getSearchBar.addEventListener(): We simply added a keyup event listener to the search bar. getAllMovies.forEach(movie => { if (movie.innerText.toLowerCase() .includes(e.target.value.toLowerCase())) { movie.style.display = 'block'; return movie; } else { movie.style.display = 'none'; } }); This block of code simply means the user types into the search bar are present in the movie text content, then style that movie box to be displayed in blocks and return all of them. Else don’t return any movie block. CSS-Misc HTML-Misc JavaScript-Misc 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. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 142, "s": 28, "text": "Given a list of items and the task is to filter through the items and return the best match using the search bar." }, { "code": null, "e": 267, "s": 142, "text": "There are several approaches to implement this but, we will be using a simple if-else statement to implement our search bar." }, { "code": null, "e": 277, "s": 267, "text": "Approach:" }, { "code": null, "e": 314, "s": 277, "text": "Create a folder called gfgSearchBar." }, { "code": null, "e": 359, "s": 314, "text": "Open the folder in your desired IDE or IDLE." }, { "code": null, "e": 402, "s": 359, "text": "Create a html file called approachOne.html" }, { "code": null, "e": 443, "s": 402, "text": "Paste the below code into the html file." }, { "code": null, "e": 452, "s": 443, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" /> <meta author=\"Emmanuel Onah\" /> <title> GeeksforGeeks Search Bar </title></head> <style> * { margin: 0; padding: 0; } .container { box-sizing: border-box; } header { display: flex; align-content: center; align-items: center; justify-content: space-evenly; background: #d87093; padding: 0.5rem 1rem; } h3 { color: #000; font-family: Arial, Helvetica, sans-serif; font-size: 0.98rem; } input[type='search'] { padding: 0.5rem 2rem 0.5rem 0.4rem; border-radius: 4rem; font-size: 0.98rem; } .movieCollection { width: 100%; margin: 0 auto; padding: 1rem; box-sizing: border-box; display: flex; flex-wrap: wrap; justify-content: space-between; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } .movieWrapper { margin-top: 1.5rem; } img { width: 400px; height: 400px; display: block; }</style> <body> <div class=\"container\"> <header> <h3>Geeks4Geeks Search Bar</h3> <input type=\"search\" placeholder=\"search\" id=\"searchBar\" /> </header> <div class=\"movieCollection\"> <div class=\"movieWrapper movieOne\"> <h4>The city gate</h4> <time>01.02.1999</time> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png\" alt=\"The city gate\" /> </div> <div class=\"movieWrapper movieTwo\"> <h4>Land of scientist</h4> <time>01.02.2000</time> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png\" alt=\"Land of scientist\" /> </div> <div class=\"movieWrapper movieThree\"> <h4>Hidden treasure</h4> <time>01.02.2010</time> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png\" alt=\"Hidden treasure\" /> </div> <div class=\"movieWrapper movieFour\"> <h4>Beautiful city of heroes</h4> <time>01.02.2020</time> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png\" alt=\"Beautiful city of heroes\" /> </div> <div class=\"movieWrapper movieFive\"> <h4>The city gate</h4> <time>01.02.1999</time> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png\" alt=\"The city gate\" /> </div> <div class=\"movieWrapper movieSix\"> <h4>Land of scientist</h4> <time>01.02.2000</time> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190812003701/html7.png\" alt=\"Land of scientist\" /> </div> </div> </div> <script> document.addEventListener('DOMContentLoaded', () => { const getSearchBar = document.querySelector('#searchBar'); const getAllMovies = document.querySelectorAll('.movieWrapper'); getSearchBar.addEventListener('keyup', e => { getAllMovies.forEach(movie => { if (movie.innerText.toLowerCase().includes( e.target.value.toLowerCase())) { movie.style.display = 'block'; return movie; } else { movie.style.display = 'none'; } }); }); }); </script></body> </html>", "e": 4672, "s": 452, "text": null }, { "code": null, "e": 4680, "s": 4672, "text": "Output:" }, { "code": null, "e": 4727, "s": 4680, "text": "Explanation of the code inside the script tag:" }, { "code": null, "e": 4995, "s": 4727, "text": "document.addEventListener(‘DOMContentLoaded’); This is a document event that gets executed or triggered immediately the html file gets loaded on your browser. Operations inside this event block doesn’t get executed until the html file is completely loaded to the DOM." }, { "code": null, "e": 5129, "s": 4995, "text": "const getSearchBar = document.querySelector(‘#searchBar’); We simply got the search bar element and pass it to getSearchBar variable." }, { "code": null, "e": 5359, "s": 5129, "text": "const getAllMovies = document.querySelectorAll(‘.movieWrapper’); We simply got all the movie divs and pass then to getAllMovies variable. Note that getAllMovies is a Nodelist of elements which is an Array look alike not an Array." }, { "code": null, "e": 5450, "s": 5359, "text": "getSearchBar.addEventListener(): We simply added a keyup event listener to the search bar." }, { "code": null, "e": 5694, "s": 5450, "text": "getAllMovies.forEach(movie => {\n if (movie.innerText.toLowerCase()\n .includes(e.target.value.toLowerCase())) {\n movie.style.display = 'block';\n return movie;\n }\n else {\n movie.style.display = 'none';\n }\n});\n" }, { "code": null, "e": 5911, "s": 5694, "text": "This block of code simply means the user types into the search bar are present in the movie text content, then style that movie box to be displayed in blocks and return all of them. Else don’t return any movie block." }, { "code": null, "e": 5920, "s": 5911, "text": "CSS-Misc" }, { "code": null, "e": 5930, "s": 5920, "text": "HTML-Misc" }, { "code": null, "e": 5946, "s": 5930, "text": "JavaScript-Misc" }, { "code": null, "e": 5950, "s": 5946, "text": "CSS" }, { "code": null, "e": 5955, "s": 5950, "text": "HTML" }, { "code": null, "e": 5966, "s": 5955, "text": "JavaScript" }, { "code": null, "e": 5983, "s": 5966, "text": "Web Technologies" }, { "code": null, "e": 6010, "s": 5983, "text": "Web technologies Questions" }, { "code": null, "e": 6015, "s": 6010, "text": "HTML" }, { "code": null, "e": 6113, "s": 6015, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6152, "s": 6113, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 6191, "s": 6152, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 6230, "s": 6191, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 6267, "s": 6230, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 6296, "s": 6267, "text": "Form validation using jQuery" }, { "code": null, "e": 6320, "s": 6296, "text": "REST API (Introduction)" }, { "code": null, "e": 6373, "s": 6320, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 6433, "s": 6373, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 6494, "s": 6433, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python Set | symmetric_difference()
06 Feb, 2018 This in-built function of Python Set helps us to get the symmetric difference between two sets, which is equal to the elements present in either of the two sets, but not common to both the sets. Let’s look at the Venn diagram of the symmetric_difference between two sets. Symmetric Difference is marked in Green If there are a set_A and set_B, then the symmetric difference between them will be equal to the union of set_A and set_B without the intersection between the two. // Takes a single parameter that has to be // a set and returns a new set which is the // symmetric difference between the two sets. set_A.symmetric_difference(set_B) Examples: Input: set_A = {1, 2, 3, 4, 5} set_B = {6, 7, 3, 9, 4} Output : {1, 2, 5, 6, 7, 9} Explanation: The common elements {3, 4} are discarded from the output. Input: set_A = {"ram", "rahim", "ajay", "rishav", "aakash"} set_B = {"aakash", "ajay", "shyam", "ram", "ravi"} Output: {"rahim", "rishav", "shyam", "ravi"} Explanation: The common elements {"ram", "ajay", "aakash"} are discarded from the final set In this program we will try to find the symmetric difference between two sets: # Python code to find the symmetric_difference# Use of symmetric_difference() method set_A = {1, 2, 3, 4, 5}set_B = {6, 7, 3, 9, 4}print(set_A.symmetric_difference(set_B)) Output: {1, 2, 5, 6, 7, 9} There is also another method to get the symmetric difference between two sets, by the use of an operator “^“.Example: # Python code to find the Symmetric difference# using ^ operator. # Driver Codeset_A = {"ram", "rahim", "ajay", "rishav", "aakash"}set_B = {"aakash", "ajay", "shyam", "ram", "ravi"}print(set_A ^ set_B) Output: {'shyam', 'ravi', 'rahim', 'rishav'} # One more example Python code to find # the symmetric_difference use of # symmetric_difference() method A = {'p', 'a', 'w', 'a', 'n'}B = {'r', 'a', 'o', 'n', 'e'}C = {} print(A.symmetric_difference(B))print(B.symmetric_difference(A)) print(A.symmetric_difference(C))print(B.symmetric_difference(C)) # this example is contributed by sunny6041 Output: set(['e', 'o', 'p', 'r', 'w']) set(['e', 'o', 'p', 'r', 'w']) set(['a', 'p', 'w', 'n']) set(['a', 'r', 'e', 'o', 'n']) python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Feb, 2018" }, { "code": null, "e": 300, "s": 28, "text": "This in-built function of Python Set helps us to get the symmetric difference between two sets, which is equal to the elements present in either of the two sets, but not common to both the sets. Let’s look at the Venn diagram of the symmetric_difference between two sets." }, { "code": null, "e": 340, "s": 300, "text": "Symmetric Difference is marked in Green" }, { "code": null, "e": 503, "s": 340, "text": "If there are a set_A and set_B, then the symmetric difference between them will be equal to the union of set_A and set_B without the intersection between the two." }, { "code": null, "e": 672, "s": 503, "text": "// Takes a single parameter that has to be \n// a set and returns a new set which is the \n// symmetric difference between the two sets.\nset_A.symmetric_difference(set_B)" }, { "code": null, "e": 682, "s": 672, "text": "Examples:" }, { "code": null, "e": 1096, "s": 682, "text": "Input: set_A = {1, 2, 3, 4, 5}\n set_B = {6, 7, 3, 9, 4}\nOutput : {1, 2, 5, 6, 7, 9}\nExplanation: The common elements {3, 4} \nare discarded from the output.\n\nInput:\nset_A = {\"ram\", \"rahim\", \"ajay\", \"rishav\", \"aakash\"}\nset_B = {\"aakash\", \"ajay\", \"shyam\", \"ram\", \"ravi\"}\nOutput: {\"rahim\", \"rishav\", \"shyam\", \"ravi\"}\n\nExplanation: The common elements {\"ram\", \"ajay\", \n\"aakash\"} are discarded from the final set" }, { "code": null, "e": 1175, "s": 1096, "text": "In this program we will try to find the symmetric difference between two sets:" }, { "code": "# Python code to find the symmetric_difference# Use of symmetric_difference() method set_A = {1, 2, 3, 4, 5}set_B = {6, 7, 3, 9, 4}print(set_A.symmetric_difference(set_B))", "e": 1348, "s": 1175, "text": null }, { "code": null, "e": 1356, "s": 1348, "text": "Output:" }, { "code": null, "e": 1375, "s": 1356, "text": "{1, 2, 5, 6, 7, 9}" }, { "code": null, "e": 1493, "s": 1375, "text": "There is also another method to get the symmetric difference between two sets, by the use of an operator “^“.Example:" }, { "code": "# Python code to find the Symmetric difference# using ^ operator. # Driver Codeset_A = {\"ram\", \"rahim\", \"ajay\", \"rishav\", \"aakash\"}set_B = {\"aakash\", \"ajay\", \"shyam\", \"ram\", \"ravi\"}print(set_A ^ set_B)", "e": 1696, "s": 1493, "text": null }, { "code": null, "e": 1704, "s": 1696, "text": "Output:" }, { "code": null, "e": 1741, "s": 1704, "text": "{'shyam', 'ravi', 'rahim', 'rishav'}" }, { "code": "# One more example Python code to find # the symmetric_difference use of # symmetric_difference() method A = {'p', 'a', 'w', 'a', 'n'}B = {'r', 'a', 'o', 'n', 'e'}C = {} print(A.symmetric_difference(B))print(B.symmetric_difference(A)) print(A.symmetric_difference(C))print(B.symmetric_difference(C)) # this example is contributed by sunny6041", "e": 2088, "s": 1741, "text": null }, { "code": null, "e": 2096, "s": 2088, "text": "Output:" }, { "code": null, "e": 2216, "s": 2096, "text": "set(['e', 'o', 'p', 'r', 'w'])\nset(['e', 'o', 'p', 'r', 'w'])\nset(['a', 'p', 'w', 'n'])\nset(['a', 'r', 'e', 'o', 'n'])\n" }, { "code": null, "e": 2227, "s": 2216, "text": "python-set" }, { "code": null, "e": 2234, "s": 2227, "text": "Python" }, { "code": null, "e": 2245, "s": 2234, "text": "python-set" }, { "code": null, "e": 2343, "s": 2245, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2385, "s": 2343, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2407, "s": 2385, "text": "Enumerate() in Python" }, { "code": null, "e": 2433, "s": 2407, "text": "Python String | replace()" }, { "code": null, "e": 2465, "s": 2433, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2494, "s": 2465, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2521, "s": 2494, "text": "Python Classes and Objects" }, { "code": null, "e": 2542, "s": 2521, "text": "Python OOPs Concepts" }, { "code": null, "e": 2565, "s": 2542, "text": "Introduction To PYTHON" }, { "code": null, "e": 2601, "s": 2565, "text": "Convert integer to string in Python" } ]
Python input() Function
05 Nov, 2021 Python input() function is used to take user input. By default, it returns the user input in form of a string. Syntax input(prompt) Parameter: Prompt: A String, representing a default message (usually screen) before the input. However, it is optional to have a prompt message. Return: input() returns a string object. Even if the inputted value is an integer it converts it into a string. By Default, input returns a string. So the name and age will be stored as strings. Python # Taking name of the user as input # and storing it name variablename = input("Please Enter Your Name: ") # taking age of the user as input and # storing in into variable ageage = input("Please Enter Your Age: ") # printing itprint("The name of the user is {0} and his/her age is {1}".format(name, age)) Output: In this example, we will be looking at how to take integer input from users. To take integer input we will be using int() along with input() Python # Taking number 1 from user as intnum1 = int(input("Please Enter First Number: ")) # Taking number 2 from user as intnum2 = int(input("Please Enter Second Number: ")) # adding num1 and num2 and storing them in# variable additionaddition = num1 + num2 # printingprint("The sum of the two given numbers is {} ".format(addition)) Output: Similarly, we can use float() to take two float numbers. Let’s see one more example of how to take lists as input Python # Taking list1 input from user as listlist1 = list(input("Please Enter Elements of list1: ")) # Taking list2 input from user as listlist2 = list(input("Please Enter Elements of list2: ")) # appending list2 into list1 using .append functionfor i in list2: list1.append(i) # printing list1print(list1) Output: Picked Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Nov, 2021" }, { "code": null, "e": 165, "s": 54, "text": "Python input() function is used to take user input. By default, it returns the user input in form of a string." }, { "code": null, "e": 172, "s": 165, "text": "Syntax" }, { "code": null, "e": 186, "s": 172, "text": "input(prompt)" }, { "code": null, "e": 197, "s": 186, "text": "Parameter:" }, { "code": null, "e": 332, "s": 197, "text": "Prompt: A String, representing a default message (usually screen) before the input. However, it is optional to have a prompt message." }, { "code": null, "e": 444, "s": 332, "text": "Return: input() returns a string object. Even if the inputted value is an integer it converts it into a string." }, { "code": null, "e": 527, "s": 444, "text": "By Default, input returns a string. So the name and age will be stored as strings." }, { "code": null, "e": 534, "s": 527, "text": "Python" }, { "code": "# Taking name of the user as input # and storing it name variablename = input(\"Please Enter Your Name: \") # taking age of the user as input and # storing in into variable ageage = input(\"Please Enter Your Age: \") # printing itprint(\"The name of the user is {0} and his/her age is {1}\".format(name, age))", "e": 840, "s": 534, "text": null }, { "code": null, "e": 848, "s": 840, "text": "Output:" }, { "code": null, "e": 989, "s": 848, "text": "In this example, we will be looking at how to take integer input from users. To take integer input we will be using int() along with input()" }, { "code": null, "e": 996, "s": 989, "text": "Python" }, { "code": "# Taking number 1 from user as intnum1 = int(input(\"Please Enter First Number: \")) # Taking number 2 from user as intnum2 = int(input(\"Please Enter Second Number: \")) # adding num1 and num2 and storing them in# variable additionaddition = num1 + num2 # printingprint(\"The sum of the two given numbers is {} \".format(addition))", "e": 1326, "s": 996, "text": null }, { "code": null, "e": 1334, "s": 1326, "text": "Output:" }, { "code": null, "e": 1448, "s": 1334, "text": "Similarly, we can use float() to take two float numbers. Let’s see one more example of how to take lists as input" }, { "code": null, "e": 1455, "s": 1448, "text": "Python" }, { "code": "# Taking list1 input from user as listlist1 = list(input(\"Please Enter Elements of list1: \")) # Taking list2 input from user as listlist2 = list(input(\"Please Enter Elements of list2: \")) # appending list2 into list1 using .append functionfor i in list2: list1.append(i) # printing list1print(list1)", "e": 1763, "s": 1455, "text": null }, { "code": null, "e": 1771, "s": 1763, "text": "Output:" }, { "code": null, "e": 1778, "s": 1771, "text": "Picked" }, { "code": null, "e": 1795, "s": 1778, "text": "Python-Functions" }, { "code": null, "e": 1802, "s": 1795, "text": "Python" } ]
Update multiple rows in same query in PostgreSQL using Pyscopg2-Python
17 Oct, 2021 In this article, we are going to update multiple rows in the same query in PostgreSQL using Pyscopg2in Python. We can update multiple values at once by using the update clause from PostgreSQL. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. UPDATE "table" SET "column_one" = value1, "column_two" = value2, "column_three" = valueN WHERE condition; Python3 import psycopg2 conn = psycopg2.connect( database="classroom_database", user='postgres', password='pass', host='127.0.0.1', port='5432') conn.autocommit = Truecursor = conn.cursor() sql = ''' update student_details set cgpa = 9.5 , branch = 'AE' where student_name = 'rahul';''' cursor.execute(sql) sql1 = '''select * from student_details;'''cursor.execute(sql1) for i in cursor.fetchall(): print(i) conn.commit()conn.close() Output: (12124468, 'arjun', 9.7, '[email protected]', 'CSE') (12124469, 'DIYA', 9.4, '[email protected]', 'CSE') (12124466, 'sarah', 9.8, '[email protected]', 'CSE') (12124470, 'priya', 8.8, '[email protected]', 'CSE') (12124467, 'rahul', 9.5, '[email protected]', 'AE') Output in PostgreSQL: Picked Python PostgreSQL Python Pyscopg2 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Oct, 2021" }, { "code": null, "e": 139, "s": 28, "text": "In this article, we are going to update multiple rows in the same query in PostgreSQL using Pyscopg2in Python." }, { "code": null, "e": 349, "s": 139, "text": "We can update multiple values at once by using the update clause from PostgreSQL. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. " }, { "code": null, "e": 457, "s": 349, "text": "UPDATE \"table\"\nSET \"column_one\" = value1, \n\"column_two\" = value2, \n\"column_three\" = valueN\nWHERE condition;" }, { "code": null, "e": 465, "s": 457, "text": "Python3" }, { "code": "import psycopg2 conn = psycopg2.connect( database=\"classroom_database\", user='postgres', password='pass', host='127.0.0.1', port='5432') conn.autocommit = Truecursor = conn.cursor() sql = ''' update student_details set cgpa = 9.5 , branch = 'AE' where student_name = 'rahul';''' cursor.execute(sql) sql1 = '''select * from student_details;'''cursor.execute(sql1) for i in cursor.fetchall(): print(i) conn.commit()conn.close()", "e": 941, "s": 465, "text": null }, { "code": null, "e": 949, "s": 941, "text": "Output:" }, { "code": null, "e": 1208, "s": 949, "text": "(12124468, 'arjun', 9.7, '[email protected]', 'CSE')\n(12124469, 'DIYA', 9.4, '[email protected]', 'CSE')\n(12124466, 'sarah', 9.8, '[email protected]', 'CSE')\n(12124470, 'priya', 8.8, '[email protected]', 'CSE')\n(12124467, 'rahul', 9.5, '[email protected]', 'AE')" }, { "code": null, "e": 1230, "s": 1208, "text": "Output in PostgreSQL:" }, { "code": null, "e": 1237, "s": 1230, "text": "Picked" }, { "code": null, "e": 1255, "s": 1237, "text": "Python PostgreSQL" }, { "code": null, "e": 1271, "s": 1255, "text": "Python Pyscopg2" }, { "code": null, "e": 1278, "s": 1271, "text": "Python" }, { "code": null, "e": 1376, "s": 1278, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1408, "s": 1376, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1435, "s": 1408, "text": "Python Classes and Objects" }, { "code": null, "e": 1456, "s": 1435, "text": "Python OOPs Concepts" }, { "code": null, "e": 1479, "s": 1456, "text": "Introduction To PYTHON" }, { "code": null, "e": 1535, "s": 1479, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1566, "s": 1535, "text": "Python | os.path.join() method" }, { "code": null, "e": 1608, "s": 1566, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1650, "s": 1608, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1689, "s": 1650, "text": "Python | Get unique values from a list" } ]
Print the longest common substring
09 Apr, 2022 Given two strings ‘X’ and ‘Y’, print the length of the longest common substring. If two or more substrings have the same value for the longest common substring, then print any one of them. Examples: Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : Geeks Input : X = "zxabcdezy", Y = "yzabcdezx" Output : abcdez We have discussed a solution to find the length of the longest common string. In this post, we have discussed printing common string is discussed. Naive Approach: Let strings X and Y be the lengths m and n respectively. Generate all possible substrings of X which requires a time complexity of O(m2) and search each substring in the string Y which can be achieved in O(n) time complexity using the KMP algorithm. Overall time complexity will be O(n * m2). Efficient Approach: It is based on the dynamic programming implementation explained in this post. The longest suffix matrix LCSuff[][] is build up and the index of the cell having the maximum value is tracked. Let that index be represented by (row, col) pair. Now the final longest common substring is built with the help of that index by diagonally traversing up the LCSuff[][] matrix until LCSuff[row][col] != 0 and during the iteration obtaining the characters either from X[row-1] or Y[col-1] and adding them from right to left in the resultant common string. C++ Java Python3 C# Javascript // C++ implementation to print the longest common substring#include <iostream>#include <stdlib.h>#include <string.h> using namespace std; /* function to find and print the longest common substring of X[0..m-1] and Y[0..n-1] */void printLCSubStr(char* X, char* Y, int m, int n){ // Create a table to store lengths of longest common // suffixes of substrings. Note that LCSuff[i][j] // contains length of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and first column entries // have no logical meaning, they are used only for // simplicity of program int LCSuff[m + 1][n + 1]; // To store length of the longest common substring int len = 0; // To store the index of the cell which contains the // maximum value. This cell's index helps in building // up the longest common substring from right to left. int row, col; /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) LCSuff[i][j] = 0; else if (X[i - 1] == Y[j - 1]) { LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1; if (len < LCSuff[i][j]) { len = LCSuff[i][j]; row = i; col = j; } } else LCSuff[i][j] = 0; } } // if true, then no common substring exists if (len == 0) { cout << "No Common Substring"; return; } // allocate space for the longest common substring char* resultStr = (char*)malloc((len + 1) * sizeof(char)); // traverse up diagonally form the (row, col) cell // until LCSuff[row][col] != 0 while (LCSuff[row][col] != 0) { resultStr[--len] = X[row - 1]; // or Y[col-1] // move diagonally up to previous cell row--; col--; } // required longest common substring cout << resultStr;} /* Driver program to test above function */int main(){ char X[] = "OldSite:GeeksforGeeks.org"; char Y[] = "NewSite:GeeksQuiz.com"; int m = strlen(X); int n = strlen(Y); printLCSubStr(X, Y, m, n); return 0;} // Java implementation to print the longest common substringpublic class Longest_common_substr { /* function to find and print the longest common substring of X[0..m-1] and Y[0..n-1] */ static void printLCSubStr(String X, String Y, int m, int n) { // Create a table to store lengths of longest common // suffixes of substrings. Note that LCSuff[i][j] // contains length of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and first column entries // have no logical meaning, they are used only for // simplicity of program int[][] LCSuff = new int[m + 1][n + 1]; // To store length of the longest common substring int len = 0; // To store the index of the cell which contains the // maximum value. This cell's index helps in building // up the longest common substring from right to left. int row = 0, col = 0; /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) LCSuff[i][j] = 0; else if (X.charAt(i - 1) == Y.charAt(j - 1)) { LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1; if (len < LCSuff[i][j]) { len = LCSuff[i][j]; row = i; col = j; } } else LCSuff[i][j] = 0; } } // if true, then no common substring exists if (len == 0) { System.out.println("No Common Substring"); return; } // allocate space for the longest common substring String resultStr = ""; // traverse up diagonally form the (row, col) cell // until LCSuff[row][col] != 0 while (LCSuff[row][col] != 0) { resultStr = X.charAt(row - 1) + resultStr; // or Y[col-1] --len; // move diagonally up to previous cell row--; col--; } // required longest common substring System.out.println(resultStr); } /* Driver program to test above function */ public static void main(String args[]) { String X = "OldSite:GeeksforGeeks.org"; String Y = "NewSite:GeeksQuiz.com"; int m = X.length(); int n = Y.length(); printLCSubStr(X, Y, m, n); }}// This code is contributed by Sumit Ghosh # Python3 implementation to print# the longest common substring # function to find and print # the longest common substring of# X[0..m-1] and Y[0..n-1]def printLCSSubStr(X: str, Y: str, m: int, n: int): # Create a table to store lengths of # longest common suffixes of substrings. # Note that LCSuff[i][j] contains length # of longest common suffix of X[0..i-1] and # Y[0..j-1]. The first row and first # column entries have no logical meaning, # they are used only for simplicity of program LCSuff = [[0 for i in range(n + 1)] for j in range(m + 1)] # To store length of the # longest common substring length = 0 # To store the index of the cell # which contains the maximum value. # This cell's index helps in building # up the longest common substring # from right to left. row, col = 0, 0 # Following steps build LCSuff[m+1][n+1] # in bottom up fashion. for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: LCSuff[i][j] = 0 else if X[i - 1] == Y[j - 1]: LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1 if length < LCSuff[i][j]: length = LCSuff[i][j] row = i col = j else: LCSuff[i][j] = 0 # if true, then no common substring exists if length == 0: print("No Common Substring") return # allocate space for the longest # common substring resultStr = ['0'] * length # traverse up diagonally form the # (row, col) cell until LCSuff[row][col] != 0 while LCSuff[row][col] != 0: length -= 1 resultStr[length] = X[row - 1] # or Y[col-1] # move diagonally up to previous cell row -= 1 col -= 1 # required longest common substring print(''.join(resultStr)) # Driver Codeif __name__ == "__main__": X = "OldSite:GeeksforGeeks.org" Y = "NewSite:GeeksQuiz.com" m = len(X) n = len(Y) printLCSSubStr(X, Y, m, n) # This code is contributed by# sanjeev2552 // C# implementation to print the// longest common substringusing System; class GFG { /* function to find and print the longest common substring of X[0..m-1] and Y[0..n-1] */ static void printLCSubStr(String X, String Y, int m, int n) { // Create a table to store lengths of longest common // suffixes of substrings. Note that LCSuff[i][j] // contains length of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and first column entries // have no logical meaning, they are used only for // simplicity of program int[, ] LCSuff = new int[m + 1, n + 1]; // To store length of the longest common substring int len = 0; // To store the index of the cell which contains the // maximum value. This cell's index helps in building // up the longest common substring from right to left. int row = 0, col = 0; /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) LCSuff[i, j] = 0; else if (X[i - 1] == Y[j - 1]) { LCSuff[i, j] = LCSuff[i - 1, j - 1] + 1; if (len < LCSuff[i, j]) { len = LCSuff[i, j]; row = i; col = j; } } else LCSuff[i, j] = 0; } } // if true, then no common substring exists if (len == 0) { Console.Write("No Common Substring"); return; } // allocate space for the longest common substring String resultStr = ""; // traverse up diagonally form the (row, col) cell // until LCSuff[row][col] != 0 while (LCSuff[row, col] != 0) { resultStr = X[row - 1] + resultStr; // or Y[col-1] --len; // move diagonally up to previous cell row--; col--; } // required longest common substring Console.WriteLine(resultStr); } /* Driver program to test above function */ public static void Main() { String X = "OldSite:GeeksforGeeks.org"; String Y = "NewSite:GeeksQuiz.com"; int m = X.Length; int n = Y.Length; printLCSubStr(X, Y, m, n); }} // This code is contributed by Sam007 <script>// Javascript implementation to print the longest common substring /* function to find and print the longest common substring of X[0..m-1] and Y[0..n-1] */ function printLCSubStr(X,Y,m,n) { // Create a table to store lengths of longest common // suffixes of substrings. Note that LCSuff[i][j] // contains length of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and first column entries // have no logical meaning, they are used only for // simplicity of program let LCSuff = new Array(m+1); // To store length of the longest common substring let len = 0; // To store the index of the cell which contains the // maximum value. This cell's index helps in building // up the longest common substring from right to left. let row = 0, col = 0; /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */ for (let i = 0; i <= m; i++) { LCSuff[i] = Array(n+1); for (let j = 0; j <= n; j++) { LCSuff[i][j]=0; if (i == 0 || j == 0) LCSuff[i][j] = 0; else if (X[i-1] == Y[j-1]) { LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1; if (len < LCSuff[i][j]) { len = LCSuff[i][j]; row = i; col = j; } } else LCSuff[i][j] = 0; } } // if true, then no common substring exists if (len == 0) { document.write("No Common Substring"); return; } // allocate space for the longest common substring let resultStr = ""; // traverse up diagonally form the (row, col) cell // until LCSuff[row][col] != 0 while (LCSuff[row][col] != 0) { resultStr = X[row-1] + resultStr; // or Y[col-1] --len; // move diagonally up to previous cell row--; col--; } // required longest common substring document.write(resultStr); } /* Driver program to test above function */ let X = "OldSite:GeeksforGeeks.org"; let Y = "NewSite:GeeksQuiz.com"; let m = X.length; let n = Y.length; printLCSubStr(X, Y, m, n); //This code is contributed by rag2127 </script> Site:Geeks Time Complexity: O(m*n). Auxiliary Space: O(m*n). Space Optimized Approach: The auxiliary space used by the solution above is O(m*n), where m and n are lengths of string X and Y. The space used by the above solution can be reduced to O(2*n). A variable end is used to store the ending point of the longest common substring in string X and variable maxlen is used to store the length of the longest common substring. Suppose we are at DP state when the length of X is i and length of Y is j, the result of which is stored in len[i][j]. Now if X[i-1] == Y[j-1], then len[i][j] = 1 + len[i-1][j-1], that is result of current row in matrix len[][] depends on values from previous row. Hence, the required length of the longest common substring can be obtained by maintaining values of two consecutive rows only, thereby reducing space requirements to O(2*n). To print the longest common substring, we use a variable end. When len[i][j] is calculated, it is compared with maxlen. If maxlen is less than len[i][j], then end is updated to i-1 to show that longest common substring ends at index i-1 in X and maxlen is updated to len[i][j]. The longest common substring then is from index end – maxlen + 1 to index end in X. A variable currRow is used to represent that either row 0 or row 1 of len[2][n] matrix is currently used to find the length. Initially, row 0 is used as the current row for the case when the length of string X is zero. At the end of each iteration, the current row is made the previous row and the previous row is made the new current row. Given below is the implementation of the above approach: C++ Java Python3 C# Javascript // Space optimized CPP implementation to print// longest common substring.#include <bits/stdc++.h>using namespace std; // Function to find longest common substring.string LCSubStr(string X, string Y){ // Find length of both the strings. int m = X.length(); int n = Y.length(); // Variable to store length of longest // common substring. int result = 0; // Variable to store ending point of // longest common substring in X. int end; // Matrix to store result of two // consecutive rows at a time. int len[2][n + 1]; // Variable to represent which row of // matrix is current row. int currRow = 0; // For a particular value of i and j, // len[currRow][j] stores length of longest // common substring in string X[0..i] and Y[0..j]. for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { len[currRow][j] = 0; } else if (X[i - 1] == Y[j - 1]) { len[currRow][j] = len[1 - currRow][j - 1] + 1; if (len[currRow][j] > result) { result = len[currRow][j]; end = i - 1; } } else { len[currRow][j] = 0; } } // Make current row as previous row and // previous row as new current row. currRow = 1 - currRow; } // If there is no common substring, print -1. if (result == 0) { return "-1"; } // Longest common substring is from index // end - result + 1 to index end in X. return X.substr(end - result + 1, result);}// Driver Codeint main(){ string X = "GeeksforGeeks"; string Y = "GeeksQuiz"; // function call cout << LCSubStr(X, Y); return 0;} // Space optimized Java implementation to print// longest common substring. public class GFG { // Function to find longest common substring. static String LCSubStr(String X, String Y) { // Find length of both the Strings. int m = X.length(); int n = Y.length(); // Variable to store length of longest // common subString. int result = 0; // Variable to store ending point of // longest common subString in X. int end = 0; // Matrix to store result of two // consecutive rows at a time. int len[][] = new int[2][m]; // Variable to represent which row of // matrix is current row. int currRow = 0; // For a particular value of i and j, // len[currRow][j] stores length of longest // common subString in String X[0..i] and Y[0..j]. for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { len[currRow][j] = 0; } else if (X.charAt(i - 1) == Y.charAt(j - 1)) { len[currRow][j] = len[1 - currRow][j - 1] + 1; if (len[currRow][j] > result) { result = len[currRow][j]; end = i - 1; } } else { len[currRow][j] = 0; } } // Make current row as previous row and // previous row as new current row. currRow = 1 - currRow; } // If there is no common subString, print -1. if (result == 0) { return "-1"; } // Longest common subString is from index // end - result + 1 to index end in X. return X.substring(end - result + 1, result); } // Driver Code public static void main(String[] args) { String X = "GeeksforGeeks"; String Y = "GeeksQuiz"; // function call System.out.println(LCSubStr(X, Y)); } }// This code is contributed by PrinciRaj1992 # Space optimized Python3 implementation to# print longest common substring. # Function to find longest common substring.def LCSubStr(X, Y): # Find length of both the strings. m = len(X) n = len(Y) # Variable to store length of longest # common substring. result = 0 # Variable to store ending point of # longest common substring in X. end = 0 # Matrix to store result of two # consecutive rows at a time. length = [[0 for j in range(m)] for i in range(2)] # Variable to represent which row of # matrix is current row. currRow = 0 # For a particular value of i and j, # length[currRow][j] stores length # of longest common substring in # string X[0..i] and Y[0..j]. for i in range(0, m + 1): for j in range(0, n + 1): if (i == 0 or j == 0): length[currRow][j] = 0 elif (X[i - 1] == Y[j - 1]): length[currRow][j] = length[1 - currRow][j - 1] + 1 if (length[currRow][j] > result): result = length[currRow][j] end = i - 1 else: length[currRow][j] = 0 # Make current row as previous row and # previous row as new current row. currRow = 1 - currRow # If there is no common substring, print -1. if (result == 0): return "-1" # Longest common substring is from index # end - result + 1 to index end in X. return X[end - result + 1 : end + 1] # Driver codeif __name__=="__main__": X = "GeeksforGeeks" Y = "GeeksQuiz" # Function call print(LCSubStr(X, Y)) # This code is contributed by rutvik_56 using System;// Space optimized Java implementation to print// longest common substring. public class GFG { // Function to find longest common substring. static string LCSubStr(string X, string Y) { // Find length of both the Strings. int m = X.Length; int n = Y.Length; // Variable to store length of longest // common subString. int result = 0; // Variable to store ending point of // longest common subString in X. int end = 0; // Matrix to store result of two // consecutive rows at a time. int[,] len = new int[2,m]; // Variable to represent which row of // matrix is current row. int currRow = 0; // For a particular value of i and j, // len[currRow][j] stores length of longest // common subString in String X[0..i] and Y[0..j]. for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { len[currRow,j] = 0; } else if (X[i - 1] == Y[j - 1]) { len[currRow,j] = len[1 - currRow,j - 1] + 1; if (len[currRow,j] > result) { result = len[currRow,j]; end = i - 1; } } else { len[currRow,j] = 0; } } // Make current row as previous row and // previous row as new current row. currRow = 1 - currRow; } // If there is no common subString, print -1. if (result == 0) { return "-1"; } // Longest common subString is from index // end - result + 1 to index end in X. return X.Substring(end - result + 1, result); } // Driver Code public static void Main() { string X = "GeeksforGeeks"; string Y = "GeeksQuiz"; // function call Console.Write(LCSubStr(X, Y)); } } <script>// Space optimized javascript implementation to print// longest common substring. // Function to find longest common substring. function LCSubStr(X,Y) { // Find length of both the strings. let m = X.length; let n = Y.length; // Variable to store length of longest // common substring. let result = 0; // Variable to store ending point of // longest common substring in X. let end; // Matrix to store result of two // consecutive rows at a time. let len= new Array(2); for(let i=0;i<len.length;i++) { len[i]=new Array(n); for(let j=0;j<n;j++) { len[i][j]=0; } } // Variable to represent which row of // matrix is current row. let currRow = 0; // For a particular value of i and j, // len[currRow][j] stores length of longest // common substring in string X[0..i] and Y[0..j]. for (let i = 0; i <= m; i++) { for (let j = 0; j <= n; j++) { if (i == 0 || j == 0) { len[currRow][j] = 0; } else if (X[i - 1] == Y[j - 1]) { len[currRow][j] = len[1 - currRow][j - 1] + 1; if (len[currRow][j] > result) { result = len[currRow][j]; end = i - 1; } } else { len[currRow][j] = 0; } } // Make current row as previous row and // previous row as new current row. currRow = 1 - currRow; } // If there is no common substring, print -1. if (result == 0) { return "-1"; } // Longest common substring is from index // end - result + 1 to index end in X. return X.substr(end - result + 1, result); } // Driver Code let X = "GeeksforGeeks"; let Y = "GeeksQuiz"; // function call document.write(LCSubStr(X, Y)); // This code is contributed by avanitrachhadiya2155</script> Geeks Time Complexity: O(m*n) Auxiliary Space: O(n) This approach has been suggested by nik1996. This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princiraj1992 ukasp sanjeev2552 rutvik_56 rag2127 avanitrachhadiya2155 surinderdawra388 rentearobert7901 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Find if a string is interleaved of two other strings | DP-33 Remove first and last character of a string in Java Find the smallest window in a string containing all characters of another string Convert character array to string in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Apr, 2022" }, { "code": null, "e": 243, "s": 54, "text": "Given two strings ‘X’ and ‘Y’, print the length of the longest common substring. If two or more substrings have the same value for the longest common substring, then print any one of them." }, { "code": null, "e": 254, "s": 243, "text": "Examples: " }, { "code": null, "e": 392, "s": 254, "text": "Input : X = \"GeeksforGeeks\", \n Y = \"GeeksQuiz\"\nOutput : Geeks\n\nInput : X = \"zxabcdezy\", \n Y = \"yzabcdezx\"\nOutput : abcdez" }, { "code": null, "e": 539, "s": 392, "text": "We have discussed a solution to find the length of the longest common string. In this post, we have discussed printing common string is discussed." }, { "code": null, "e": 848, "s": 539, "text": "Naive Approach: Let strings X and Y be the lengths m and n respectively. Generate all possible substrings of X which requires a time complexity of O(m2) and search each substring in the string Y which can be achieved in O(n) time complexity using the KMP algorithm. Overall time complexity will be O(n * m2)." }, { "code": null, "e": 1413, "s": 848, "text": "Efficient Approach: It is based on the dynamic programming implementation explained in this post. The longest suffix matrix LCSuff[][] is build up and the index of the cell having the maximum value is tracked. Let that index be represented by (row, col) pair. Now the final longest common substring is built with the help of that index by diagonally traversing up the LCSuff[][] matrix until LCSuff[row][col] != 0 and during the iteration obtaining the characters either from X[row-1] or Y[col-1] and adding them from right to left in the resultant common string. " }, { "code": null, "e": 1417, "s": 1413, "text": "C++" }, { "code": null, "e": 1422, "s": 1417, "text": "Java" }, { "code": null, "e": 1430, "s": 1422, "text": "Python3" }, { "code": null, "e": 1433, "s": 1430, "text": "C#" }, { "code": null, "e": 1444, "s": 1433, "text": "Javascript" }, { "code": "// C++ implementation to print the longest common substring#include <iostream>#include <stdlib.h>#include <string.h> using namespace std; /* function to find and print the longest common substring of X[0..m-1] and Y[0..n-1] */void printLCSubStr(char* X, char* Y, int m, int n){ // Create a table to store lengths of longest common // suffixes of substrings. Note that LCSuff[i][j] // contains length of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and first column entries // have no logical meaning, they are used only for // simplicity of program int LCSuff[m + 1][n + 1]; // To store length of the longest common substring int len = 0; // To store the index of the cell which contains the // maximum value. This cell's index helps in building // up the longest common substring from right to left. int row, col; /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) LCSuff[i][j] = 0; else if (X[i - 1] == Y[j - 1]) { LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1; if (len < LCSuff[i][j]) { len = LCSuff[i][j]; row = i; col = j; } } else LCSuff[i][j] = 0; } } // if true, then no common substring exists if (len == 0) { cout << \"No Common Substring\"; return; } // allocate space for the longest common substring char* resultStr = (char*)malloc((len + 1) * sizeof(char)); // traverse up diagonally form the (row, col) cell // until LCSuff[row][col] != 0 while (LCSuff[row][col] != 0) { resultStr[--len] = X[row - 1]; // or Y[col-1] // move diagonally up to previous cell row--; col--; } // required longest common substring cout << resultStr;} /* Driver program to test above function */int main(){ char X[] = \"OldSite:GeeksforGeeks.org\"; char Y[] = \"NewSite:GeeksQuiz.com\"; int m = strlen(X); int n = strlen(Y); printLCSubStr(X, Y, m, n); return 0;}", "e": 3661, "s": 1444, "text": null }, { "code": "// Java implementation to print the longest common substringpublic class Longest_common_substr { /* function to find and print the longest common substring of X[0..m-1] and Y[0..n-1] */ static void printLCSubStr(String X, String Y, int m, int n) { // Create a table to store lengths of longest common // suffixes of substrings. Note that LCSuff[i][j] // contains length of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and first column entries // have no logical meaning, they are used only for // simplicity of program int[][] LCSuff = new int[m + 1][n + 1]; // To store length of the longest common substring int len = 0; // To store the index of the cell which contains the // maximum value. This cell's index helps in building // up the longest common substring from right to left. int row = 0, col = 0; /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) LCSuff[i][j] = 0; else if (X.charAt(i - 1) == Y.charAt(j - 1)) { LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1; if (len < LCSuff[i][j]) { len = LCSuff[i][j]; row = i; col = j; } } else LCSuff[i][j] = 0; } } // if true, then no common substring exists if (len == 0) { System.out.println(\"No Common Substring\"); return; } // allocate space for the longest common substring String resultStr = \"\"; // traverse up diagonally form the (row, col) cell // until LCSuff[row][col] != 0 while (LCSuff[row][col] != 0) { resultStr = X.charAt(row - 1) + resultStr; // or Y[col-1] --len; // move diagonally up to previous cell row--; col--; } // required longest common substring System.out.println(resultStr); } /* Driver program to test above function */ public static void main(String args[]) { String X = \"OldSite:GeeksforGeeks.org\"; String Y = \"NewSite:GeeksQuiz.com\"; int m = X.length(); int n = Y.length(); printLCSubStr(X, Y, m, n); }}// This code is contributed by Sumit Ghosh", "e": 6208, "s": 3661, "text": null }, { "code": "# Python3 implementation to print# the longest common substring # function to find and print # the longest common substring of# X[0..m-1] and Y[0..n-1]def printLCSSubStr(X: str, Y: str, m: int, n: int): # Create a table to store lengths of # longest common suffixes of substrings. # Note that LCSuff[i][j] contains length # of longest common suffix of X[0..i-1] and # Y[0..j-1]. The first row and first # column entries have no logical meaning, # they are used only for simplicity of program LCSuff = [[0 for i in range(n + 1)] for j in range(m + 1)] # To store length of the # longest common substring length = 0 # To store the index of the cell # which contains the maximum value. # This cell's index helps in building # up the longest common substring # from right to left. row, col = 0, 0 # Following steps build LCSuff[m+1][n+1] # in bottom up fashion. for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: LCSuff[i][j] = 0 else if X[i - 1] == Y[j - 1]: LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1 if length < LCSuff[i][j]: length = LCSuff[i][j] row = i col = j else: LCSuff[i][j] = 0 # if true, then no common substring exists if length == 0: print(\"No Common Substring\") return # allocate space for the longest # common substring resultStr = ['0'] * length # traverse up diagonally form the # (row, col) cell until LCSuff[row][col] != 0 while LCSuff[row][col] != 0: length -= 1 resultStr[length] = X[row - 1] # or Y[col-1] # move diagonally up to previous cell row -= 1 col -= 1 # required longest common substring print(''.join(resultStr)) # Driver Codeif __name__ == \"__main__\": X = \"OldSite:GeeksforGeeks.org\" Y = \"NewSite:GeeksQuiz.com\" m = len(X) n = len(Y) printLCSSubStr(X, Y, m, n) # This code is contributed by# sanjeev2552", "e": 8312, "s": 6208, "text": null }, { "code": "// C# implementation to print the// longest common substringusing System; class GFG { /* function to find and print the longest common substring of X[0..m-1] and Y[0..n-1] */ static void printLCSubStr(String X, String Y, int m, int n) { // Create a table to store lengths of longest common // suffixes of substrings. Note that LCSuff[i][j] // contains length of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and first column entries // have no logical meaning, they are used only for // simplicity of program int[, ] LCSuff = new int[m + 1, n + 1]; // To store length of the longest common substring int len = 0; // To store the index of the cell which contains the // maximum value. This cell's index helps in building // up the longest common substring from right to left. int row = 0, col = 0; /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) LCSuff[i, j] = 0; else if (X[i - 1] == Y[j - 1]) { LCSuff[i, j] = LCSuff[i - 1, j - 1] + 1; if (len < LCSuff[i, j]) { len = LCSuff[i, j]; row = i; col = j; } } else LCSuff[i, j] = 0; } } // if true, then no common substring exists if (len == 0) { Console.Write(\"No Common Substring\"); return; } // allocate space for the longest common substring String resultStr = \"\"; // traverse up diagonally form the (row, col) cell // until LCSuff[row][col] != 0 while (LCSuff[row, col] != 0) { resultStr = X[row - 1] + resultStr; // or Y[col-1] --len; // move diagonally up to previous cell row--; col--; } // required longest common substring Console.WriteLine(resultStr); } /* Driver program to test above function */ public static void Main() { String X = \"OldSite:GeeksforGeeks.org\"; String Y = \"NewSite:GeeksQuiz.com\"; int m = X.Length; int n = Y.Length; printLCSubStr(X, Y, m, n); }} // This code is contributed by Sam007", "e": 10792, "s": 8312, "text": null }, { "code": "<script>// Javascript implementation to print the longest common substring /* function to find and print the longest common substring of X[0..m-1] and Y[0..n-1] */ function printLCSubStr(X,Y,m,n) { // Create a table to store lengths of longest common // suffixes of substrings. Note that LCSuff[i][j] // contains length of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and first column entries // have no logical meaning, they are used only for // simplicity of program let LCSuff = new Array(m+1); // To store length of the longest common substring let len = 0; // To store the index of the cell which contains the // maximum value. This cell's index helps in building // up the longest common substring from right to left. let row = 0, col = 0; /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */ for (let i = 0; i <= m; i++) { LCSuff[i] = Array(n+1); for (let j = 0; j <= n; j++) { LCSuff[i][j]=0; if (i == 0 || j == 0) LCSuff[i][j] = 0; else if (X[i-1] == Y[j-1]) { LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1; if (len < LCSuff[i][j]) { len = LCSuff[i][j]; row = i; col = j; } } else LCSuff[i][j] = 0; } } // if true, then no common substring exists if (len == 0) { document.write(\"No Common Substring\"); return; } // allocate space for the longest common substring let resultStr = \"\"; // traverse up diagonally form the (row, col) cell // until LCSuff[row][col] != 0 while (LCSuff[row][col] != 0) { resultStr = X[row-1] + resultStr; // or Y[col-1] --len; // move diagonally up to previous cell row--; col--; } // required longest common substring document.write(resultStr); } /* Driver program to test above function */ let X = \"OldSite:GeeksforGeeks.org\"; let Y = \"NewSite:GeeksQuiz.com\"; let m = X.length; let n = Y.length; printLCSubStr(X, Y, m, n); //This code is contributed by rag2127 </script>", "e": 13266, "s": 10792, "text": null }, { "code": null, "e": 13277, "s": 13266, "text": "Site:Geeks" }, { "code": null, "e": 13330, "s": 13279, "text": "Time Complexity: O(m*n). Auxiliary Space: O(m*n). " }, { "code": null, "e": 13697, "s": 13330, "text": "Space Optimized Approach: The auxiliary space used by the solution above is O(m*n), where m and n are lengths of string X and Y. The space used by the above solution can be reduced to O(2*n). A variable end is used to store the ending point of the longest common substring in string X and variable maxlen is used to store the length of the longest common substring. " }, { "code": null, "e": 14137, "s": 13697, "text": "Suppose we are at DP state when the length of X is i and length of Y is j, the result of which is stored in len[i][j]. Now if X[i-1] == Y[j-1], then len[i][j] = 1 + len[i-1][j-1], that is result of current row in matrix len[][] depends on values from previous row. Hence, the required length of the longest common substring can be obtained by maintaining values of two consecutive rows only, thereby reducing space requirements to O(2*n). " }, { "code": null, "e": 14839, "s": 14137, "text": "To print the longest common substring, we use a variable end. When len[i][j] is calculated, it is compared with maxlen. If maxlen is less than len[i][j], then end is updated to i-1 to show that longest common substring ends at index i-1 in X and maxlen is updated to len[i][j]. The longest common substring then is from index end – maxlen + 1 to index end in X. A variable currRow is used to represent that either row 0 or row 1 of len[2][n] matrix is currently used to find the length. Initially, row 0 is used as the current row for the case when the length of string X is zero. At the end of each iteration, the current row is made the previous row and the previous row is made the new current row." }, { "code": null, "e": 14897, "s": 14839, "text": "Given below is the implementation of the above approach: " }, { "code": null, "e": 14901, "s": 14897, "text": "C++" }, { "code": null, "e": 14906, "s": 14901, "text": "Java" }, { "code": null, "e": 14914, "s": 14906, "text": "Python3" }, { "code": null, "e": 14917, "s": 14914, "text": "C#" }, { "code": null, "e": 14928, "s": 14917, "text": "Javascript" }, { "code": "// Space optimized CPP implementation to print// longest common substring.#include <bits/stdc++.h>using namespace std; // Function to find longest common substring.string LCSubStr(string X, string Y){ // Find length of both the strings. int m = X.length(); int n = Y.length(); // Variable to store length of longest // common substring. int result = 0; // Variable to store ending point of // longest common substring in X. int end; // Matrix to store result of two // consecutive rows at a time. int len[2][n + 1]; // Variable to represent which row of // matrix is current row. int currRow = 0; // For a particular value of i and j, // len[currRow][j] stores length of longest // common substring in string X[0..i] and Y[0..j]. for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { len[currRow][j] = 0; } else if (X[i - 1] == Y[j - 1]) { len[currRow][j] = len[1 - currRow][j - 1] + 1; if (len[currRow][j] > result) { result = len[currRow][j]; end = i - 1; } } else { len[currRow][j] = 0; } } // Make current row as previous row and // previous row as new current row. currRow = 1 - currRow; } // If there is no common substring, print -1. if (result == 0) { return \"-1\"; } // Longest common substring is from index // end - result + 1 to index end in X. return X.substr(end - result + 1, result);}// Driver Codeint main(){ string X = \"GeeksforGeeks\"; string Y = \"GeeksQuiz\"; // function call cout << LCSubStr(X, Y); return 0;}", "e": 16711, "s": 14928, "text": null }, { "code": "// Space optimized Java implementation to print// longest common substring. public class GFG { // Function to find longest common substring. static String LCSubStr(String X, String Y) { // Find length of both the Strings. int m = X.length(); int n = Y.length(); // Variable to store length of longest // common subString. int result = 0; // Variable to store ending point of // longest common subString in X. int end = 0; // Matrix to store result of two // consecutive rows at a time. int len[][] = new int[2][m]; // Variable to represent which row of // matrix is current row. int currRow = 0; // For a particular value of i and j, // len[currRow][j] stores length of longest // common subString in String X[0..i] and Y[0..j]. for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { len[currRow][j] = 0; } else if (X.charAt(i - 1) == Y.charAt(j - 1)) { len[currRow][j] = len[1 - currRow][j - 1] + 1; if (len[currRow][j] > result) { result = len[currRow][j]; end = i - 1; } } else { len[currRow][j] = 0; } } // Make current row as previous row and // previous row as new current row. currRow = 1 - currRow; } // If there is no common subString, print -1. if (result == 0) { return \"-1\"; } // Longest common subString is from index // end - result + 1 to index end in X. return X.substring(end - result + 1, result); } // Driver Code public static void main(String[] args) { String X = \"GeeksforGeeks\"; String Y = \"GeeksQuiz\"; // function call System.out.println(LCSubStr(X, Y)); } }// This code is contributed by PrinciRaj1992", "e": 18775, "s": 16711, "text": null }, { "code": "# Space optimized Python3 implementation to# print longest common substring. # Function to find longest common substring.def LCSubStr(X, Y): # Find length of both the strings. m = len(X) n = len(Y) # Variable to store length of longest # common substring. result = 0 # Variable to store ending point of # longest common substring in X. end = 0 # Matrix to store result of two # consecutive rows at a time. length = [[0 for j in range(m)] for i in range(2)] # Variable to represent which row of # matrix is current row. currRow = 0 # For a particular value of i and j, # length[currRow][j] stores length # of longest common substring in # string X[0..i] and Y[0..j]. for i in range(0, m + 1): for j in range(0, n + 1): if (i == 0 or j == 0): length[currRow][j] = 0 elif (X[i - 1] == Y[j - 1]): length[currRow][j] = length[1 - currRow][j - 1] + 1 if (length[currRow][j] > result): result = length[currRow][j] end = i - 1 else: length[currRow][j] = 0 # Make current row as previous row and # previous row as new current row. currRow = 1 - currRow # If there is no common substring, print -1. if (result == 0): return \"-1\" # Longest common substring is from index # end - result + 1 to index end in X. return X[end - result + 1 : end + 1] # Driver codeif __name__==\"__main__\": X = \"GeeksforGeeks\" Y = \"GeeksQuiz\" # Function call print(LCSubStr(X, Y)) # This code is contributed by rutvik_56", "e": 20492, "s": 18775, "text": null }, { "code": "using System;// Space optimized Java implementation to print// longest common substring. public class GFG { // Function to find longest common substring. static string LCSubStr(string X, string Y) { // Find length of both the Strings. int m = X.Length; int n = Y.Length; // Variable to store length of longest // common subString. int result = 0; // Variable to store ending point of // longest common subString in X. int end = 0; // Matrix to store result of two // consecutive rows at a time. int[,] len = new int[2,m]; // Variable to represent which row of // matrix is current row. int currRow = 0; // For a particular value of i and j, // len[currRow][j] stores length of longest // common subString in String X[0..i] and Y[0..j]. for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { len[currRow,j] = 0; } else if (X[i - 1] == Y[j - 1]) { len[currRow,j] = len[1 - currRow,j - 1] + 1; if (len[currRow,j] > result) { result = len[currRow,j]; end = i - 1; } } else { len[currRow,j] = 0; } } // Make current row as previous row and // previous row as new current row. currRow = 1 - currRow; } // If there is no common subString, print -1. if (result == 0) { return \"-1\"; } // Longest common subString is from index // end - result + 1 to index end in X. return X.Substring(end - result + 1, result); } // Driver Code public static void Main() { string X = \"GeeksforGeeks\"; string Y = \"GeeksQuiz\"; // function call Console.Write(LCSubStr(X, Y)); } }", "e": 22494, "s": 20492, "text": null }, { "code": "<script>// Space optimized javascript implementation to print// longest common substring. // Function to find longest common substring. function LCSubStr(X,Y) { // Find length of both the strings. let m = X.length; let n = Y.length; // Variable to store length of longest // common substring. let result = 0; // Variable to store ending point of // longest common substring in X. let end; // Matrix to store result of two // consecutive rows at a time. let len= new Array(2); for(let i=0;i<len.length;i++) { len[i]=new Array(n); for(let j=0;j<n;j++) { len[i][j]=0; } } // Variable to represent which row of // matrix is current row. let currRow = 0; // For a particular value of i and j, // len[currRow][j] stores length of longest // common substring in string X[0..i] and Y[0..j]. for (let i = 0; i <= m; i++) { for (let j = 0; j <= n; j++) { if (i == 0 || j == 0) { len[currRow][j] = 0; } else if (X[i - 1] == Y[j - 1]) { len[currRow][j] = len[1 - currRow][j - 1] + 1; if (len[currRow][j] > result) { result = len[currRow][j]; end = i - 1; } } else { len[currRow][j] = 0; } } // Make current row as previous row and // previous row as new current row. currRow = 1 - currRow; } // If there is no common substring, print -1. if (result == 0) { return \"-1\"; } // Longest common substring is from index // end - result + 1 to index end in X. return X.substr(end - result + 1, result); } // Driver Code let X = \"GeeksforGeeks\"; let Y = \"GeeksQuiz\"; // function call document.write(LCSubStr(X, Y)); // This code is contributed by avanitrachhadiya2155</script>", "e": 24471, "s": 22494, "text": null }, { "code": null, "e": 24477, "s": 24471, "text": "Geeks" }, { "code": null, "e": 24525, "s": 24479, "text": "Time Complexity: O(m*n) Auxiliary Space: O(n)" }, { "code": null, "e": 24992, "s": 24525, "text": "This approach has been suggested by nik1996. This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 25006, "s": 24992, "text": "princiraj1992" }, { "code": null, "e": 25012, "s": 25006, "text": "ukasp" }, { "code": null, "e": 25024, "s": 25012, "text": "sanjeev2552" }, { "code": null, "e": 25034, "s": 25024, "text": "rutvik_56" }, { "code": null, "e": 25042, "s": 25034, "text": "rag2127" }, { "code": null, "e": 25063, "s": 25042, "text": "avanitrachhadiya2155" }, { "code": null, "e": 25080, "s": 25063, "text": "surinderdawra388" }, { "code": null, "e": 25097, "s": 25080, "text": "rentearobert7901" }, { "code": null, "e": 25105, "s": 25097, "text": "Strings" }, { "code": null, "e": 25113, "s": 25105, "text": "Strings" }, { "code": null, "e": 25211, "s": 25113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25256, "s": 25211, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 25320, "s": 25256, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 25365, "s": 25320, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 25400, "s": 25365, "text": "Print all subsequences of a string" }, { "code": null, "e": 25465, "s": 25400, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 25494, "s": 25465, "text": "String class in Java | Set 1" }, { "code": null, "e": 25555, "s": 25494, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 25607, "s": 25555, "text": "Remove first and last character of a string in Java" }, { "code": null, "e": 25688, "s": 25607, "text": "Find the smallest window in a string containing all characters of another string" } ]
Number of refills to complete the journey of N km
04 May, 2021 Given a number N which represents the total distance in km to be covered by a car on a single road. There are N petrol pumps at a distance of 1 km each(1, 2, 3, ..N). The capacity of the fuel tank of the car is such that at full tank it goes till a distance of K km. The car has to compulsorily stop at M petrol tanks whose distance from the starting position is given as M integers. The task is to find the number of times, the car has to refill its tank including the compulsory stops to complete its journey of N km. Examples : Input: N = 5, K = 2, M = 1 arr[] = {3} Output: 2 The car starts at 0, with its tank full, travels for 2 km and then refills its tank at 2 km. The car makes the compulsory stop at 3 where its tank if refilled again. It travels for 2 km more to reach its destination of 5 km. Input: N = 10, K = 2, M = 3 arr[] = { 6, 7, 8 } Output: 5 The car starts from 0, stops at 2, 4 for refilling its tank, before making compulsory stops at 6, 7, 8. It travels 2 km from 8 km to make its journey of 10 km complete. Approach: As total journey is of N km, so keep a track of distance covered till now in a variable, say distCovered, which will be initialized by 0. Increment distCovered by K km till distCovered is less than N because K is the amount of distance vehicle can travel since the last refill. Also, with each increment, check if there is a compulsory petrol pump to stop between distCovered and distCovered + K, if yes, then distCovered will be K plus the last compulsory petrol pump to stop at between distCovered and distCovered + K. Also, keep counting the number of refills taken to reach the destination of N km. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program for finding the total// number of stops for refilling to// reach destination of N km#include <iostream>using namespace std; // Function that returns the total number of// refills made to reach the destination of N kmint countRefill(int N, int K, int M, int compulsory[]){ int count = 0; int i = 0; int distCovered = 0; // While we complete the whole journey. while (distCovered < N) { // If must visited petrol pump lie // between distCovered and distCovered+K. if (i < M && compulsory[i] <= (distCovered + K)) { // make last mustVisited as distCovered distCovered = compulsory[i]; // increment the index of compulsory visited. i++; } // if no such must visited pump is // there then increment distCovered by K. else distCovered += K; // Counting the number of refill. if (distCovered < N) count++; } return count;} // Driver Codeint main(){ int N = 10; int K = 2; int M = 3; // compulsory petrol pumps to refill at int compulsory[] = { 6, 7, 8 }; // function call that returns the answer to the problem cout << countRefill(N, K, M, compulsory) << endl; return 0;} // Java program for finding the// total number of stops for// refilling to reach// destination of N kmimport java.io.*; class GFG{ ; // Function that returns the// total number of refills made// to reach the destination of N kmstatic int countRefill(int N, int K, int M, int compulsory[]){ int count = 0; int i = 0; int distCovered = 0; // While we complete // the whole journey. while (distCovered < N) { // If must visited petrol pump lie // between distCovered and distCovered+K. if (i < M && compulsory[i] <= (distCovered + K)) { // make last mustVisited // as distCovered distCovered = compulsory[i]; // increment the index // of compulsory visited. i++; } // if no such must visited // pump is there then // increment distCovered by K. else distCovered += K; // Counting the number of refill. if (distCovered < N) count++; } return count;} // Driver Codepublic static void main (String[] args){ int N = 10; int K = 2; int M = 3; // compulsory petrol // pumps to refill at int compulsory[] = { 6, 7, 8 }; // function call that returns // the answer to the problem System.out.println(countRefill(N, K, M, compulsory));}} // This code is contributed by anuj_67. # Python 3 program for finding the total# number of stops for refilling to reach# destination of N km # Function that returns the total number of# refills made to reach the destination of N kmdef countRefill(N, K, M, compulsory): count = 0 i = 0 distCovered = 0 # While we complete the whole journey. while (distCovered < N): # If must visited petrol pump lie # between distCovered and distCovered+K. if (i < M and compulsory[i] <= (distCovered + K)): # make last mustVisited as distCovered distCovered = compulsory[i] # increment the index of # compulsory visited. i += 1 # if no such must visited pump is # there then increment distCovered by K. else: distCovered += K # Counting the number of refill. if (distCovered < N): count += 1 return count # Driver Codeif __name__ == '__main__': N = 10 K = 2 M = 3 # compulsory petrol pumps to refill at compulsory = [6, 7, 8] # function call that returns the # answer to the problem print(countRefill(N, K, M, compulsory)) # This code is contributed by# Sanjit_Prasad // C# program for finding the// total number of stops for// refilling to reach// destination of N kmusing System; class GFG{ // Function that returns// the total number of// refills made to reach// the destination of N kmstatic int countRefill(int N, int K, int M, int []compulsory){ int count = 0; int i = 0; int distCovered = 0; // While we complete // the whole journey. while (distCovered < N) { // If must visited petrol pump // lie between distCovered and // distCovered+K. if (i < M && compulsory[i] <= (distCovered + K)) { // make last mustVisited // as distCovered distCovered = compulsory[i]; // increment the index // of compulsory visited. i++; } // if no such must visited // pump is there then // increment distCovered by K. else distCovered += K; // Counting the number of refill. if (distCovered < N) count++; } return count;} // Driver Codepublic static void Main (){ int N = 10; int K = 2; int M = 3; // compulsory petrol // pumps to refill at int []compulsory = {6, 7, 8}; // function call that returns // the answer to the problem Console.WriteLine(countRefill(N, K, M, compulsory));}} // This code is contributed by anuj_67. <?php// PHP program for finding the total// number of stops for refilling to// reach destination of N km // Function that returns the total// number of refills made to reach// the destination of N kmfunction countRefill($N, $K, $M, $compulsory){ $count = 0; $i = 0; $distCovered = 0; // While we complete // the whole journey. while ($distCovered < $N) { // If must visited petrol // pump lie between distCovered // and distCovered + K. if ($i < $M and $compulsory[$i] <= ($distCovered + $K)) { // make last mustVisited // as distCovered $distCovered = $compulsory[$i]; // increment the index // of compulsory visited. $i++; } // if no such must visited // pump is there then // increment distCovered by K. else $distCovered += $K; // Counting the number // of refill. if ($distCovered < $N) $count++; } return $count;} // Driver Code$N = 10;$K = 2;$M = 3; // compulsory petrol// pumps to refill at$compulsory = array(6, 7, 8); // function call that returns// the answer to the problemecho countRefill($N, $K, $M, $compulsory) , "\n"; // This code is contributed by anuj_67.?> <script> // Javascript program for finding the total// number of stops for refilling to// reach destination of N km // Function that returns the total number of// refills made to reach the destination of N kmfunction countRefill(N, K, M, compulsory){ var count = 0; var i = 0; var distCovered = 0; // While we complete the whole journey. while (distCovered < N) { // If must visited petrol pump lie // between distCovered and distCovered+K. if (i < M && compulsory[i] <= (distCovered + K)) { // make last mustVisited as distCovered distCovered = compulsory[i]; // increment the index of compulsory visited. i++; } // if no such must visited pump is // there then increment distCovered by K. else distCovered += K; // Counting the number of refill. if (distCovered < N) count++; } return count;} // Driver Codevar N = 10;var K = 2;var M = 3; // compulsory petrol pumps to refill atvar compulsory = [ 6, 7, 8 ]; // function call that returns the answer to the problemdocument.write( countRefill(N, K, M, compulsory)); </script> 5 Time Complexity: O(N) Auxiliary Space: O(1) vt_m Sanjit_Prasad rrrtnx Constructive Algorithms cpp-array Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 May, 2021" }, { "code": null, "e": 585, "s": 52, "text": "Given a number N which represents the total distance in km to be covered by a car on a single road. There are N petrol pumps at a distance of 1 km each(1, 2, 3, ..N). The capacity of the fuel tank of the car is such that at full tank it goes till a distance of K km. The car has to compulsorily stop at M petrol tanks whose distance from the starting position is given as M integers. The task is to find the number of times, the car has to refill its tank including the compulsory stops to complete its journey of N km. Examples : " }, { "code": null, "e": 1087, "s": 585, "text": "Input: N = 5, K = 2, M = 1 arr[] = {3} Output: 2 The car starts at 0, with its tank full, travels for 2 km and then refills its tank at 2 km. The car makes the compulsory stop at 3 where its tank if refilled again. It travels for 2 km more to reach its destination of 5 km. Input: N = 10, K = 2, M = 3 arr[] = { 6, 7, 8 } Output: 5 The car starts from 0, stops at 2, 4 for refilling its tank, before making compulsory stops at 6, 7, 8. It travels 2 km from 8 km to make its journey of 10 km complete. " }, { "code": null, "e": 1755, "s": 1089, "text": "Approach: As total journey is of N km, so keep a track of distance covered till now in a variable, say distCovered, which will be initialized by 0. Increment distCovered by K km till distCovered is less than N because K is the amount of distance vehicle can travel since the last refill. Also, with each increment, check if there is a compulsory petrol pump to stop between distCovered and distCovered + K, if yes, then distCovered will be K plus the last compulsory petrol pump to stop at between distCovered and distCovered + K. Also, keep counting the number of refills taken to reach the destination of N km. Below is the implementation of the above approach: " }, { "code": null, "e": 1759, "s": 1755, "text": "C++" }, { "code": null, "e": 1764, "s": 1759, "text": "Java" }, { "code": null, "e": 1772, "s": 1764, "text": "Python3" }, { "code": null, "e": 1775, "s": 1772, "text": "C#" }, { "code": null, "e": 1779, "s": 1775, "text": "PHP" }, { "code": null, "e": 1790, "s": 1779, "text": "Javascript" }, { "code": "// CPP program for finding the total// number of stops for refilling to// reach destination of N km#include <iostream>using namespace std; // Function that returns the total number of// refills made to reach the destination of N kmint countRefill(int N, int K, int M, int compulsory[]){ int count = 0; int i = 0; int distCovered = 0; // While we complete the whole journey. while (distCovered < N) { // If must visited petrol pump lie // between distCovered and distCovered+K. if (i < M && compulsory[i] <= (distCovered + K)) { // make last mustVisited as distCovered distCovered = compulsory[i]; // increment the index of compulsory visited. i++; } // if no such must visited pump is // there then increment distCovered by K. else distCovered += K; // Counting the number of refill. if (distCovered < N) count++; } return count;} // Driver Codeint main(){ int N = 10; int K = 2; int M = 3; // compulsory petrol pumps to refill at int compulsory[] = { 6, 7, 8 }; // function call that returns the answer to the problem cout << countRefill(N, K, M, compulsory) << endl; return 0;}", "e": 3050, "s": 1790, "text": null }, { "code": "// Java program for finding the// total number of stops for// refilling to reach// destination of N kmimport java.io.*; class GFG{ ; // Function that returns the// total number of refills made// to reach the destination of N kmstatic int countRefill(int N, int K, int M, int compulsory[]){ int count = 0; int i = 0; int distCovered = 0; // While we complete // the whole journey. while (distCovered < N) { // If must visited petrol pump lie // between distCovered and distCovered+K. if (i < M && compulsory[i] <= (distCovered + K)) { // make last mustVisited // as distCovered distCovered = compulsory[i]; // increment the index // of compulsory visited. i++; } // if no such must visited // pump is there then // increment distCovered by K. else distCovered += K; // Counting the number of refill. if (distCovered < N) count++; } return count;} // Driver Codepublic static void main (String[] args){ int N = 10; int K = 2; int M = 3; // compulsory petrol // pumps to refill at int compulsory[] = { 6, 7, 8 }; // function call that returns // the answer to the problem System.out.println(countRefill(N, K, M, compulsory));}} // This code is contributed by anuj_67.", "e": 4524, "s": 3050, "text": null }, { "code": "# Python 3 program for finding the total# number of stops for refilling to reach# destination of N km # Function that returns the total number of# refills made to reach the destination of N kmdef countRefill(N, K, M, compulsory): count = 0 i = 0 distCovered = 0 # While we complete the whole journey. while (distCovered < N): # If must visited petrol pump lie # between distCovered and distCovered+K. if (i < M and compulsory[i] <= (distCovered + K)): # make last mustVisited as distCovered distCovered = compulsory[i] # increment the index of # compulsory visited. i += 1 # if no such must visited pump is # there then increment distCovered by K. else: distCovered += K # Counting the number of refill. if (distCovered < N): count += 1 return count # Driver Codeif __name__ == '__main__': N = 10 K = 2 M = 3 # compulsory petrol pumps to refill at compulsory = [6, 7, 8] # function call that returns the # answer to the problem print(countRefill(N, K, M, compulsory)) # This code is contributed by# Sanjit_Prasad", "e": 5749, "s": 4524, "text": null }, { "code": "// C# program for finding the// total number of stops for// refilling to reach// destination of N kmusing System; class GFG{ // Function that returns// the total number of// refills made to reach// the destination of N kmstatic int countRefill(int N, int K, int M, int []compulsory){ int count = 0; int i = 0; int distCovered = 0; // While we complete // the whole journey. while (distCovered < N) { // If must visited petrol pump // lie between distCovered and // distCovered+K. if (i < M && compulsory[i] <= (distCovered + K)) { // make last mustVisited // as distCovered distCovered = compulsory[i]; // increment the index // of compulsory visited. i++; } // if no such must visited // pump is there then // increment distCovered by K. else distCovered += K; // Counting the number of refill. if (distCovered < N) count++; } return count;} // Driver Codepublic static void Main (){ int N = 10; int K = 2; int M = 3; // compulsory petrol // pumps to refill at int []compulsory = {6, 7, 8}; // function call that returns // the answer to the problem Console.WriteLine(countRefill(N, K, M, compulsory));}} // This code is contributed by anuj_67.", "e": 7199, "s": 5749, "text": null }, { "code": "<?php// PHP program for finding the total// number of stops for refilling to// reach destination of N km // Function that returns the total// number of refills made to reach// the destination of N kmfunction countRefill($N, $K, $M, $compulsory){ $count = 0; $i = 0; $distCovered = 0; // While we complete // the whole journey. while ($distCovered < $N) { // If must visited petrol // pump lie between distCovered // and distCovered + K. if ($i < $M and $compulsory[$i] <= ($distCovered + $K)) { // make last mustVisited // as distCovered $distCovered = $compulsory[$i]; // increment the index // of compulsory visited. $i++; } // if no such must visited // pump is there then // increment distCovered by K. else $distCovered += $K; // Counting the number // of refill. if ($distCovered < $N) $count++; } return $count;} // Driver Code$N = 10;$K = 2;$M = 3; // compulsory petrol// pumps to refill at$compulsory = array(6, 7, 8); // function call that returns// the answer to the problemecho countRefill($N, $K, $M, $compulsory) , \"\\n\"; // This code is contributed by anuj_67.?>", "e": 8545, "s": 7199, "text": null }, { "code": "<script> // Javascript program for finding the total// number of stops for refilling to// reach destination of N km // Function that returns the total number of// refills made to reach the destination of N kmfunction countRefill(N, K, M, compulsory){ var count = 0; var i = 0; var distCovered = 0; // While we complete the whole journey. while (distCovered < N) { // If must visited petrol pump lie // between distCovered and distCovered+K. if (i < M && compulsory[i] <= (distCovered + K)) { // make last mustVisited as distCovered distCovered = compulsory[i]; // increment the index of compulsory visited. i++; } // if no such must visited pump is // there then increment distCovered by K. else distCovered += K; // Counting the number of refill. if (distCovered < N) count++; } return count;} // Driver Codevar N = 10;var K = 2;var M = 3; // compulsory petrol pumps to refill atvar compulsory = [ 6, 7, 8 ]; // function call that returns the answer to the problemdocument.write( countRefill(N, K, M, compulsory)); </script>", "e": 9733, "s": 8545, "text": null }, { "code": null, "e": 9735, "s": 9733, "text": "5" }, { "code": null, "e": 9782, "s": 9737, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 9787, "s": 9782, "text": "vt_m" }, { "code": null, "e": 9801, "s": 9787, "text": "Sanjit_Prasad" }, { "code": null, "e": 9808, "s": 9801, "text": "rrrtnx" }, { "code": null, "e": 9832, "s": 9808, "text": "Constructive Algorithms" }, { "code": null, "e": 9842, "s": 9832, "text": "cpp-array" }, { "code": null, "e": 9849, "s": 9842, "text": "Arrays" }, { "code": null, "e": 9856, "s": 9849, "text": "Arrays" } ]
Draw Multiple Time Series in Same Plot in R
26 May, 2022 Time Series in R programming language is used to see how an object behaves over a period of time. In R, it can be easily done by the ts() function with some parameters. Time series takes the data vector and each data is connected with timestamp value as given by the user. First, we create a data vector that has data for all the time series that have to be drawn. Then we plot the time series using the first dataset and plot() function. Then add other time series using line() function to the existing plot. Then we may add a legend on top to show which line in the plot represents which time series. Example: R # Create sample dataset.seed(1023) sample_data <- round(data.frame(year = 1997:2021, time_data1 = 1:25 + rnorm(25), time_data2 = 30:6 + runif(25, 0, 10), time_data3 = rnorm(25, 5, 5))) # Plot a graph with time_data1plot(sample_data$year, sample_data$time_data1, type = "l", col = 2, ylim = c(- 15, 40), xlab = "Year", ylab = "Values") # Add line graphs of other two datasetlines(sample_data$year, sample_data$time_data2, type = "l", col = 3) lines(sample_data$year, sample_data$time_data3, type = "l", col = 4) # Add legend in top right cornerlegend("topright", c("Geeksforgeeks", "technical-scripter", "geek-i-knack"), lty = 1, col = 2:4) Output: Multiple time series in one plot In ggplot2 we can directly use geom_line() to draw the plot. We first create a sample data vector. The ggplot2 will be used to draw the plot and reshape will melt the data from the wide form to long-form. Convert data from the wide form to long-form. Syntax: melt(sample_data, id.vars = variable) Draw the plot with the help of ggplot2 and geom_line(), Example: R # Create sample dataset.seed(1023) sample_data <- round(data.frame(year = 1997:2021, time_data1 = 1:25 + rnorm(25), time_data2 = 30:6 + runif(25, 0, 10), time_data3 = rnorm(25, 5, 5))) # Load packages reshape2 and ggplot2library("reshape2") library("ggplot2") # Convert sample_data from wide form to long formdata_final <- melt(sample_data, id.vars = "year") # Plot the final dataggplot(data_final, aes(x = year, y = value, col = variable)) + geom_line() Output: Multiple time series using ggplot2 varshagumber28 Picked R-Charts R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 May, 2022" }, { "code": null, "e": 328, "s": 54, "text": "Time Series in R programming language is used to see how an object behaves over a period of time. In R, it can be easily done by the ts() function with some parameters. Time series takes the data vector and each data is connected with timestamp value as given by the user. " }, { "code": null, "e": 658, "s": 328, "text": "First, we create a data vector that has data for all the time series that have to be drawn. Then we plot the time series using the first dataset and plot() function. Then add other time series using line() function to the existing plot. Then we may add a legend on top to show which line in the plot represents which time series." }, { "code": null, "e": 667, "s": 658, "text": "Example:" }, { "code": null, "e": 669, "s": 667, "text": "R" }, { "code": "# Create sample dataset.seed(1023) sample_data <- round(data.frame(year = 1997:2021, time_data1 = 1:25 + rnorm(25), time_data2 = 30:6 + runif(25, 0, 10), time_data3 = rnorm(25, 5, 5))) # Plot a graph with time_data1plot(sample_data$year, sample_data$time_data1, type = \"l\", col = 2, ylim = c(- 15, 40), xlab = \"Year\", ylab = \"Values\") # Add line graphs of other two datasetlines(sample_data$year, sample_data$time_data2, type = \"l\", col = 3) lines(sample_data$year, sample_data$time_data3, type = \"l\", col = 4) # Add legend in top right cornerlegend(\"topright\", c(\"Geeksforgeeks\", \"technical-scripter\", \"geek-i-knack\"), lty = 1, col = 2:4)", "e": 1577, "s": 669, "text": null }, { "code": null, "e": 1585, "s": 1577, "text": "Output:" }, { "code": null, "e": 1618, "s": 1585, "text": "Multiple time series in one plot" }, { "code": null, "e": 1680, "s": 1618, "text": "In ggplot2 we can directly use geom_line() to draw the plot. " }, { "code": null, "e": 1870, "s": 1680, "text": "We first create a sample data vector. The ggplot2 will be used to draw the plot and reshape will melt the data from the wide form to long-form. Convert data from the wide form to long-form." }, { "code": null, "e": 1878, "s": 1870, "text": "Syntax:" }, { "code": null, "e": 1916, "s": 1878, "text": "melt(sample_data, id.vars = variable)" }, { "code": null, "e": 1972, "s": 1916, "text": "Draw the plot with the help of ggplot2 and geom_line()," }, { "code": null, "e": 1981, "s": 1972, "text": "Example:" }, { "code": null, "e": 1983, "s": 1981, "text": "R" }, { "code": "# Create sample dataset.seed(1023) sample_data <- round(data.frame(year = 1997:2021, time_data1 = 1:25 + rnorm(25), time_data2 = 30:6 + runif(25, 0, 10), time_data3 = rnorm(25, 5, 5))) # Load packages reshape2 and ggplot2library(\"reshape2\") library(\"ggplot2\") # Convert sample_data from wide form to long formdata_final <- melt(sample_data, id.vars = \"year\") # Plot the final dataggplot(data_final, aes(x = year, y = value, col = variable)) + geom_line()", "e": 2581, "s": 1983, "text": null }, { "code": null, "e": 2589, "s": 2581, "text": "Output:" }, { "code": null, "e": 2624, "s": 2589, "text": "Multiple time series using ggplot2" }, { "code": null, "e": 2639, "s": 2624, "text": "varshagumber28" }, { "code": null, "e": 2646, "s": 2639, "text": "Picked" }, { "code": null, "e": 2655, "s": 2646, "text": "R-Charts" }, { "code": null, "e": 2664, "s": 2655, "text": "R-Graphs" }, { "code": null, "e": 2672, "s": 2664, "text": "R-plots" }, { "code": null, "e": 2683, "s": 2672, "text": "R Language" } ]
numpy.arctan() in Python
29 Nov, 2018 numpy.arctan(x[, out]) = ufunc ‘arctan’) : This mathematical function helps user to calculate inverse tangent for all x(being the array elements). Parameters : array : [array_like]elements are in radians. out : [array_like]array of same shape as x. Note : 2pi Radians = 360 degreesThe convention is to return the angle z whose real part lies in [-pi/2, pi/2]. Return : An array with inverse tangent of x for all x i.e. array elements. The values are in the closed interval [-pi/2, pi/2]. Code #1 : Working # Python program explaining# arctan() function import numpy as np in_array = [0, 1, 0.3, -1]print ("Input array : \n", in_array) arctan_Values = np.arctan(in_array)print ("\nInverse Tangent values : \n", arctan_Values) Output : Input array : [0, 1, 0.3, -1] Inverse Tangent values : [ 0. 0.78539816 0.29145679 -0.78539816] Code #2 : Graphical representation # Python program showing# Graphical representation # of arctan() function import numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array1 = np.tan(in_array)out_array2 = np.arctan(in_array) print("in_array : ", in_array)print("\nout_array with tan : ", out_array1)print("\nout_arraywith arctan : ", out_array1) # red for numpy.arccos()plt.plot(in_array, out_array1, color = 'blue', marker = "*") plt.plot(in_array, out_array2, color = 'red', marker = "o") plt.title("blue : numpy.tan() \nred : numpy.arctan()")plt.xlabel("X")plt.ylabel("Y")plt.show() Output : in_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933 0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265] out_array with tan : [ 1.22464680e-16 6.42660977e-01 2.18969456e+00 -6.95515277e+00 -1.15406152e+00 -2.93626493e-01 2.93626493e-01 1.15406152e+00 6.95515277e+00 -2.18969456e+00 -6.42660977e-01 -1.22464680e-16] out_arraywith arctan : [ 1.22464680e-16 6.42660977e-01 2.18969456e+00 -6.95515277e+00 -1.15406152e+00 -2.93626493e-01 2.93626493e-01 1.15406152e+00 6.95515277e+00 -2.18969456e+00 -6.42660977e-01 -1.22464680e-16] References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.arcsin.html#numpy.arccos. Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 175, "s": 28, "text": "numpy.arctan(x[, out]) = ufunc ‘arctan’) : This mathematical function helps user to calculate inverse tangent for all x(being the array elements)." }, { "code": null, "e": 188, "s": 175, "text": "Parameters :" }, { "code": null, "e": 280, "s": 188, "text": "array : [array_like]elements are in radians.\nout : [array_like]array of same shape as x.\n" }, { "code": null, "e": 287, "s": 280, "text": "Note :" }, { "code": null, "e": 391, "s": 287, "text": "2pi Radians = 360 degreesThe convention is to return the angle z whose real part lies in [-pi/2, pi/2]." }, { "code": null, "e": 400, "s": 391, "text": "Return :" }, { "code": null, "e": 522, "s": 400, "text": "An array with inverse tangent of x\nfor all x i.e. array elements. \n\nThe values are in the closed interval [-pi/2, pi/2].\n" }, { "code": null, "e": 541, "s": 522, "text": " Code #1 : Working" }, { "code": "# Python program explaining# arctan() function import numpy as np in_array = [0, 1, 0.3, -1]print (\"Input array : \\n\", in_array) arctan_Values = np.arctan(in_array)print (\"\\nInverse Tangent values : \\n\", arctan_Values)", "e": 790, "s": 541, "text": null }, { "code": null, "e": 799, "s": 790, "text": "Output :" }, { "code": null, "e": 909, "s": 799, "text": "Input array : \n [0, 1, 0.3, -1]\n\nInverse Tangent values : \n [ 0. 0.78539816 0.29145679 -0.78539816]" }, { "code": null, "e": 945, "s": 909, "text": " Code #2 : Graphical representation" }, { "code": "# Python program showing# Graphical representation # of arctan() function import numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array1 = np.tan(in_array)out_array2 = np.arctan(in_array) print(\"in_array : \", in_array)print(\"\\nout_array with tan : \", out_array1)print(\"\\nout_arraywith arctan : \", out_array1) # red for numpy.arccos()plt.plot(in_array, out_array1, color = 'blue', marker = \"*\") plt.plot(in_array, out_array2, color = 'red', marker = \"o\") plt.title(\"blue : numpy.tan() \\nred : numpy.arctan()\")plt.xlabel(\"X\")plt.ylabel(\"Y\")plt.show()", "e": 1586, "s": 945, "text": null }, { "code": null, "e": 1595, "s": 1586, "text": "Output :" }, { "code": null, "e": 2218, "s": 1595, "text": "in_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933\n 0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265]\n\nout_array with tan : [ 1.22464680e-16 6.42660977e-01 2.18969456e+00 -6.95515277e+00\n -1.15406152e+00 -2.93626493e-01 2.93626493e-01 1.15406152e+00\n 6.95515277e+00 -2.18969456e+00 -6.42660977e-01 -1.22464680e-16]\n\nout_arraywith arctan : [ 1.22464680e-16 6.42660977e-01 2.18969456e+00 -6.95515277e+00\n -1.15406152e+00 -2.93626493e-01 2.93626493e-01 1.15406152e+00\n 6.95515277e+00 -2.18969456e+00 -6.42660977e-01 -1.22464680e-16]" }, { "code": null, "e": 2319, "s": 2218, "text": "References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.arcsin.html#numpy.arccos." }, { "code": null, "e": 2354, "s": 2319, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 2367, "s": 2354, "text": "Python-numpy" }, { "code": null, "e": 2374, "s": 2367, "text": "Python" } ]
Python Tweepy – Getting the text of a tweet
18 Jun, 2020 In this article we will see how we can get the text of a status/tweet. A tweet can only have a maximum of 280 characters. The text attribute of the Status object provides us with the text of the status. Identifying the text of the status in the GUI : In the above mentioned status, the text of the status is : A programmer’s takeaway from the pandemic: Local variables over Global variables. What do you think? . . . . . #programming #coding #programmingmemes #Covid_19 #codinglife #Python #javascript #pandemic #thursdayvibes In order to get the text of the status, we have to do the following : Identify the status ID of the status from the GUI.Get the Status object of the status using the get_status() method with the status ID. If we want to get the complete text, pass another parameter tweet_mode = "extended".From this object, fetch the text attribute present in it. If we want to get the complete text, fetch the attribute full_text. Identify the status ID of the status from the GUI. Get the Status object of the status using the get_status() method with the status ID. If we want to get the complete text, pass another parameter tweet_mode = "extended". From this object, fetch the text attribute present in it. If we want to get the complete text, fetch the attribute full_text. Example 1 : Consider the following status : We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272771459249844224. # 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 statusid = 1272771459249844224 # fetching the statusstatus = api.get_status(id) # fetching the text attributetext = status.text print("The text of the status is : \n\n" + text) Output : The text of the status is : Which movie did you watch recently? Reply us! . . . . . #tuesdaymood #TuesdayThoughts #Bollywood #Hollywood #genre #movies #movie #fun Example 2 : Consider the following status : We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272479136133627905. This time we will be fetching the complete text of the status. While using the get_status() method also pass tweet_mode = "extended" as a parameter. Then fetch the complete text using the full_text attribute. # the ID of the statusid = 1272479136133627905 # fetching the status with extended tweet_modestatus = api.get_status(id, tweet_mode = "extended") # fetching the full_text attributefull_text = status.full_text print("The text of the status is : \n\n" + full_text) Output : The text of the status is : "I am thankful to programming for _______________." Reply us most quirky/unexpected answers! . . . . . . . #coding #programming #codinglife #code #javascript #NodeJS #reactjs #100DaysOfCode #codingisfun Python-Tweepy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jun, 2020" }, { "code": null, "e": 231, "s": 28, "text": "In this article we will see how we can get the text of a status/tweet. A tweet can only have a maximum of 280 characters. The text attribute of the Status object provides us with the text of the status." }, { "code": null, "e": 279, "s": 231, "text": "Identifying the text of the status in the GUI :" }, { "code": null, "e": 338, "s": 279, "text": "In the above mentioned status, the text of the status is :" }, { "code": null, "e": 560, "s": 338, "text": "A programmer’s takeaway from the pandemic: Local variables over Global variables.\n\n What do you think?\n.\n.\n.\n.\n.\n#programming #coding #programmingmemes #Covid_19 #codinglife #Python #javascript \n#pandemic #thursdayvibes\n" }, { "code": null, "e": 630, "s": 560, "text": "In order to get the text of the status, we have to do the following :" }, { "code": null, "e": 976, "s": 630, "text": "Identify the status ID of the status from the GUI.Get the Status object of the status using the get_status() method with the status ID. If we want to get the complete text, pass another parameter tweet_mode = \"extended\".From this object, fetch the text attribute present in it. If we want to get the complete text, fetch the attribute full_text." }, { "code": null, "e": 1027, "s": 976, "text": "Identify the status ID of the status from the GUI." }, { "code": null, "e": 1198, "s": 1027, "text": "Get the Status object of the status using the get_status() method with the status ID. If we want to get the complete text, pass another parameter tweet_mode = \"extended\"." }, { "code": null, "e": 1324, "s": 1198, "text": "From this object, fetch the text attribute present in it. If we want to get the complete text, fetch the attribute full_text." }, { "code": null, "e": 1368, "s": 1324, "text": "Example 1 : Consider the following status :" }, { "code": null, "e": 1483, "s": 1368, "text": "We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272771459249844224." }, { "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 statusid = 1272771459249844224 # fetching the statusstatus = api.get_status(id) # fetching the text attributetext = status.text print(\"The text of the status is : \\n\\n\" + text)", "e": 2087, "s": 1483, "text": null }, { "code": null, "e": 2096, "s": 2087, "text": "Output :" }, { "code": null, "e": 2264, "s": 2096, "text": "The text of the status is : \n\nWhich movie did you watch recently?\n\nReply us!\n.\n.\n.\n.\n.\n#tuesdaymood #TuesdayThoughts #Bollywood #Hollywood #genre \n#movies #movie #fun\n" }, { "code": null, "e": 2308, "s": 2264, "text": "Example 2 : Consider the following status :" }, { "code": null, "e": 2632, "s": 2308, "text": "We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272479136133627905. This time we will be fetching the complete text of the status. While using the get_status() method also pass tweet_mode = \"extended\" as a parameter. Then fetch the complete text using the full_text attribute." }, { "code": "# the ID of the statusid = 1272479136133627905 # fetching the status with extended tweet_modestatus = api.get_status(id, tweet_mode = \"extended\") # fetching the full_text attributefull_text = status.full_text print(\"The text of the status is : \\n\\n\" + full_text)", "e": 2899, "s": 2632, "text": null }, { "code": null, "e": 2908, "s": 2899, "text": "Output :" }, { "code": null, "e": 3144, "s": 2908, "text": "The text of the status is : \n\n\"I am thankful to programming for _______________.\"\n\nReply us most quirky/unexpected answers!\n.\n.\n.\n.\n.\n.\n.\n#coding #programming #codinglife #code #javascript #NodeJS #reactjs #100DaysOfCode #codingisfun\n" }, { "code": null, "e": 3158, "s": 3144, "text": "Python-Tweepy" }, { "code": null, "e": 3165, "s": 3158, "text": "Python" }, { "code": null, "e": 3263, "s": 3165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3281, "s": 3263, "text": "Python Dictionary" }, { "code": null, "e": 3323, "s": 3281, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3345, "s": 3323, "text": "Enumerate() in Python" }, { "code": null, "e": 3380, "s": 3345, "text": "Read a file line by line in Python" }, { "code": null, "e": 3406, "s": 3380, "text": "Python String | replace()" }, { "code": null, "e": 3438, "s": 3406, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3467, "s": 3438, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3494, "s": 3467, "text": "Python Classes and Objects" }, { "code": null, "e": 3524, "s": 3494, "text": "Iterate over a list in Python" } ]
unordered_multimap equal_range() function in C++ STL
08 Aug, 2018 unordered_multimap::equal_range() is a built-in function in C++ STL which returns the range in which all the element’s key is equal to a key. It returns a pair of iterators where the first is an iterator pointing to the lower bound of the range and second is an iterator pointing to the upper bound of the range. If there is no element equal to a given value in the container, then it returns a pair where both lower and upper bound points to the position past the end of the container or unordered_multimap.end(). Syntax: unordered_multimap_name.equal_range(k) Parameters: The function accepts a mandatory parameter k. The range returned will have the elements with key k. Return Value: It returns a pair of iterators. Below programs illustrates the above function: Program 1: // C++ program to illustrate the// unordered_multimap::equal_range()#include <iostream>#include <unordered_map>using namespace std; int main(){ // declaration unordered_multimap<int, int> sample; // inserts key and element sample.insert({ 1, 2 }); sample.insert({ 1, 2 }); sample.insert({ 2, 3 }); sample.insert({ 3, 4 }); sample.insert({ 2, 6 }); // iterator of pairs pointing to range // which includes 1 and print by iterating in range auto itr = sample.equal_range(1); cout << "Elements with Key 1: "; for (auto it = itr.first; it != itr.second; it++) { cout << it->second << " "; } cout << endl; // iterator of pairs pointing to range // which includes 2 and print by iterating in range itr = sample.equal_range(2); cout << "Elements with Key 2: "; for (auto it = itr.first; it != itr.second; it++) { cout << it->second << " "; } return 0;} Elements with Key 1: 2 2 Elements with Key 2: 6 3 Program 2: // C++ program to illustrate the// unordered_multimap::equal_range()#include <iostream>#include <unordered_map>using namespace std; int main(){ // declaration unordered_multimap<char, char> sample; // inserts key and element sample.insert({ 'a', 'b' }); sample.insert({ 'a', 'b' }); sample.insert({ 'a', 'd' }); sample.insert({ 'b', 'e' }); sample.insert({ 'b', 'd' }); // iterator of pairs pointing to range // which includes b and print by iterating in range auto itr = sample.equal_range('b'); cout << "Elements with Key b: "; for (auto it = itr.first; it != itr.second; it++) { cout << it->second << " "; } cout << endl; // iterator of pairs pointing to range // which includes a and print by iterating in range itr = sample.equal_range('a'); cout << "Elements with Key a: "; for (auto it = itr.first; it != itr.second; it++) { cout << it->second << " "; } return 0;} Elements with Key b: d e Elements with Key a: d b b CPP-Functions cpp-unordered_multimap STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Aug, 2018" }, { "code": null, "e": 543, "s": 28, "text": "unordered_multimap::equal_range() is a built-in function in C++ STL which returns the range in which all the element’s key is equal to a key. It returns a pair of iterators where the first is an iterator pointing to the lower bound of the range and second is an iterator pointing to the upper bound of the range. If there is no element equal to a given value in the container, then it returns a pair where both lower and upper bound points to the position past the end of the container or unordered_multimap.end()." }, { "code": null, "e": 551, "s": 543, "text": "Syntax:" }, { "code": null, "e": 590, "s": 551, "text": "unordered_multimap_name.equal_range(k)" }, { "code": null, "e": 702, "s": 590, "text": "Parameters: The function accepts a mandatory parameter k. The range returned will have the elements with key k." }, { "code": null, "e": 748, "s": 702, "text": "Return Value: It returns a pair of iterators." }, { "code": null, "e": 795, "s": 748, "text": "Below programs illustrates the above function:" }, { "code": null, "e": 806, "s": 795, "text": "Program 1:" }, { "code": "// C++ program to illustrate the// unordered_multimap::equal_range()#include <iostream>#include <unordered_map>using namespace std; int main(){ // declaration unordered_multimap<int, int> sample; // inserts key and element sample.insert({ 1, 2 }); sample.insert({ 1, 2 }); sample.insert({ 2, 3 }); sample.insert({ 3, 4 }); sample.insert({ 2, 6 }); // iterator of pairs pointing to range // which includes 1 and print by iterating in range auto itr = sample.equal_range(1); cout << \"Elements with Key 1: \"; for (auto it = itr.first; it != itr.second; it++) { cout << it->second << \" \"; } cout << endl; // iterator of pairs pointing to range // which includes 2 and print by iterating in range itr = sample.equal_range(2); cout << \"Elements with Key 2: \"; for (auto it = itr.first; it != itr.second; it++) { cout << it->second << \" \"; } return 0;}", "e": 1745, "s": 806, "text": null }, { "code": null, "e": 1797, "s": 1745, "text": "Elements with Key 1: 2 2 \nElements with Key 2: 6 3\n" }, { "code": null, "e": 1808, "s": 1797, "text": "Program 2:" }, { "code": "// C++ program to illustrate the// unordered_multimap::equal_range()#include <iostream>#include <unordered_map>using namespace std; int main(){ // declaration unordered_multimap<char, char> sample; // inserts key and element sample.insert({ 'a', 'b' }); sample.insert({ 'a', 'b' }); sample.insert({ 'a', 'd' }); sample.insert({ 'b', 'e' }); sample.insert({ 'b', 'd' }); // iterator of pairs pointing to range // which includes b and print by iterating in range auto itr = sample.equal_range('b'); cout << \"Elements with Key b: \"; for (auto it = itr.first; it != itr.second; it++) { cout << it->second << \" \"; } cout << endl; // iterator of pairs pointing to range // which includes a and print by iterating in range itr = sample.equal_range('a'); cout << \"Elements with Key a: \"; for (auto it = itr.first; it != itr.second; it++) { cout << it->second << \" \"; } return 0;}", "e": 2773, "s": 1808, "text": null }, { "code": null, "e": 2827, "s": 2773, "text": "Elements with Key b: d e \nElements with Key a: d b b\n" }, { "code": null, "e": 2841, "s": 2827, "text": "CPP-Functions" }, { "code": null, "e": 2864, "s": 2841, "text": "cpp-unordered_multimap" }, { "code": null, "e": 2868, "s": 2864, "text": "STL" }, { "code": null, "e": 2872, "s": 2868, "text": "C++" }, { "code": null, "e": 2876, "s": 2872, "text": "STL" }, { "code": null, "e": 2880, "s": 2876, "text": "CPP" } ]
lvalues references and rvalues references in C++ with Examples - GeeksforGeeks
02 Sep, 2021 Prerequisites: lvalue and rvalue in C++, References in C++“l-value” refers to a memory location that identifies an object. “r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the ‘&’ before the name of the variable. Example: int a = 10; // Declaring lvalue reference int& lref = a; // Declaring rvalue reference int&& rref = 20; Below is the implementation for lvalue and rvalue: C++ // C++ program to illustrate the// lvalue and rvalue #include <iostream>using namespace std; // Driver Codeint main(){ // Declaring the variable int a{ 10 }; // Declaring reference to // already created variable int& b = a; // Provision made to display // the boolean output in the // form of True and False // instead of 1 and cout << boolalpha; // Comparing the address of both the // variable and its reference and it // will turn out to be same cout << (&a == &b) << endl; return 0;} true Explanation: The following code will print True as both the variable are pointing to the same memory location. b is just an alternative name to the memory assigned to the variable a. The reference declared in the above code is lvalue reference (i.e., referring to variable in the lvalue) similarly the references for the values can also be declared. rvalue references have two properties that are useful: rvalue references extend the lifespan of the temporary object to which they are assigned.Non-const rvalue references allow you to modify the rvalue. rvalue references extend the lifespan of the temporary object to which they are assigned. Non-const rvalue references allow you to modify the rvalue. Important: lvalue references can be assigned with the rvalues but rvalue references cannot be assigned to the lvalue. C++ // C++ program to illustrate the// lvalue and rvalue#include <iostream>using namespace std; // Driver Codeint main(){ int a = 10; // Declaring lvalue reference // (i.e variable a) int& lref = a; // Declaring rvalue reference int&& rref = 20; // Print the values cout << "lref = " << lref << endl; cout << "rref = " << rref << endl; // Value of both a // and lref is changed lref = 30; // Value of rref is changed rref = 40; cout << "lref = " << lref << endl; cout << "rref = " << rref << endl; // This line will generate an error // as l-value cannot be assigned // to the r-value references // int &&ref = a; return 0;} lref = 10 rref = 20 lref = 30 rref = 40 Uses of the lvalue references: lvalue references can be used to alias an existing object.They can also be used to implement pass-by-reference semantics. lvalue references can be used to alias an existing object. They can also be used to implement pass-by-reference semantics. C++ // C++ program to illustrate lvalue#include <iostream>using namespace std; // Creating the references of the// parameter passed to the functionvoid swap(int& x, int& y){ int temp = x; x = y; y = temp;} // Driver Codeint main(){ // Given values int a{ 10 }, b{ 20 }; cout << "a = " << a << " b = " << b << endl; // Call by Reference swap(a, b); // Print the value cout << "a = " << a << " b = " << b << endl; return 0;} a = 10 b = 20 a = 20 b = 10 Note: When the function return lvalue reference the expression becomes lvalue expression. Uses of rvalue references: They are used in working with the move constructor and move assignment.cannot bind non-const lvalue reference of type ‘int&‘ to an rvalue of type ‘int’.cannot bind rvalue references of type ‘int&&‘ to lvalue of type ‘int’. They are used in working with the move constructor and move assignment. cannot bind non-const lvalue reference of type ‘int&‘ to an rvalue of type ‘int’. cannot bind rvalue references of type ‘int&&‘ to lvalue of type ‘int’. Program 1: C++ // C++ program to illustrate rvalue#include <iostream>using namespace std; // lvalue reference to the lvalue// passed as the parametervoid printReferenceValue(int& x){ cout << x << endl;} // Driver Codeint main(){ // Given value int a{ 10 }; // Function call is made lvalue & can // be assigned to lvalue reference printReferenceValue(a); return 0;} 10 Program 2: C++ // C++ program to illustrate rvalue#include <iostream>using namespace std; // Declaring rvalue reference to the// rvalue passed as the parametervoid printReferenceValue(int&& x){ cout << x << endl;} // Driver Codeint main(){ // Given value a int a{ 10 }; // Works fine as the function is // called with rvalue printReferenceValue(100); return 0;} 100 adnanirshad158 surindertarika1234 simranarora5sos gulshankumarar231 C++-References cpp-references C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Inline Functions in C++ Pair in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Destructors in C++
[ { "code": null, "e": 25918, "s": 25890, "text": "\n02 Sep, 2021" }, { "code": null, "e": 26267, "s": 25918, "text": "Prerequisites: lvalue and rvalue in C++, References in C++“l-value” refers to a memory location that identifies an object. “r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the ‘&’ before the name of the variable." }, { "code": null, "e": 26277, "s": 26267, "text": "Example: " }, { "code": null, "e": 26383, "s": 26277, "text": "int a = 10;\n\n// Declaring lvalue reference\nint& lref = a;\n\n// Declaring rvalue reference\nint&& rref = 20;" }, { "code": null, "e": 26434, "s": 26383, "text": "Below is the implementation for lvalue and rvalue:" }, { "code": null, "e": 26438, "s": 26434, "text": "C++" }, { "code": "// C++ program to illustrate the// lvalue and rvalue #include <iostream>using namespace std; // Driver Codeint main(){ // Declaring the variable int a{ 10 }; // Declaring reference to // already created variable int& b = a; // Provision made to display // the boolean output in the // form of True and False // instead of 1 and cout << boolalpha; // Comparing the address of both the // variable and its reference and it // will turn out to be same cout << (&a == &b) << endl; return 0;}", "e": 26974, "s": 26438, "text": null }, { "code": null, "e": 26979, "s": 26974, "text": "true" }, { "code": null, "e": 27331, "s": 26981, "text": "Explanation: The following code will print True as both the variable are pointing to the same memory location. b is just an alternative name to the memory assigned to the variable a. The reference declared in the above code is lvalue reference (i.e., referring to variable in the lvalue) similarly the references for the values can also be declared." }, { "code": null, "e": 27387, "s": 27331, "text": "rvalue references have two properties that are useful: " }, { "code": null, "e": 27536, "s": 27387, "text": "rvalue references extend the lifespan of the temporary object to which they are assigned.Non-const rvalue references allow you to modify the rvalue." }, { "code": null, "e": 27626, "s": 27536, "text": "rvalue references extend the lifespan of the temporary object to which they are assigned." }, { "code": null, "e": 27686, "s": 27626, "text": "Non-const rvalue references allow you to modify the rvalue." }, { "code": null, "e": 27805, "s": 27686, "text": "Important: lvalue references can be assigned with the rvalues but rvalue references cannot be assigned to the lvalue. " }, { "code": null, "e": 27809, "s": 27805, "text": "C++" }, { "code": "// C++ program to illustrate the// lvalue and rvalue#include <iostream>using namespace std; // Driver Codeint main(){ int a = 10; // Declaring lvalue reference // (i.e variable a) int& lref = a; // Declaring rvalue reference int&& rref = 20; // Print the values cout << \"lref = \" << lref << endl; cout << \"rref = \" << rref << endl; // Value of both a // and lref is changed lref = 30; // Value of rref is changed rref = 40; cout << \"lref = \" << lref << endl; cout << \"rref = \" << rref << endl; // This line will generate an error // as l-value cannot be assigned // to the r-value references // int &&ref = a; return 0;}", "e": 28499, "s": 27809, "text": null }, { "code": null, "e": 28539, "s": 28499, "text": "lref = 10\nrref = 20\nlref = 30\nrref = 40" }, { "code": null, "e": 28573, "s": 28541, "text": "Uses of the lvalue references: " }, { "code": null, "e": 28695, "s": 28573, "text": "lvalue references can be used to alias an existing object.They can also be used to implement pass-by-reference semantics." }, { "code": null, "e": 28754, "s": 28695, "text": "lvalue references can be used to alias an existing object." }, { "code": null, "e": 28818, "s": 28754, "text": "They can also be used to implement pass-by-reference semantics." }, { "code": null, "e": 28822, "s": 28818, "text": "C++" }, { "code": "// C++ program to illustrate lvalue#include <iostream>using namespace std; // Creating the references of the// parameter passed to the functionvoid swap(int& x, int& y){ int temp = x; x = y; y = temp;} // Driver Codeint main(){ // Given values int a{ 10 }, b{ 20 }; cout << \"a = \" << a << \" b = \" << b << endl; // Call by Reference swap(a, b); // Print the value cout << \"a = \" << a << \" b = \" << b << endl; return 0;}", "e": 29292, "s": 28822, "text": null }, { "code": null, "e": 29320, "s": 29292, "text": "a = 10 b = 20\na = 20 b = 10" }, { "code": null, "e": 29412, "s": 29322, "text": "Note: When the function return lvalue reference the expression becomes lvalue expression." }, { "code": null, "e": 29440, "s": 29412, "text": "Uses of rvalue references: " }, { "code": null, "e": 29663, "s": 29440, "text": "They are used in working with the move constructor and move assignment.cannot bind non-const lvalue reference of type ‘int&‘ to an rvalue of type ‘int’.cannot bind rvalue references of type ‘int&&‘ to lvalue of type ‘int’." }, { "code": null, "e": 29735, "s": 29663, "text": "They are used in working with the move constructor and move assignment." }, { "code": null, "e": 29817, "s": 29735, "text": "cannot bind non-const lvalue reference of type ‘int&‘ to an rvalue of type ‘int’." }, { "code": null, "e": 29888, "s": 29817, "text": "cannot bind rvalue references of type ‘int&&‘ to lvalue of type ‘int’." }, { "code": null, "e": 29901, "s": 29888, "text": "Program 1: " }, { "code": null, "e": 29905, "s": 29901, "text": "C++" }, { "code": "// C++ program to illustrate rvalue#include <iostream>using namespace std; // lvalue reference to the lvalue// passed as the parametervoid printReferenceValue(int& x){ cout << x << endl;} // Driver Codeint main(){ // Given value int a{ 10 }; // Function call is made lvalue & can // be assigned to lvalue reference printReferenceValue(a); return 0;}", "e": 30277, "s": 29905, "text": null }, { "code": null, "e": 30280, "s": 30277, "text": "10" }, { "code": null, "e": 30294, "s": 30282, "text": "Program 2: " }, { "code": null, "e": 30298, "s": 30294, "text": "C++" }, { "code": "// C++ program to illustrate rvalue#include <iostream>using namespace std; // Declaring rvalue reference to the// rvalue passed as the parametervoid printReferenceValue(int&& x){ cout << x << endl;} // Driver Codeint main(){ // Given value a int a{ 10 }; // Works fine as the function is // called with rvalue printReferenceValue(100); return 0;}", "e": 30667, "s": 30298, "text": null }, { "code": null, "e": 30671, "s": 30667, "text": "100" }, { "code": null, "e": 30688, "s": 30673, "text": "adnanirshad158" }, { "code": null, "e": 30707, "s": 30688, "text": "surindertarika1234" }, { "code": null, "e": 30723, "s": 30707, "text": "simranarora5sos" }, { "code": null, "e": 30741, "s": 30723, "text": "gulshankumarar231" }, { "code": null, "e": 30756, "s": 30741, "text": "C++-References" }, { "code": null, "e": 30771, "s": 30756, "text": "cpp-references" }, { "code": null, "e": 30775, "s": 30771, "text": "C++" }, { "code": null, "e": 30779, "s": 30775, "text": "CPP" }, { "code": null, "e": 30877, "s": 30779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30905, "s": 30877, "text": "Operator Overloading in C++" }, { "code": null, "e": 30925, "s": 30905, "text": "Polymorphism in C++" }, { "code": null, "e": 30958, "s": 30925, "text": "Friend class and function in C++" }, { "code": null, "e": 30982, "s": 30958, "text": "Sorting a vector in C++" }, { "code": null, "e": 31007, "s": 30982, "text": "std::string class in C++" }, { "code": null, "e": 31031, "s": 31007, "text": "Inline Functions in C++" }, { "code": null, "e": 31075, "s": 31031, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 31128, "s": 31075, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 31164, "s": 31128, "text": "Convert string to char array in C++" } ]
Difference between React.js and Angular.js - GeeksforGeeks
26 Nov, 2021 In this article, we will learn about React js & angular, along with discussing the significant distinction that differentiates Angular from React js. React.js: React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook. React uses a declarative paradigm that makes it easier to reason about your application and aims to be both efficient and flexible. It designs simple views for each state in your application, and React will efficiently update and render just the right component when your data changes. The declarative view makes your code more predictable and easier to debug. Features of React js: Scalability: It is reasonable for enormous scale applications because of its adaptable structure and scalability. Rich JavaScript Library: Developers from everywhere throughout the world are placing in an exertion to include significantly more features. Code Reusability: It enables the developers to reuse the code components of different levels while working on the project. Example: This example demonstrates the simple React js syntax. Javascript import React from 'react';import ReactDOM from 'react-dom'; var name = "Learner";var element = <h1>Hello, { name }.Welcome to GeeksforGeeks.</h1>; ReactDOM.render( element, document.getElementById("root")); Output: Simple React js example Angular: It is a popular open-source JavaScript framework created by Google for developing web applications. Front-end developers use frameworks like Angular or React for presenting and manipulating data efficiently. Updated Angular is much more efficient compared to the older version of Angular, especially, the core functionality was moved to different modules. That’s why it becomes so much fast and smooth compare to the older one. Newly added angular CLI. With that package, you can create a scaffolding for your Angular project. Features of Angular: Accessibility: It provides easier access as it holds ARIA-enabled components. Templates: Angular holds several templates to create UI views in a much faster manner by providing and suggesting some syntax. Testing: The program here is broken into several chunks which makes it easier to test. Testing is performed by the protractor in this case. Example: This example demonstrates the simple Angular program. app.component.html: HTML <hello name="{{ name }}"></hello><h2> Weclome to GeeksforGeeks Learning</h2> app.component.ts: Javascript import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { name = 'Geeks';} app.module.ts: Javascript import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component';import { HelloComponent } from './hello.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent, HelloComponent ], bootstrap: [ AppComponent ]})export class AppModule { } Output: Simple Angular example Difference between React.js & Angular: Though both react js and angular seems similar, but still there is significant contrast that differentiates both React.js and Angular, which is given below. React.js is a JavaScript library. As it indicates react js updates only the virtual DOM is present and the data flow is always in a single direction. Angular is a framework. Angular updates the Real DOM and the data flow is ensured in the architecture in both directions. React.js is more simplified as it follows MVC ie., Model View Control. This like angular includes features such as navigation but this can be achieved only with certain libraries like Redux and Flux. Needs more configuration and integration. The architecture of angular on the other hand is a bit complex as it follows MVVM models ie., Model View-ViewModel. This includes lots of tools and other features required for navigation, routing, and various other functionalities. React.js holds JSX hence the usage of HTML codes and syntax is enabled. But this doesn’t make react js a subset of HTML. This is purely JavaScript-based. Angular, on the other, is a mere subset of HTML. React.js is preferred when the dynamic content needed is intensive. As react js holds more straightforward programming and since it is reliable many apps such as Instagram, Facebook, and Twitter still prefer to react js over angular. Angular is platform-independent and hence is compatible to work in any platform. Hence, the HTML app which is compatible with all the browsers can prefer angular. One major app which uses angular is YouTube. React.js written in JavaScript. Written in Microsoft’s Typescript language, which is a superset of ECMAScript 6 (ES6). React.js Does not use the Dependency Injection concept. Angular Hierarchical Dependency Injection system used. Note: Angular is a great framework it has many improvements in terms of ReactJS, it is good at bigger applications. If you are a beginner or have less coding practice also if you want stability for your project you can go with ReactJS. bunnyram19 shubhamyadav4 bhaskargeeksforgeeks react-js AngularJS Difference Between JavaScript 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 Auth Guards in Angular 9/10/11 Angular PrimeNG Messages Component How to bundle an Angular app for production? Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Differences between IPv4 and IPv6
[ { "code": null, "e": 25772, "s": 25744, "text": "\n26 Nov, 2021" }, { "code": null, "e": 25922, "s": 25772, "text": "In this article, we will learn about React js & angular, along with discussing the significant distinction that differentiates Angular from React js." }, { "code": null, "e": 26576, "s": 25922, "text": "React.js: React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook. React uses a declarative paradigm that makes it easier to reason about your application and aims to be both efficient and flexible. It designs simple views for each state in your application, and React will efficiently update and render just the right component when your data changes. The declarative view makes your code more predictable and easier to debug. Features of React js:" }, { "code": null, "e": 26690, "s": 26576, "text": "Scalability: It is reasonable for enormous scale applications because of its adaptable structure and scalability." }, { "code": null, "e": 26830, "s": 26690, "text": "Rich JavaScript Library: Developers from everywhere throughout the world are placing in an exertion to include significantly more features." }, { "code": null, "e": 26953, "s": 26830, "text": "Code Reusability: It enables the developers to reuse the code components of different levels while working on the project." }, { "code": null, "e": 27016, "s": 26953, "text": "Example: This example demonstrates the simple React js syntax." }, { "code": null, "e": 27027, "s": 27016, "text": "Javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; var name = \"Learner\";var element = <h1>Hello, { name }.Welcome to GeeksforGeeks.</h1>; ReactDOM.render( element, document.getElementById(\"root\"));", "e": 27245, "s": 27027, "text": null }, { "code": null, "e": 27253, "s": 27245, "text": "Output:" }, { "code": null, "e": 27277, "s": 27253, "text": "Simple React js example" }, { "code": null, "e": 27834, "s": 27277, "text": "Angular: It is a popular open-source JavaScript framework created by Google for developing web applications. Front-end developers use frameworks like Angular or React for presenting and manipulating data efficiently. Updated Angular is much more efficient compared to the older version of Angular, especially, the core functionality was moved to different modules. That’s why it becomes so much fast and smooth compare to the older one. Newly added angular CLI. With that package, you can create a scaffolding for your Angular project. Features of Angular:" }, { "code": null, "e": 27912, "s": 27834, "text": "Accessibility: It provides easier access as it holds ARIA-enabled components." }, { "code": null, "e": 28039, "s": 27912, "text": "Templates: Angular holds several templates to create UI views in a much faster manner by providing and suggesting some syntax." }, { "code": null, "e": 28179, "s": 28039, "text": "Testing: The program here is broken into several chunks which makes it easier to test. Testing is performed by the protractor in this case." }, { "code": null, "e": 28242, "s": 28179, "text": "Example: This example demonstrates the simple Angular program." }, { "code": null, "e": 28262, "s": 28242, "text": "app.component.html:" }, { "code": null, "e": 28267, "s": 28262, "text": "HTML" }, { "code": "<hello name=\"{{ name }}\"></hello><h2> Weclome to GeeksforGeeks Learning</h2>", "e": 28345, "s": 28267, "text": null }, { "code": null, "e": 28363, "s": 28345, "text": "app.component.ts:" }, { "code": null, "e": 28374, "s": 28363, "text": "Javascript" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]})export class AppComponent { name = 'Geeks';}", "e": 28575, "s": 28374, "text": null }, { "code": null, "e": 28590, "s": 28575, "text": "app.module.ts:" }, { "code": null, "e": 28601, "s": 28590, "text": "Javascript" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component';import { HelloComponent } from './hello.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent, HelloComponent ], bootstrap: [ AppComponent ]})export class AppModule { }", "e": 29013, "s": 28601, "text": null }, { "code": null, "e": 29021, "s": 29013, "text": "Output:" }, { "code": null, "e": 29044, "s": 29021, "text": "Simple Angular example" }, { "code": null, "e": 29083, "s": 29044, "text": "Difference between React.js & Angular:" }, { "code": null, "e": 29240, "s": 29083, "text": "Though both react js and angular seems similar, but still there is significant contrast that differentiates both React.js and Angular, which is given below." }, { "code": null, "e": 29390, "s": 29240, "text": "React.js is a JavaScript library. As it indicates react js updates only the virtual DOM is present and the data flow is always in a single direction." }, { "code": null, "e": 29512, "s": 29390, "text": "Angular is a framework. Angular updates the Real DOM and the data flow is ensured in the architecture in both directions." }, { "code": null, "e": 29754, "s": 29512, "text": "React.js is more simplified as it follows MVC ie., Model View Control. This like angular includes features such as navigation but this can be achieved only with certain libraries like Redux and Flux. Needs more configuration and integration." }, { "code": null, "e": 29986, "s": 29754, "text": "The architecture of angular on the other hand is a bit complex as it follows MVVM models ie., Model View-ViewModel. This includes lots of tools and other features required for navigation, routing, and various other functionalities." }, { "code": null, "e": 30140, "s": 29986, "text": "React.js holds JSX hence the usage of HTML codes and syntax is enabled. But this doesn’t make react js a subset of HTML. This is purely JavaScript-based." }, { "code": null, "e": 30189, "s": 30140, "text": "Angular, on the other, is a mere subset of HTML." }, { "code": null, "e": 30423, "s": 30189, "text": "React.js is preferred when the dynamic content needed is intensive. As react js holds more straightforward programming and since it is reliable many apps such as Instagram, Facebook, and Twitter still prefer to react js over angular." }, { "code": null, "e": 30631, "s": 30423, "text": "Angular is platform-independent and hence is compatible to work in any platform. Hence, the HTML app which is compatible with all the browsers can prefer angular. One major app which uses angular is YouTube." }, { "code": null, "e": 30663, "s": 30631, "text": "React.js written in JavaScript." }, { "code": null, "e": 30750, "s": 30663, "text": "Written in Microsoft’s Typescript language, which is a superset of ECMAScript 6 (ES6)." }, { "code": null, "e": 30806, "s": 30750, "text": "React.js Does not use the Dependency Injection concept." }, { "code": null, "e": 30861, "s": 30806, "text": "Angular Hierarchical Dependency Injection system used." }, { "code": null, "e": 31097, "s": 30861, "text": "Note: Angular is a great framework it has many improvements in terms of ReactJS, it is good at bigger applications. If you are a beginner or have less coding practice also if you want stability for your project you can go with ReactJS." }, { "code": null, "e": 31108, "s": 31097, "text": "bunnyram19" }, { "code": null, "e": 31122, "s": 31108, "text": "shubhamyadav4" }, { "code": null, "e": 31143, "s": 31122, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 31152, "s": 31143, "text": "react-js" }, { "code": null, "e": 31162, "s": 31152, "text": "AngularJS" }, { "code": null, "e": 31181, "s": 31162, "text": "Difference Between" }, { "code": null, "e": 31192, "s": 31181, "text": "JavaScript" }, { "code": null, "e": 31209, "s": 31192, "text": "Web Technologies" }, { "code": null, "e": 31307, "s": 31209, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31342, "s": 31307, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31377, "s": 31342, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 31408, "s": 31377, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 31443, "s": 31408, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 31488, "s": 31443, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 31519, "s": 31488, "text": "Difference between BFS and DFS" }, { "code": null, "e": 31559, "s": 31519, "text": "Class method vs Static method in Python" }, { "code": null, "e": 31591, "s": 31559, "text": "Differences between TCP and UDP" }, { "code": null, "e": 31652, "s": 31591, "text": "Difference between var, let and const keywords in JavaScript" } ]
Count of matrices (of different orders) with given number of elements - GeeksforGeeks
13 May, 2021 Given a number N denotes the total number of elements in a matrix, the task is to print all possible order of matrix. An order is a pair (m, n) of integers where m is number of rows and n is number of columns. For example, if the number of elements is 8 then all possible orders are: (1, 8), (2, 4), (4, 2), (8, 1).Examples: Input: N = 8 Output: (1, 2) (2, 4) (4, 2) (8, 1)Input: N = 100 Output: (1, 100) (2, 50) (4, 25) (5, 20) (10, 10) (20, 5) (25, 4) (50, 2) (100, 1) Approach: A matrix is said to be of order m x n if it has m rows and n columns. The total number of elements in a matrix is equal to (m*n). So we start from 1 and check one by one if it divides N(the total number of elements). If it divides, it will be one possible order.Below is the implementation of the above approach: C++ Java Python C# PHP Javascript // C++ implementation of the above approach#include <iostream>using namespace std; // Function to print all possible ordervoid printAllOrder(int n){ // total number of elements in a matrix // of order m * n is equal (m*n) // where m is number of rows and n is // number of columns for (int i = 1; i <= n; i++) { // if n is divisible by i then i // and n/i will be the one // possible order of the matrix if (n % i == 0) { // print the given format cout << i << " " << n / i << endl; } }} // Driver codeint main(){ int n = 10; printAllOrder(n); return 0;} // Java implementation of the above approach class GFG { // Function to print all possible order static void printAllOrder(int n) { // total number of elements in a matrix // of order m * n is equal (m*n) // where m is number of rows and n is // number of columns for (int i = 1; i <= n; i++) { // if n is divisible by i then i // and n/i will be the one // possible order of the matrix if (n % i == 0) { // print the given format System.out.println( i + " " + n / i ); } } } // Driver code public static void main(String []args) { int n = 10; printAllOrder(n); } } // This code is contributed by ihritik # Python implementation of the above approach # Function to print all possible orderdef printAllOrder(n): # total number of elements in a matrix # of order m * n is equal (m*n) # where m is number of rows and n is # number of columns for i in range(1,n+1): # if n is divisible by i then i # and n/i will be the one # possible order of the matrix if (n % i == 0) : # print the given format print( i ,n // i ) # Driver coden = 10printAllOrder(n) # This code is contributed by ihritik // C# implementation of the above approach using System;class GFG { // Function to print all possible order static void printAllOrder(int n) { // total number of elements in a matrix // of order m * n is equal (m*n) // where m is number of rows and n is // number of columns for (int i = 1; i <= n; i++) { // if n is divisible by i then i // and n/i will be the one // possible order of the matrix if (n % i == 0) { // print the given format Console.WriteLine( i + " " + n / i ); } } } // Driver code public static void Main() { int n = 10; printAllOrder(n); } } // This code is contributed by ihritik <?php// PHP implementation of the above approach // Function to print all possible orderfunction printAllOrder($n){ // total number of elements in a matrix // of order m * n is equal (m*n) // where m is number of rows and n is // number of columns for ($i = 1; $i <= $n; $i++) { // if n is divisible by i then i // and n/i will be the one // possible order of the matrix if ($n % $i == 0) { // print the given format echo $i, " ", ($n / $i), "\n"; } }} // Driver code$n = 10;printAllOrder($n); // This code is contributed by Ryuga?> <script>// Java Script implementation of the above approach // Function to print all possible order function printAllOrder( n) { // total number of elements in a matrix // of order m * n is equal (m*n) // where m is number of rows and n is // number of columns for (let i = 1; i <= n; i++) { // if n is divisible by i then i // and n/i will be the one // possible order of the matrix if (n % i == 0) { // print the given format document.write( i + " " + n / i+"<br>" ); } } } // Driver code let n = 10; printAllOrder(n); // This code is contributed by sravan</script> 1 10 2 5 5 2 10 1 Time Complexity: O(n) Auxiliary Space: O(1) ihritik ankthon subham348 sravankumar8128 Combinatorial Matrix Matrix Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Count ways to reach the nth stair using step 1, 2 or 3 Combinational Sum Count of subsets with sum equal to X Python program to get all subsets of given size of a set Print all possible strings of length k that can be formed from a set of n characters Matrix Chain Multiplication | DP-8 Program to find largest element in an array Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Sudoku | Backtracking-7 Rat in a Maze | Backtracking-2
[ { "code": null, "e": 25254, "s": 25226, "text": "\n13 May, 2021" }, { "code": null, "e": 25580, "s": 25254, "text": "Given a number N denotes the total number of elements in a matrix, the task is to print all possible order of matrix. An order is a pair (m, n) of integers where m is number of rows and n is number of columns. For example, if the number of elements is 8 then all possible orders are: (1, 8), (2, 4), (4, 2), (8, 1).Examples: " }, { "code": null, "e": 25726, "s": 25580, "text": "Input: N = 8 Output: (1, 2) (2, 4) (4, 2) (8, 1)Input: N = 100 Output: (1, 100) (2, 50) (4, 25) (5, 20) (10, 10) (20, 5) (25, 4) (50, 2) (100, 1)" }, { "code": null, "e": 26051, "s": 25726, "text": "Approach: A matrix is said to be of order m x n if it has m rows and n columns. The total number of elements in a matrix is equal to (m*n). So we start from 1 and check one by one if it divides N(the total number of elements). If it divides, it will be one possible order.Below is the implementation of the above approach: " }, { "code": null, "e": 26055, "s": 26051, "text": "C++" }, { "code": null, "e": 26060, "s": 26055, "text": "Java" }, { "code": null, "e": 26067, "s": 26060, "text": "Python" }, { "code": null, "e": 26070, "s": 26067, "text": "C#" }, { "code": null, "e": 26074, "s": 26070, "text": "PHP" }, { "code": null, "e": 26085, "s": 26074, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <iostream>using namespace std; // Function to print all possible ordervoid printAllOrder(int n){ // total number of elements in a matrix // of order m * n is equal (m*n) // where m is number of rows and n is // number of columns for (int i = 1; i <= n; i++) { // if n is divisible by i then i // and n/i will be the one // possible order of the matrix if (n % i == 0) { // print the given format cout << i << \" \" << n / i << endl; } }} // Driver codeint main(){ int n = 10; printAllOrder(n); return 0;}", "e": 26726, "s": 26085, "text": null }, { "code": "// Java implementation of the above approach class GFG { // Function to print all possible order static void printAllOrder(int n) { // total number of elements in a matrix // of order m * n is equal (m*n) // where m is number of rows and n is // number of columns for (int i = 1; i <= n; i++) { // if n is divisible by i then i // and n/i will be the one // possible order of the matrix if (n % i == 0) { // print the given format System.out.println( i + \" \" + n / i ); } } } // Driver code public static void main(String []args) { int n = 10; printAllOrder(n); } } // This code is contributed by ihritik", "e": 27525, "s": 26726, "text": null }, { "code": "# Python implementation of the above approach # Function to print all possible orderdef printAllOrder(n): # total number of elements in a matrix # of order m * n is equal (m*n) # where m is number of rows and n is # number of columns for i in range(1,n+1): # if n is divisible by i then i # and n/i will be the one # possible order of the matrix if (n % i == 0) : # print the given format print( i ,n // i ) # Driver coden = 10printAllOrder(n) # This code is contributed by ihritik", "e": 28091, "s": 27525, "text": null }, { "code": "// C# implementation of the above approach using System;class GFG { // Function to print all possible order static void printAllOrder(int n) { // total number of elements in a matrix // of order m * n is equal (m*n) // where m is number of rows and n is // number of columns for (int i = 1; i <= n; i++) { // if n is divisible by i then i // and n/i will be the one // possible order of the matrix if (n % i == 0) { // print the given format Console.WriteLine( i + \" \" + n / i ); } } } // Driver code public static void Main() { int n = 10; printAllOrder(n); } } // This code is contributed by ihritik", "e": 28885, "s": 28091, "text": null }, { "code": "<?php// PHP implementation of the above approach // Function to print all possible orderfunction printAllOrder($n){ // total number of elements in a matrix // of order m * n is equal (m*n) // where m is number of rows and n is // number of columns for ($i = 1; $i <= $n; $i++) { // if n is divisible by i then i // and n/i will be the one // possible order of the matrix if ($n % $i == 0) { // print the given format echo $i, \" \", ($n / $i), \"\\n\"; } }} // Driver code$n = 10;printAllOrder($n); // This code is contributed by Ryuga?>", "e": 29505, "s": 28885, "text": null }, { "code": "<script>// Java Script implementation of the above approach // Function to print all possible order function printAllOrder( n) { // total number of elements in a matrix // of order m * n is equal (m*n) // where m is number of rows and n is // number of columns for (let i = 1; i <= n; i++) { // if n is divisible by i then i // and n/i will be the one // possible order of the matrix if (n % i == 0) { // print the given format document.write( i + \" \" + n / i+\"<br>\" ); } } } // Driver code let n = 10; printAllOrder(n); // This code is contributed by sravan</script>", "e": 30264, "s": 29505, "text": null }, { "code": null, "e": 30282, "s": 30264, "text": "1 10\n2 5\n5 2\n10 1" }, { "code": null, "e": 30306, "s": 30284, "text": "Time Complexity: O(n)" }, { "code": null, "e": 30328, "s": 30306, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 30336, "s": 30328, "text": "ihritik" }, { "code": null, "e": 30344, "s": 30336, "text": "ankthon" }, { "code": null, "e": 30354, "s": 30344, "text": "subham348" }, { "code": null, "e": 30370, "s": 30354, "text": "sravankumar8128" }, { "code": null, "e": 30384, "s": 30370, "text": "Combinatorial" }, { "code": null, "e": 30391, "s": 30384, "text": "Matrix" }, { "code": null, "e": 30398, "s": 30391, "text": "Matrix" }, { "code": null, "e": 30412, "s": 30398, "text": "Combinatorial" }, { "code": null, "e": 30510, "s": 30412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30519, "s": 30510, "text": "Comments" }, { "code": null, "e": 30532, "s": 30519, "text": "Old Comments" }, { "code": null, "e": 30587, "s": 30532, "text": "Count ways to reach the nth stair using step 1, 2 or 3" }, { "code": null, "e": 30605, "s": 30587, "text": "Combinational Sum" }, { "code": null, "e": 30642, "s": 30605, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 30699, "s": 30642, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 30784, "s": 30699, "text": "Print all possible strings of length k that can be formed from a set of n characters" }, { "code": null, "e": 30819, "s": 30784, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 30863, "s": 30819, "text": "Program to find largest element in an array" }, { "code": null, "e": 30925, "s": 30863, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 30949, "s": 30925, "text": "Sudoku | Backtracking-7" } ]
Guava - BigIntegerMath Class
BigIntegerMath provides utility methods on BigInteger. Following is the declaration for com.google.common.math.BigIntegerMath class − @GwtCompatible(emulated = true) public final class BigIntegerMath extends Object static BigInteger binomial(int n, int k) Returns n choose k, also known as the binomial coefficient of n and k, that is, n! / (k! (n - k)!). static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode) Returns the result of dividing p by q, rounding using the specified RoundingMode. static BigInteger factorial(int n) Returns n!, that is, the product of the first n positive integers, or 1 if n == 0. static boolean isPowerOfTwo(BigInteger x) Returns true if x represents a power of two. static int log10(BigInteger x, RoundingMode mode) Returns the base-10 logarithm of x, rounded according to the specified rounding mode. static int log2(BigInteger x, RoundingMode mode) Returns the base-2 logarithm of x, rounded according to the specified rounding mode. static BigInteger sqrt(BigInteger x, RoundingMode mode) Returns the square root of x, rounded with the specified rounding mode. This class inherits methods from the following class − java.lang.Object Create the following java program using any editor of your choice in say C:/> Guava. import java.math.BigInteger; import java.math.RoundingMode; import com.google.common.math.BigIntegerMath; public class GuavaTester { public static void main(String args[]) { GuavaTester tester = new GuavaTester(); tester.testBigIntegerMath(); } private void testBigIntegerMath() { System.out.println(BigIntegerMath.divide(BigInteger.TEN, new BigInteger("2"), RoundingMode.UNNECESSARY)); try { //exception will be thrown as 100 is not completely divisible by 3 // thus rounding is required, and RoundingMode is set as UNNESSARY System.out.println(BigIntegerMath.divide(BigInteger.TEN, new BigInteger("3"), RoundingMode.UNNECESSARY)); } catch(ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } System.out.println("Log2(2): " + BigIntegerMath.log2(new BigInteger("2"), RoundingMode.HALF_EVEN)); System.out.println("Log10(10): " + BigIntegerMath.log10(BigInteger.TEN, RoundingMode.HALF_EVEN)); System.out.println("sqrt(100): " + BigIntegerMath.sqrt(BigInteger.TEN.multiply(BigInteger.TEN), RoundingMode.HALF_EVEN)); System.out.println("factorial(5): "+BigIntegerMath.factorial(5)); } } Compile the class using javac compiler as follows − C:\Guava>javac GuavaTester.java Now run the GuavaTester to see the result. C:\Guava>java GuavaTester See the result. 5 Error: Rounding necessary Log2(2): 1 Log10(10): 1 sqrt(100): 10 factorial(5): 120 Print Add Notes Bookmark this page
[ { "code": null, "e": 1940, "s": 1885, "text": "BigIntegerMath provides utility methods on BigInteger." }, { "code": null, "e": 2019, "s": 1940, "text": "Following is the declaration for com.google.common.math.BigIntegerMath class −" }, { "code": null, "e": 2103, "s": 2019, "text": "@GwtCompatible(emulated = true)\npublic final class BigIntegerMath\n extends Object" }, { "code": null, "e": 2144, "s": 2103, "text": "static BigInteger binomial(int n, int k)" }, { "code": null, "e": 2244, "s": 2144, "text": "Returns n choose k, also known as the binomial coefficient of n and k, that is, n! / (k! (n - k)!)." }, { "code": null, "e": 2316, "s": 2244, "text": "static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode)" }, { "code": null, "e": 2398, "s": 2316, "text": "Returns the result of dividing p by q, rounding using the specified RoundingMode." }, { "code": null, "e": 2433, "s": 2398, "text": "static BigInteger factorial(int n)" }, { "code": null, "e": 2516, "s": 2433, "text": "Returns n!, that is, the product of the first n positive integers, or 1 if n == 0." }, { "code": null, "e": 2558, "s": 2516, "text": "static boolean isPowerOfTwo(BigInteger x)" }, { "code": null, "e": 2603, "s": 2558, "text": "Returns true if x represents a power of two." }, { "code": null, "e": 2653, "s": 2603, "text": "static int log10(BigInteger x, RoundingMode mode)" }, { "code": null, "e": 2739, "s": 2653, "text": "Returns the base-10 logarithm of x, rounded according to the specified rounding mode." }, { "code": null, "e": 2788, "s": 2739, "text": "static int log2(BigInteger x, RoundingMode mode)" }, { "code": null, "e": 2873, "s": 2788, "text": "Returns the base-2 logarithm of x, rounded according to the specified rounding mode." }, { "code": null, "e": 2929, "s": 2873, "text": "static BigInteger sqrt(BigInteger x, RoundingMode mode)" }, { "code": null, "e": 3001, "s": 2929, "text": "Returns the square root of x, rounded with the specified rounding mode." }, { "code": null, "e": 3056, "s": 3001, "text": "This class inherits methods from the following class −" }, { "code": null, "e": 3073, "s": 3056, "text": "java.lang.Object" }, { "code": null, "e": 3158, "s": 3073, "text": "Create the following java program using any editor of your choice in say C:/> Guava." }, { "code": null, "e": 4394, "s": 3158, "text": "import java.math.BigInteger;\nimport java.math.RoundingMode;\n\nimport com.google.common.math.BigIntegerMath;\n\npublic class GuavaTester {\n\n public static void main(String args[]) {\n GuavaTester tester = new GuavaTester();\n tester.testBigIntegerMath();\n }\n \n private void testBigIntegerMath() {\n System.out.println(BigIntegerMath.divide(BigInteger.TEN, new BigInteger(\"2\"), RoundingMode.UNNECESSARY));\n try {\n \n //exception will be thrown as 100 is not completely divisible by 3 \n // thus rounding is required, and RoundingMode is set as UNNESSARY\n System.out.println(BigIntegerMath.divide(BigInteger.TEN, new BigInteger(\"3\"), RoundingMode.UNNECESSARY));\n } catch(ArithmeticException e) {\n System.out.println(\"Error: \" + e.getMessage());\n }\n\n System.out.println(\"Log2(2): \" + BigIntegerMath.log2(new BigInteger(\"2\"), RoundingMode.HALF_EVEN));\n\n System.out.println(\"Log10(10): \" + BigIntegerMath.log10(BigInteger.TEN, RoundingMode.HALF_EVEN));\n\n System.out.println(\"sqrt(100): \" + BigIntegerMath.sqrt(BigInteger.TEN.multiply(BigInteger.TEN), RoundingMode.HALF_EVEN));\n\n System.out.println(\"factorial(5): \"+BigIntegerMath.factorial(5));\n }\n}" }, { "code": null, "e": 4446, "s": 4394, "text": "Compile the class using javac compiler as follows −" }, { "code": null, "e": 4479, "s": 4446, "text": "C:\\Guava>javac GuavaTester.java\n" }, { "code": null, "e": 4522, "s": 4479, "text": "Now run the GuavaTester to see the result." }, { "code": null, "e": 4549, "s": 4522, "text": "C:\\Guava>java GuavaTester\n" }, { "code": null, "e": 4565, "s": 4549, "text": "See the result." }, { "code": null, "e": 4650, "s": 4565, "text": "5\nError: Rounding necessary\nLog2(2): 1\nLog10(10): 1\nsqrt(100): 10\nfactorial(5): 120\n" }, { "code": null, "e": 4657, "s": 4650, "text": " Print" }, { "code": null, "e": 4668, "s": 4657, "text": " Add Notes" } ]
How to detect orientation change in layout in Android using Kotlin?
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="32sp" android:textStyle="bold" /> <TextView android:layout_centerInParent="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textSize="24sp" android:textStyle="bold" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.content.res.Configuration import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Toast.makeText(baseContext, "Landscape Mode", Toast.LENGTH_SHORT).show() } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { Toast.makeText(baseContext, "Portrait Mode", Toast.LENGTH_SHORT).show() } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1191, "s": 1062, "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": 1256, "s": 1191, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2221, "s": 1256, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout 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:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:layout_centerInParent=\"true\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>" }, { "code": null, "e": 2276, "s": 2221, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3079, "s": 2276, "text": "import android.content.res.Configuration\nimport android.os.Bundle\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n }\n override fun onConfigurationChanged(newConfig: Configuration) {\n super.onConfigurationChanged(newConfig)\n if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {\n Toast.makeText(baseContext, \"Landscape Mode\", Toast.LENGTH_SHORT).show()\n } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {\n Toast.makeText(baseContext, \"Portrait Mode\", Toast.LENGTH_SHORT).show()\n }\n }\n}" }, { "code": null, "e": 3134, "s": 3079, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3801, "s": 3134, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"app.com.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4149, "s": 3801, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Pandas - Cleaning Data
"Wrong data" does not have to be "empty cells" or "wrong format", it can just be wrong, like if someone registered "199" instead of "1.99". Sometimes you can spot wrong data by looking at the data set, because you have an expectation of what it should be. If you take a look at our data set, you can see that in row 7, the duration is 450, but for all the other rows the duration is between 30 and 60. It doesn't have to be wrong, but taking in consideration that this is the data set of someone's workout sessions, we conclude with the fact that this person did not work out in 450 minutes. Duration Date Pulse Maxpulse Calories 0 60 '2020/12/01' 110 130 409.1 1 60 '2020/12/02' 117 145 479.0 2 60 '2020/12/03' 103 135 340.0 3 45 '2020/12/04' 109 175 282.4 4 45 '2020/12/05' 117 148 406.0 5 60 '2020/12/06' 102 127 300.0 6 60 '2020/12/07' 110 136 374.0 7 450 '2020/12/08' 104 134 253.3 8 30 '2020/12/09' 109 133 195.1 9 60 '2020/12/10' 98 124 269.0 10 60 '2020/12/11' 103 147 329.3 11 60 '2020/12/12' 100 120 250.7 12 60 '2020/12/12' 100 120 250.7 13 60 '2020/12/13' 106 128 345.3 14 60 '2020/12/14' 104 132 379.3 15 60 '2020/12/15' 98 123 275.0 16 60 '2020/12/16' 98 120 215.2 17 60 '2020/12/17' 100 120 300.0 18 45 '2020/12/18' 90 112 NaN 19 60 '2020/12/19' 103 123 323.0 20 45 '2020/12/20' 97 125 243.0 21 60 '2020/12/21' 108 131 364.2 22 45 NaN 100 119 282.0 23 60 '2020/12/23' 130 101 300.0 24 45 '2020/12/24' 105 132 246.0 25 60 '2020/12/25' 102 126 334.5 26 60 20201226 100 120 250.0 27 60 '2020/12/27' 92 118 241.0 28 60 '2020/12/28' 103 132 NaN 29 60 '2020/12/29' 100 132 280.0 30 60 '2020/12/30' 102 129 380.3 31 60 '2020/12/31' 92 115 243.0 How can we fix wrong values, like the one for "Duration" in row 7? One way to fix wrong values is to replace them with something else. In our example, it is most likely a typo, and the value should be "45" instead of "450", and we could just insert "45" in row 7: Set "Duration" = 45 in row 7: For small data sets you might be able to replace the wrong data one by one, but not for big data sets. To replace wrong data for larger data sets you can create some rules, e.g. set some boundaries for legal values, and replace any values that are outside of the boundaries. Loop through all values in the "Duration" column. If the value is higher than 120, set it to 120: Another way of handling wrong data is to remove the rows that contains wrong data. This way you do not have to find out what to replace them with, and there is a good chance you do not need them to do your analyses. Delete rows where "Duration" is higher than 120: 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: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 142, "s": 0, "text": "\"Wrong data\" does not have to be \"empty cells\" or \"wrong format\", it can \njust be wrong, like if someone registered \"199\" instead of \"1.99\"." }, { "code": null, "e": 259, "s": 142, "text": "Sometimes you can spot wrong data by looking at the data set, because you have an expectation of what \nit should be." }, { "code": null, "e": 405, "s": 259, "text": "If you take a look at our data set, you can see that in row 7, the duration is 450, but for all the other rows the duration is between 30 and 60." }, { "code": null, "e": 596, "s": 405, "text": "It doesn't have to be wrong, but taking in consideration that this is the data set of someone's workout \nsessions,\nwe conclude with the fact that this person did not work out in 450 minutes." }, { "code": null, "e": 2447, "s": 596, "text": "\n Duration Date Pulse Maxpulse Calories\n 0 60 '2020/12/01' 110 130 409.1\n 1 60 '2020/12/02' 117 145 479.0\n 2 60 '2020/12/03' 103 135 340.0\n 3 45 '2020/12/04' 109 175 282.4\n 4 45 '2020/12/05' 117 148 406.0\n 5 60 '2020/12/06' 102 127 300.0\n 6 60 '2020/12/07' 110 136 374.0\n 7 450 '2020/12/08' 104 134 253.3\n 8 30 '2020/12/09' 109 133 195.1\n 9 60 '2020/12/10' 98 124 269.0\n 10 60 '2020/12/11' 103 147 329.3\n 11 60 '2020/12/12' 100 120 250.7\n 12 60 '2020/12/12' 100 120 250.7\n 13 60 '2020/12/13' 106 128 345.3\n 14 60 '2020/12/14' 104 132 379.3\n 15 60 '2020/12/15' 98 123 275.0\n 16 60 '2020/12/16' 98 120 215.2\n 17 60 '2020/12/17' 100 120 300.0\n 18 45 '2020/12/18' 90 112 NaN\n 19 60 '2020/12/19' 103 123 323.0\n 20 45 '2020/12/20' 97 125 243.0\n 21 60 '2020/12/21' 108 131 364.2\n 22 45 NaN 100 119 282.0\n 23 60 '2020/12/23' 130 101 300.0\n 24 45 '2020/12/24' 105 132 246.0\n 25 60 '2020/12/25' 102 126 334.5\n 26 60 20201226 100 120 250.0\n 27 60 '2020/12/27' 92 118 241.0\n 28 60 '2020/12/28' 103 132 NaN\n 29 60 '2020/12/29' 100 132 280.0\n 30 60 '2020/12/30' 102 129 380.3\n 31 60 '2020/12/31' 92 115 243.0\n\n" }, { "code": null, "e": 2514, "s": 2447, "text": "How can we fix wrong values, like the one for \"Duration\" in row 7?" }, { "code": null, "e": 2582, "s": 2514, "text": "One way to fix wrong values is to replace them with something else." }, { "code": null, "e": 2713, "s": 2582, "text": "In our example, it is most likely a typo, and the value should be \"45\" instead of \"450\", and \nwe \ncould just insert \"45\" in row 7:" }, { "code": null, "e": 2743, "s": 2713, "text": "Set \"Duration\" = 45 in row 7:" }, { "code": null, "e": 2847, "s": 2743, "text": "For small data sets you might be able to replace the wrong data one by one, \nbut not for big data sets." }, { "code": null, "e": 3021, "s": 2847, "text": "To replace wrong data for larger data sets you can create some rules, e.g. \nset some boundaries for legal values, and replace any values that are outside of the \nboundaries." }, { "code": null, "e": 3071, "s": 3021, "text": "Loop through all values in the \"Duration\" column." }, { "code": null, "e": 3119, "s": 3071, "text": "If the value is higher than 120, set it to 120:" }, { "code": null, "e": 3202, "s": 3119, "text": "Another way of handling wrong data is to remove the rows that contains wrong data." }, { "code": null, "e": 3336, "s": 3202, "text": "This way you do not have to find out what to replace them with, and there is \na good chance you do not need them to do your analyses." }, { "code": null, "e": 3385, "s": 3336, "text": "Delete rows where \"Duration\" is higher than 120:" }, { "code": null, "e": 3418, "s": 3385, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3460, "s": 3418, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3567, "s": 3460, "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": 3586, "s": 3567, "text": "[email protected]" } ]
Using Azure Data Factory to incrementally copy files based on URL pattern over HTTP | by Dhyanendra Singh Rathore | Towards Data Science
Copying files using Azure Data Factory is straightforward; however, it gets tricky if the files are being hosted on a third-party web server, and the only way to copy them is by using their URL. In this article, we look at an innovative use of Data factory activities to generate the URLs on the fly to fetch the content over HTTP and store it in our storage account for further processing. Caution: Microsoft Azure is a paid service, and following this article can cause financial liability to you or your organization. Please read our terms of use before proceeding with this article: https://dhyanintech.medium.com/disclaimer-disclosure-terms-of-use-fb3bfbd1e0e5 An active Microsoft Azure subscriptionAzure Data Factory instanceAzure Data Lake Storage Gen2 storage An active Microsoft Azure subscription Azure Data Factory instance Azure Data Lake Storage Gen2 storage If you don’t have prerequisites set up yet, refer to our previous article for instructions on how to create them: medium.com This article will set up our Data factory to fetch publicly available CSV files from the COVID-19 repository at GitHub operated by Johns Hopkins University Center for Systems Science and Engineering (JHU CSSE). We’re interested in the data residing within csse_covid_19_data/csse_covid_19_daily_reports. This folder contains daily case reports with new reports added once daily since January 22, 2020. Files follow a consistent naming convention of MM-DD-YYYY.csv github.com A typical way of ingesting these files for our project is to download the repository as a zip from GitHub, extracting the files on your client machine, and upload the files to our storage account manually. On the other hand, we will have to upload a new file daily if we want to keep our Power BI report up to date with COVID-19 data. We want to find a solution to automate the ingesting task to keep our data up to date without additional manual efforts. We can achieve this using the Azure Data Factory. Our thought process should be: Create a pipeline to fetch files from GitHub and store it in our storage account We can fetch only one file at a time using its Raw URL (open a file at the GitHub URL and click on Raw to open the file without GitHub’s UI): https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/01-22-2020.csv Recall that files follow a naming convention (MM-DD-YYYY.csv); we need to create Data factory activities to generate the file names automatically, i.e., next URL to request via pipeline. We need to repeat the task multiple times; the first time, we will fetch all the files that already exist in the repository and then once every day. Transform the ingested files using Azure Databricks Activities typically contain the transformation logic or the analysis commands of the Azure Data Factory’s work and defines actions to perform on your data. A pipeline is a logical grouping of Data Factory activities that together perform a task. Pipelines can be scheduled to execute, or a trigger can be defined that determines when a pipeline execution needs to be kicked off. Further reading: docs.microsoft.com Sign in to the Azure Portal, locate and open your Data factory. We can do that in multiple ways: Select Author & Monitor on the Overview page to load our Data Factory instance in a new browser tab. Switch to the next tab (our Data Factory) and select Manage on the left-corner menu. Let’s start by creating linked services to tell the data factory where do our resources exist. Linked services are like connection strings, which define the connection information needed for the Data Factory to connect to external resources. We need to create two linked services, the first to tell the Data Factory about our data source (i.e., GitHub) and how to connect to it. We need to provide the HTTP address (Raw URL of the repository without a file name) as Base URL (https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/). Follow the below steps: The second linked service to tell our Data Factory about the data destination (i.e., storage account). Create a new linked service and search for Storage on the New linked service blade, select Azure Data Lake Store Gen2 from the matched resources list, and click Continue. Select the correct storage account from the drop-down (4). At this point, your screen should look like, as shown below. Click on Publish all to persist your changes, i.e., save. Click Publish on the Publish all blade and wait for the deployment to finish; it might take a few seconds. Next up, we need to create datasets to tell our Data factory what data to use and its format. We need to create two datasets linked to our two linked services. A dataset is a named view of data that simply points or references the data we want to use in our activities as inputs and outputs. Datasets represent data within different data stores, reachable via a linked service. Select the Author on the left-corner menu, locate Datasets on the Factory Resources blade and click on the number shown. Select New dataset and follow the steps to create our first dataset to represent our GitHub data. Our new dataset will open up, exposing options to configure further and define our data structure. Notice Base URL under the Connection tab is populated with the raw folder URL we provided in our linked service. Our data lies at the file URL, so we need to provide the absolute URL for the Data Factory to consume the data. We will use the Relative URL field to derive a complete URL to our file (Base URL + Relative URL). However, we want our pipeline to fetch multiple files; hence instead of providing a straight-up file name, we will use a parameter to generate file names dynamically on the fly. We can use parameters to pass external values into pipelines, datasets, linked services, and data flows. By parameterizing resources, we can reuse them with different values each time. Parameters are set for the whole duration of the pipeline run. They are like constants in a programming language, defined at the top of the source code. Switch to the Parameters tab and click + New to create a new parameter. Set the fields as shown; we’re using the first CSV file’s name as the default value. Switch to Connection tab and set Relative URL as @dataset().fileName. Syntax to refer to the dataset parameters: @dataset().PARAMETER_NAME We can either type the parameter name with correct syntax or use the Add dynamic content blade to fill it (5–7). Dynamic content in Azure Data Factory uses expression language. Further reading: docs.microsoft.com Create a new dataset representing the data in our storage account. Follow the steps mentioned previously (search for Azure Data Lake Storage Gen2 instead of HTTP on New dataset blade). Your new dataset should look like as below; publish all changes to make them available for use in our Data Factory. Now that we have fulfilled the requirements to set up our Data Factory, it’s time to create a pipeline that will perform the actual task. Let’s start by creating a new pipeline from the Factory Resources blade (similar to creating a new dataset). Give a name to your new pipeline and create two variables (i and j) of type string and 01–22–2020 as default value in the Variables tab. Variables can be set at the start of a pipeline, and read and modified during a run. Variables contain real value at runtime and can be assigned to parameters. They are like normal variables in a programming language. It’s time to add activities to our pipeline; all activities are available on the Activities blade. We will use the following activities: Get Metadata: to get the list of all the CSV files that exist in our store. Initially, this will return null as there are no files in our store yet. The output will act as input to the next Set Variable activity. Set variable (1): to set our variable i with the latest file's name in our store. Initially, this will set i with the default value of variable j (i.e., 01–22–2020) as input from Get Metadata activity will be empty. Calculated output (variable i) will act as input to the next Until activity. Until: to generate file names from the latest available file date until today, input value i will be used as the start date, and today-1 will be used as the end date. The generated output (variable i) will act as input to the next Copy data sub-activity. Copy data: to copy the actual file over HTTP and store it to our storage. Input from the Until activity (variable i) will be passed to our source dataset’s parameter fileName, completing our URL to the raw CSV file. The file will be accessed over HTTP and saved to our storage. The success end will connect to our next Set variable activity. Set variable (2 & 3): to increment the variable i for the next iteration. We need two set variable activities as we cannot reference the variable being set in the Value field; hence we will use our variable j as an intermediate variable to increment i. Locate Get Metadata under the General category, drag and drop it on the canvas. Give it a name and proceed, as shown below. Syntax to refer to the output of the Get Metadata activity: @{activity('GET_METADATA_ACTIVITY_NAME').output.FIELD_NAME} Locate Set Variable under the General category, drag and drop it on the canvas. Connect it with the Success (green) end of Get Metadata activity. Give it a name and set variable i as follows @if(empty(last(activity('ac_checkAllAvailableFiles').output.childItems)),variables('j'),formatDateTime(addDays(formatDateTime(replace(last(activity('ac_checkAllavailableFiles').output.childItems).name,'.csv',''),'MM-dd-yyyy'),1),'MM-dd-yyyy')) You can open the Add dynamic content blade by clicking on the Value field; you can either type or copy-paste the above expression or use the blade's controls to create the expression. Locate Until under Iteration & conditionals category, drag and drop it on the canvas, and connect it with the previous set variable activity's success end. Give it a name; in the Settings tab, enter the following Expression: @greater(dayOfYear(formatDateTime(variables('i'),'MM-dd-yyyy')),dayOfYear(subtractFromTime(utcnow(),1,'Day'))) Move to the Activities tab and click on the edit icon to add the rest of the activities. We will add other activities inside the Until as we need to perform them multiple times. Clicking on the edit icon will show us an empty canvas, signifying we’re now adding activities in the Until activity to iterate over. Locate Copy data under Move & transform category, drag and drop it on the canvas. Give it a name, set the Source and Sink tab configuration, as shown in the image. We will assign the fileName parameter with the variable i. Here’s the fileName expression for convenient copy-paste :) @concat(formatDateTime(variables('i'),'MM-dd-yyyy'),'.csv') Add another Set variable activity. Connect it with the success end of Copy data activity. Give it a name and set variable j as @addDays(formatDateTime(variables('i'),'MM-dd-yyyy'),1) Add another Set variable activity and connect it with the success end of the previous Set variable activity. Set i as @variables('j') Our pipeline is now ready; it should look something like below. Additionally, you can refer to the JSON of our pipeline from GitHub at the end of the article for any troubleshooting purposes. The next step after adding all the activities is to validate our pipeline. Locate and select the Validate option to ensure our pipeline is free from errors and is ready to execute. The pipeline validation output blade will show us the results of the validation. We have two options to run our pipeline and see the fruits of our labor. We can debug run our pipeline without publishing our changes, or we can publish our changes first. It is advisable to Debug run the pipeline first, then publish the changes; debug run shows us logs and other useful tracking info in the pipeline's Output tab. Dedicate a few minutes to go through the output logs to get a clear picture of the execution and various activities. The sample output is shown below. You can also use the Add trigger option to run the pipeline right away or set a custom trigger to run the pipeline at specific intervals, time, or based on an external event. We presented a compelling problem of copying data over HTTP by using URL. We discussed the various components that make up a pipeline, and we set up an innovative Data Factory pipeline to solve the problem at hand. We also discussed how to set the pipeline's automatic execution and a brief overview of the pipeline execution logs. If you’re following our series on turning CSV data into Power BI visuals, please head to our next article to continue the journey with cleansing and transforming data in Azure Databricks using PySpark. medium.com If you’re trying to add and execute a Databricks notebook in your Data Factory pipeline, we have the perfect thing to show you the way. medium.com Dhyanendra Singh Rathore is a Microsoft-certified Data, BI, and power platform professional. He is passionate about solving problems and currently gravitating towards serverless computing and AI platforms. He has a Master’s degree in Computer Networking Engineering. You can join him on Medium or connect with him on LinkedIn. Got any topic-related issues you wish to discuss? Shoot an email to [email protected] for a private consultation.
[ { "code": null, "e": 367, "s": 172, "text": "Copying files using Azure Data Factory is straightforward; however, it gets tricky if the files are being hosted on a third-party web server, and the only way to copy them is by using their URL." }, { "code": null, "e": 563, "s": 367, "text": "In this article, we look at an innovative use of Data factory activities to generate the URLs on the fly to fetch the content over HTTP and store it in our storage account for further processing." }, { "code": null, "e": 693, "s": 563, "text": "Caution: Microsoft Azure is a paid service, and following this article can cause financial liability to you or your organization." }, { "code": null, "e": 838, "s": 693, "text": "Please read our terms of use before proceeding with this article: https://dhyanintech.medium.com/disclaimer-disclosure-terms-of-use-fb3bfbd1e0e5" }, { "code": null, "e": 940, "s": 838, "text": "An active Microsoft Azure subscriptionAzure Data Factory instanceAzure Data Lake Storage Gen2 storage" }, { "code": null, "e": 979, "s": 940, "text": "An active Microsoft Azure subscription" }, { "code": null, "e": 1007, "s": 979, "text": "Azure Data Factory instance" }, { "code": null, "e": 1044, "s": 1007, "text": "Azure Data Lake Storage Gen2 storage" }, { "code": null, "e": 1158, "s": 1044, "text": "If you don’t have prerequisites set up yet, refer to our previous article for instructions on how to create them:" }, { "code": null, "e": 1169, "s": 1158, "text": "medium.com" }, { "code": null, "e": 1633, "s": 1169, "text": "This article will set up our Data factory to fetch publicly available CSV files from the COVID-19 repository at GitHub operated by Johns Hopkins University Center for Systems Science and Engineering (JHU CSSE). We’re interested in the data residing within csse_covid_19_data/csse_covid_19_daily_reports. This folder contains daily case reports with new reports added once daily since January 22, 2020. Files follow a consistent naming convention of MM-DD-YYYY.csv" }, { "code": null, "e": 1644, "s": 1633, "text": "github.com" }, { "code": null, "e": 2181, "s": 1644, "text": "A typical way of ingesting these files for our project is to download the repository as a zip from GitHub, extracting the files on your client machine, and upload the files to our storage account manually. On the other hand, we will have to upload a new file daily if we want to keep our Power BI report up to date with COVID-19 data. We want to find a solution to automate the ingesting task to keep our data up to date without additional manual efforts. We can achieve this using the Azure Data Factory. Our thought process should be:" }, { "code": null, "e": 2262, "s": 2181, "text": "Create a pipeline to fetch files from GitHub and store it in our storage account" }, { "code": null, "e": 2531, "s": 2262, "text": "We can fetch only one file at a time using its Raw URL (open a file at the GitHub URL and click on Raw to open the file without GitHub’s UI): https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/01-22-2020.csv" }, { "code": null, "e": 2718, "s": 2531, "text": "Recall that files follow a naming convention (MM-DD-YYYY.csv); we need to create Data factory activities to generate the file names automatically, i.e., next URL to request via pipeline." }, { "code": null, "e": 2867, "s": 2718, "text": "We need to repeat the task multiple times; the first time, we will fetch all the files that already exist in the repository and then once every day." }, { "code": null, "e": 2919, "s": 2867, "text": "Transform the ingested files using Azure Databricks" }, { "code": null, "e": 3076, "s": 2919, "text": "Activities typically contain the transformation logic or the analysis commands of the Azure Data Factory’s work and defines actions to perform on your data." }, { "code": null, "e": 3299, "s": 3076, "text": "A pipeline is a logical grouping of Data Factory activities that together perform a task. Pipelines can be scheduled to execute, or a trigger can be defined that determines when a pipeline execution needs to be kicked off." }, { "code": null, "e": 3316, "s": 3299, "text": "Further reading:" }, { "code": null, "e": 3335, "s": 3316, "text": "docs.microsoft.com" }, { "code": null, "e": 3432, "s": 3335, "text": "Sign in to the Azure Portal, locate and open your Data factory. We can do that in multiple ways:" }, { "code": null, "e": 3713, "s": 3432, "text": "Select Author & Monitor on the Overview page to load our Data Factory instance in a new browser tab. Switch to the next tab (our Data Factory) and select Manage on the left-corner menu. Let’s start by creating linked services to tell the data factory where do our resources exist." }, { "code": null, "e": 3860, "s": 3713, "text": "Linked services are like connection strings, which define the connection information needed for the Data Factory to connect to external resources." }, { "code": null, "e": 4233, "s": 3860, "text": "We need to create two linked services, the first to tell the Data Factory about our data source (i.e., GitHub) and how to connect to it. We need to provide the HTTP address (Raw URL of the repository without a file name) as Base URL (https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/). Follow the below steps:" }, { "code": null, "e": 4566, "s": 4233, "text": "The second linked service to tell our Data Factory about the data destination (i.e., storage account). Create a new linked service and search for Storage on the New linked service blade, select Azure Data Lake Store Gen2 from the matched resources list, and click Continue. Select the correct storage account from the drop-down (4)." }, { "code": null, "e": 4792, "s": 4566, "text": "At this point, your screen should look like, as shown below. Click on Publish all to persist your changes, i.e., save. Click Publish on the Publish all blade and wait for the deployment to finish; it might take a few seconds." }, { "code": null, "e": 4952, "s": 4792, "text": "Next up, we need to create datasets to tell our Data factory what data to use and its format. We need to create two datasets linked to our two linked services." }, { "code": null, "e": 5170, "s": 4952, "text": "A dataset is a named view of data that simply points or references the data we want to use in our activities as inputs and outputs. Datasets represent data within different data stores, reachable via a linked service." }, { "code": null, "e": 5389, "s": 5170, "text": "Select the Author on the left-corner menu, locate Datasets on the Factory Resources blade and click on the number shown. Select New dataset and follow the steps to create our first dataset to represent our GitHub data." }, { "code": null, "e": 5990, "s": 5389, "text": "Our new dataset will open up, exposing options to configure further and define our data structure. Notice Base URL under the Connection tab is populated with the raw folder URL we provided in our linked service. Our data lies at the file URL, so we need to provide the absolute URL for the Data Factory to consume the data. We will use the Relative URL field to derive a complete URL to our file (Base URL + Relative URL). However, we want our pipeline to fetch multiple files; hence instead of providing a straight-up file name, we will use a parameter to generate file names dynamically on the fly." }, { "code": null, "e": 6175, "s": 5990, "text": "We can use parameters to pass external values into pipelines, datasets, linked services, and data flows. By parameterizing resources, we can reuse them with different values each time." }, { "code": null, "e": 6328, "s": 6175, "text": "Parameters are set for the whole duration of the pipeline run. They are like constants in a programming language, defined at the top of the source code." }, { "code": null, "e": 6555, "s": 6328, "text": "Switch to the Parameters tab and click + New to create a new parameter. Set the fields as shown; we’re using the first CSV file’s name as the default value. Switch to Connection tab and set Relative URL as @dataset().fileName." }, { "code": null, "e": 6624, "s": 6555, "text": "Syntax to refer to the dataset parameters: @dataset().PARAMETER_NAME" }, { "code": null, "e": 6737, "s": 6624, "text": "We can either type the parameter name with correct syntax or use the Add dynamic content blade to fill it (5–7)." }, { "code": null, "e": 6801, "s": 6737, "text": "Dynamic content in Azure Data Factory uses expression language." }, { "code": null, "e": 6818, "s": 6801, "text": "Further reading:" }, { "code": null, "e": 6837, "s": 6818, "text": "docs.microsoft.com" }, { "code": null, "e": 7138, "s": 6837, "text": "Create a new dataset representing the data in our storage account. Follow the steps mentioned previously (search for Azure Data Lake Storage Gen2 instead of HTTP on New dataset blade). Your new dataset should look like as below; publish all changes to make them available for use in our Data Factory." }, { "code": null, "e": 7385, "s": 7138, "text": "Now that we have fulfilled the requirements to set up our Data Factory, it’s time to create a pipeline that will perform the actual task. Let’s start by creating a new pipeline from the Factory Resources blade (similar to creating a new dataset)." }, { "code": null, "e": 7522, "s": 7385, "text": "Give a name to your new pipeline and create two variables (i and j) of type string and 01–22–2020 as default value in the Variables tab." }, { "code": null, "e": 7682, "s": 7522, "text": "Variables can be set at the start of a pipeline, and read and modified during a run. Variables contain real value at runtime and can be assigned to parameters." }, { "code": null, "e": 7740, "s": 7682, "text": "They are like normal variables in a programming language." }, { "code": null, "e": 7877, "s": 7740, "text": "It’s time to add activities to our pipeline; all activities are available on the Activities blade. We will use the following activities:" }, { "code": null, "e": 8090, "s": 7877, "text": "Get Metadata: to get the list of all the CSV files that exist in our store. Initially, this will return null as there are no files in our store yet. The output will act as input to the next Set Variable activity." }, { "code": null, "e": 8383, "s": 8090, "text": "Set variable (1): to set our variable i with the latest file's name in our store. Initially, this will set i with the default value of variable j (i.e., 01–22–2020) as input from Get Metadata activity will be empty. Calculated output (variable i) will act as input to the next Until activity." }, { "code": null, "e": 8638, "s": 8383, "text": "Until: to generate file names from the latest available file date until today, input value i will be used as the start date, and today-1 will be used as the end date. The generated output (variable i) will act as input to the next Copy data sub-activity." }, { "code": null, "e": 8980, "s": 8638, "text": "Copy data: to copy the actual file over HTTP and store it to our storage. Input from the Until activity (variable i) will be passed to our source dataset’s parameter fileName, completing our URL to the raw CSV file. The file will be accessed over HTTP and saved to our storage. The success end will connect to our next Set variable activity." }, { "code": null, "e": 9233, "s": 8980, "text": "Set variable (2 & 3): to increment the variable i for the next iteration. We need two set variable activities as we cannot reference the variable being set in the Value field; hence we will use our variable j as an intermediate variable to increment i." }, { "code": null, "e": 9357, "s": 9233, "text": "Locate Get Metadata under the General category, drag and drop it on the canvas. Give it a name and proceed, as shown below." }, { "code": null, "e": 9477, "s": 9357, "text": "Syntax to refer to the output of the Get Metadata activity: @{activity('GET_METADATA_ACTIVITY_NAME').output.FIELD_NAME}" }, { "code": null, "e": 9668, "s": 9477, "text": "Locate Set Variable under the General category, drag and drop it on the canvas. Connect it with the Success (green) end of Get Metadata activity. Give it a name and set variable i as follows" }, { "code": null, "e": 9912, "s": 9668, "text": "@if(empty(last(activity('ac_checkAllAvailableFiles').output.childItems)),variables('j'),formatDateTime(addDays(formatDateTime(replace(last(activity('ac_checkAllavailableFiles').output.childItems).name,'.csv',''),'MM-dd-yyyy'),1),'MM-dd-yyyy'))" }, { "code": null, "e": 10096, "s": 9912, "text": "You can open the Add dynamic content blade by clicking on the Value field; you can either type or copy-paste the above expression or use the blade's controls to create the expression." }, { "code": null, "e": 10321, "s": 10096, "text": "Locate Until under Iteration & conditionals category, drag and drop it on the canvas, and connect it with the previous set variable activity's success end. Give it a name; in the Settings tab, enter the following Expression:" }, { "code": null, "e": 10432, "s": 10321, "text": "@greater(dayOfYear(formatDateTime(variables('i'),'MM-dd-yyyy')),dayOfYear(subtractFromTime(utcnow(),1,'Day')))" }, { "code": null, "e": 10744, "s": 10432, "text": "Move to the Activities tab and click on the edit icon to add the rest of the activities. We will add other activities inside the Until as we need to perform them multiple times. Clicking on the edit icon will show us an empty canvas, signifying we’re now adding activities in the Until activity to iterate over." }, { "code": null, "e": 11027, "s": 10744, "text": "Locate Copy data under Move & transform category, drag and drop it on the canvas. Give it a name, set the Source and Sink tab configuration, as shown in the image. We will assign the fileName parameter with the variable i. Here’s the fileName expression for convenient copy-paste :)" }, { "code": null, "e": 11087, "s": 11027, "text": "@concat(formatDateTime(variables('i'),'MM-dd-yyyy'),'.csv')" }, { "code": null, "e": 11214, "s": 11087, "text": "Add another Set variable activity. Connect it with the success end of Copy data activity. Give it a name and set variable j as" }, { "code": null, "e": 11270, "s": 11214, "text": "@addDays(formatDateTime(variables('i'),'MM-dd-yyyy'),1)" }, { "code": null, "e": 11404, "s": 11270, "text": "Add another Set variable activity and connect it with the success end of the previous Set variable activity. Set i as @variables('j')" }, { "code": null, "e": 11596, "s": 11404, "text": "Our pipeline is now ready; it should look something like below. Additionally, you can refer to the JSON of our pipeline from GitHub at the end of the article for any troubleshooting purposes." }, { "code": null, "e": 11858, "s": 11596, "text": "The next step after adding all the activities is to validate our pipeline. Locate and select the Validate option to ensure our pipeline is free from errors and is ready to execute. The pipeline validation output blade will show us the results of the validation." }, { "code": null, "e": 12341, "s": 11858, "text": "We have two options to run our pipeline and see the fruits of our labor. We can debug run our pipeline without publishing our changes, or we can publish our changes first. It is advisable to Debug run the pipeline first, then publish the changes; debug run shows us logs and other useful tracking info in the pipeline's Output tab. Dedicate a few minutes to go through the output logs to get a clear picture of the execution and various activities. The sample output is shown below." }, { "code": null, "e": 12516, "s": 12341, "text": "You can also use the Add trigger option to run the pipeline right away or set a custom trigger to run the pipeline at specific intervals, time, or based on an external event." }, { "code": null, "e": 12848, "s": 12516, "text": "We presented a compelling problem of copying data over HTTP by using URL. We discussed the various components that make up a pipeline, and we set up an innovative Data Factory pipeline to solve the problem at hand. We also discussed how to set the pipeline's automatic execution and a brief overview of the pipeline execution logs." }, { "code": null, "e": 13050, "s": 12848, "text": "If you’re following our series on turning CSV data into Power BI visuals, please head to our next article to continue the journey with cleansing and transforming data in Azure Databricks using PySpark." }, { "code": null, "e": 13061, "s": 13050, "text": "medium.com" }, { "code": null, "e": 13197, "s": 13061, "text": "If you’re trying to add and execute a Databricks notebook in your Data Factory pipeline, we have the perfect thing to show you the way." }, { "code": null, "e": 13208, "s": 13197, "text": "medium.com" }, { "code": null, "e": 13475, "s": 13208, "text": "Dhyanendra Singh Rathore is a Microsoft-certified Data, BI, and power platform professional. He is passionate about solving problems and currently gravitating towards serverless computing and AI platforms. He has a Master’s degree in Computer Networking Engineering." }, { "code": null, "e": 13535, "s": 13475, "text": "You can join him on Medium or connect with him on LinkedIn." } ]
Implementing Stack in C# - GeeksforGeeks
30 Oct, 2018 Stack is a linear data structure. It follows LIFO(Last In First Out) pattern for Input/output. Following three basic operations are performed in the stack: Push: Adds an item in the stack. If the stack is full, then it is said to be a stack Overflow condition. Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be a stack Underflow condition. Peek : Return the topmost element of stack. Given below is the C# code to implement Stack using Arrays using System; namespace StackImplementation{ internal class Stack { static readonly int MAX = 1000; int top; int[] stack = new int[MAX]; bool IsEmpty() { return (top < 0); } public Stack() { top = -1; } internal bool Push(int data) { if (top >= MAX) { Console.WriteLine("Stack Overflow"); return false; } else { stack[++top] = data; return true; } } internal int Pop() { if (top < 0) { Console.WriteLine("Stack Underflow"); return 0; } else { int value = stack[top--]; return value; } } internal void Peek() { if (top < 0) { Console.WriteLine("Stack Underflow"); return; } else Console.WriteLine("The topmost element of Stack is : {0}", stack[top]); } internal void PrintStack() { if (top < 0) { Console.WriteLine("Stack Underflow"); return; } else { Console.WriteLine("Items in the Stack are :"); for (int i = top; i >= 0; i--) { Console.WriteLine(stack[i]); } } } } class Program { static void Main(string[] args) { Stack myStack = new Stack(); myStack.Push(10); myStack.Push(20); myStack.Push(30); myStack.Push(40); myStack.PrintStack(); myStack.Peek(); Console.WriteLine("Item popped from Stack : {0}", myStack.Pop()); myStack.PrintStack(); } }} Output: Items in the Stack are : 40 30 20 10 The topmost element of Stack is : 40 Item popped from Stack : 40 Items in the Stack are : 30 20 10 This article is contributed by Ankit Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. CSharp-Generic-Namespace CSharp-Generic-Stack C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Replace() Method C# | Class and Object C# | Constructors Introduction to .NET Framework C# | Data Types HashSet in C# with Examples
[ { "code": null, "e": 25745, "s": 25717, "text": "\n30 Oct, 2018" }, { "code": null, "e": 25901, "s": 25745, "text": "Stack is a linear data structure. It follows LIFO(Last In First Out) pattern for Input/output. Following three basic operations are performed in the stack:" }, { "code": null, "e": 26006, "s": 25901, "text": "Push: Adds an item in the stack. If the stack is full, then it is said to be a stack Overflow condition." }, { "code": null, "e": 26186, "s": 26006, "text": "Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be a stack Underflow condition." }, { "code": null, "e": 26230, "s": 26186, "text": "Peek : Return the topmost element of stack." }, { "code": null, "e": 26289, "s": 26230, "text": "Given below is the C# code to implement Stack using Arrays" }, { "code": "using System; namespace StackImplementation{ internal class Stack { static readonly int MAX = 1000; int top; int[] stack = new int[MAX]; bool IsEmpty() { return (top < 0); } public Stack() { top = -1; } internal bool Push(int data) { if (top >= MAX) { Console.WriteLine(\"Stack Overflow\"); return false; } else { stack[++top] = data; return true; } } internal int Pop() { if (top < 0) { Console.WriteLine(\"Stack Underflow\"); return 0; } else { int value = stack[top--]; return value; } } internal void Peek() { if (top < 0) { Console.WriteLine(\"Stack Underflow\"); return; } else Console.WriteLine(\"The topmost element of Stack is : {0}\", stack[top]); } internal void PrintStack() { if (top < 0) { Console.WriteLine(\"Stack Underflow\"); return; } else { Console.WriteLine(\"Items in the Stack are :\"); for (int i = top; i >= 0; i--) { Console.WriteLine(stack[i]); } } } } class Program { static void Main(string[] args) { Stack myStack = new Stack(); myStack.Push(10); myStack.Push(20); myStack.Push(30); myStack.Push(40); myStack.PrintStack(); myStack.Peek(); Console.WriteLine(\"Item popped from Stack : {0}\", myStack.Pop()); myStack.PrintStack(); } }}", "e": 28275, "s": 26289, "text": null }, { "code": null, "e": 28283, "s": 28275, "text": "Output:" }, { "code": null, "e": 28420, "s": 28283, "text": "Items in the Stack are :\n40\n30\n20\n10\nThe topmost element of Stack is : 40\nItem popped from Stack : 40\nItems in the Stack are :\n30\n20\n10\n" }, { "code": null, "e": 28720, "s": 28420, "text": "This article is contributed by Ankit Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28845, "s": 28720, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28870, "s": 28845, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 28891, "s": 28870, "text": "CSharp-Generic-Stack" }, { "code": null, "e": 28894, "s": 28891, "text": "C#" }, { "code": null, "e": 28992, "s": 28894, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29007, "s": 28992, "text": "C# | Delegates" }, { "code": null, "e": 29029, "s": 29007, "text": "C# | Abstract Classes" }, { "code": null, "e": 29075, "s": 29029, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29098, "s": 29075, "text": "Extension Method in C#" }, { "code": null, "e": 29120, "s": 29098, "text": "C# | Replace() Method" }, { "code": null, "e": 29142, "s": 29120, "text": "C# | Class and Object" }, { "code": null, "e": 29160, "s": 29142, "text": "C# | Constructors" }, { "code": null, "e": 29191, "s": 29160, "text": "Introduction to .NET Framework" }, { "code": null, "e": 29207, "s": 29191, "text": "C# | Data Types" } ]
FLOOR() and CEILING() Function in SQL Server - GeeksforGeeks
29 Sep, 2020 1. FLOOR() Function :The FLOOR() function returns the largest integer value which is less than or equal to a number. Syntax : FLOOR(number) Parameter : Required. A numeric value.number : It is a numeric value.Returns : It returns the integer value. Example-1 :When the argument holds a positive number. SELECT FLOOR(21.53); Output : 21 Example-2 :When the argument holds a negative number. SELECT FLOOR(-21.53); Output : -22 2. CEILING() Function :The CEILING() function returns the smallest integer value which is greater than or equal to a number. Syntax : CEILING(number) Parameter : Required. A numeric value.number : It is a numeric value.Returns : It returns the integer value. Example-1 :When the argument holds a positive number. SELECT CEILING(21.53); Output : 22 Example-2 :When the argument holds a negative number. SELECT CEILING(-21.53); Output : -21 DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Trigger | Student Database SQL Interview Questions CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL | GROUP BY Difference between DELETE, DROP and TRUNCATE SQL | Views MySQL | Group_CONCAT() Function How to Create a Table With Multiple Foreign Keys in SQL? Difference between DELETE and TRUNCATE
[ { "code": null, "e": 25303, "s": 25275, "text": "\n29 Sep, 2020" }, { "code": null, "e": 25420, "s": 25303, "text": "1. FLOOR() Function :The FLOOR() function returns the largest integer value which is less than or equal to a number." }, { "code": null, "e": 25429, "s": 25420, "text": "Syntax :" }, { "code": null, "e": 25443, "s": 25429, "text": "FLOOR(number)" }, { "code": null, "e": 25552, "s": 25443, "text": "Parameter : Required. A numeric value.number : It is a numeric value.Returns : It returns the integer value." }, { "code": null, "e": 25606, "s": 25552, "text": "Example-1 :When the argument holds a positive number." }, { "code": null, "e": 25627, "s": 25606, "text": "SELECT FLOOR(21.53);" }, { "code": null, "e": 25636, "s": 25627, "text": "Output :" }, { "code": null, "e": 25639, "s": 25636, "text": "21" }, { "code": null, "e": 25693, "s": 25639, "text": "Example-2 :When the argument holds a negative number." }, { "code": null, "e": 25715, "s": 25693, "text": "SELECT FLOOR(-21.53);" }, { "code": null, "e": 25724, "s": 25715, "text": "Output :" }, { "code": null, "e": 25728, "s": 25724, "text": "-22" }, { "code": null, "e": 25853, "s": 25728, "text": "2. CEILING() Function :The CEILING() function returns the smallest integer value which is greater than or equal to a number." }, { "code": null, "e": 25862, "s": 25853, "text": "Syntax :" }, { "code": null, "e": 25878, "s": 25862, "text": "CEILING(number)" }, { "code": null, "e": 25987, "s": 25878, "text": "Parameter : Required. A numeric value.number : It is a numeric value.Returns : It returns the integer value." }, { "code": null, "e": 26041, "s": 25987, "text": "Example-1 :When the argument holds a positive number." }, { "code": null, "e": 26064, "s": 26041, "text": "SELECT CEILING(21.53);" }, { "code": null, "e": 26073, "s": 26064, "text": "Output :" }, { "code": null, "e": 26076, "s": 26073, "text": "22" }, { "code": null, "e": 26130, "s": 26076, "text": "Example-2 :When the argument holds a negative number." }, { "code": null, "e": 26154, "s": 26130, "text": "SELECT CEILING(-21.53);" }, { "code": null, "e": 26163, "s": 26154, "text": "Output :" }, { "code": null, "e": 26167, "s": 26163, "text": "-21" }, { "code": null, "e": 26176, "s": 26167, "text": "DBMS-SQL" }, { "code": null, "e": 26187, "s": 26176, "text": "SQL-Server" }, { "code": null, "e": 26191, "s": 26187, "text": "SQL" }, { "code": null, "e": 26195, "s": 26191, "text": "SQL" }, { "code": null, "e": 26293, "s": 26195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26324, "s": 26293, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 26348, "s": 26324, "text": "SQL Interview Questions" }, { "code": null, "e": 26359, "s": 26348, "text": "CTE in SQL" }, { "code": null, "e": 26425, "s": 26359, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26440, "s": 26425, "text": "SQL | GROUP BY" }, { "code": null, "e": 26485, "s": 26440, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 26497, "s": 26485, "text": "SQL | Views" }, { "code": null, "e": 26529, "s": 26497, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 26586, "s": 26529, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" } ]
Deque in C++ Standard Template Library (STL) - GeeksforGeeks
17 Jan, 2022 Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements. Unlike vectors, contiguous storage allocation may not be guaranteed. Double Ended Queues are basically an implementation of the data structure double-ended queue. A queue data structure allows insertion only at the end and deletion from the front. This is like a queue in real life, wherein people are removed from the front and added at the back. Double-ended queues are a special case of queues where insertion and deletion operations are possible at both the ends. The functions for deque are same as vector, with an addition of push and pop operations for both front and back. CPP // CPP Program to implement Deque in STL#include <deque>#include <iostream> using namespace std; void showdq(deque<int> g){ deque<int>::iterator it; for (it = g.begin(); it != g.end(); ++it) cout << '\t' << *it; cout << '\n';} int main(){ deque<int> gquiz; gquiz.push_back(10); gquiz.push_front(20); gquiz.push_back(30); gquiz.push_front(15); cout << "The deque gquiz is : "; showdq(gquiz); cout << "\ngquiz.size() : " << gquiz.size(); cout << "\ngquiz.max_size() : " << gquiz.max_size(); cout << "\ngquiz.at(2) : " << gquiz.at(2); cout << "\ngquiz.front() : " << gquiz.front(); cout << "\ngquiz.back() : " << gquiz.back(); cout << "\ngquiz.pop_front() : "; gquiz.pop_front(); showdq(gquiz); cout << "\ngquiz.pop_back() : "; gquiz.pop_back(); showdq(gquiz); return 0;} The deque gquiz is : 15 20 10 30 gquiz.size() : 4 gquiz.max_size() : 4611686018427387903 gquiz.at(2) : 10 gquiz.front() : 15 gquiz.back() : 30 gquiz.pop_front() : 20 10 30 gquiz.pop_back() : 20 10 Method Definition Recent Articles on Deque Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. dkp1903 akshitsaxenaa09 anshikajain26 cpp-containers-library cpp-deque deque STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Vector in C++ STL Initialize a vector in C++ (6 different ways) Socket Programming in C/C++ std::sort() in C++ STL Bitwise Operators in C/C++ Virtual Function in C++ Iterators in C++ STL Templates in C++ with Examples rand() and srand() in C/C++ unordered_map in C++ STL
[ { "code": null, "e": 26960, "s": 26932, "text": "\n17 Jan, 2022" }, { "code": null, "e": 27233, "s": 26960, "text": "Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements. Unlike vectors, contiguous storage allocation may not be guaranteed. " }, { "code": null, "e": 27632, "s": 27233, "text": "Double Ended Queues are basically an implementation of the data structure double-ended queue. A queue data structure allows insertion only at the end and deletion from the front. This is like a queue in real life, wherein people are removed from the front and added at the back. Double-ended queues are a special case of queues where insertion and deletion operations are possible at both the ends." }, { "code": null, "e": 27747, "s": 27632, "text": "The functions for deque are same as vector, with an addition of push and pop operations for both front and back. " }, { "code": null, "e": 27751, "s": 27747, "text": "CPP" }, { "code": "// CPP Program to implement Deque in STL#include <deque>#include <iostream> using namespace std; void showdq(deque<int> g){ deque<int>::iterator it; for (it = g.begin(); it != g.end(); ++it) cout << '\\t' << *it; cout << '\\n';} int main(){ deque<int> gquiz; gquiz.push_back(10); gquiz.push_front(20); gquiz.push_back(30); gquiz.push_front(15); cout << \"The deque gquiz is : \"; showdq(gquiz); cout << \"\\ngquiz.size() : \" << gquiz.size(); cout << \"\\ngquiz.max_size() : \" << gquiz.max_size(); cout << \"\\ngquiz.at(2) : \" << gquiz.at(2); cout << \"\\ngquiz.front() : \" << gquiz.front(); cout << \"\\ngquiz.back() : \" << gquiz.back(); cout << \"\\ngquiz.pop_front() : \"; gquiz.pop_front(); showdq(gquiz); cout << \"\\ngquiz.pop_back() : \"; gquiz.pop_back(); showdq(gquiz); return 0;}", "e": 28598, "s": 27751, "text": null }, { "code": null, "e": 28827, "s": 28598, "text": "The deque gquiz is : 15 20 10 30\n\ngquiz.size() : 4\ngquiz.max_size() : 4611686018427387903\ngquiz.at(2) : 10\ngquiz.front() : 15\ngquiz.back() : 30\ngquiz.pop_front() : 20 10 30\n\ngquiz.pop_back() : 20 10" }, { "code": null, "e": 28834, "s": 28827, "text": "Method" }, { "code": null, "e": 28845, "s": 28834, "text": "Definition" }, { "code": null, "e": 28870, "s": 28845, "text": "Recent Articles on Deque" }, { "code": null, "e": 28996, "s": 28870, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29004, "s": 28996, "text": "dkp1903" }, { "code": null, "e": 29020, "s": 29004, "text": "akshitsaxenaa09" }, { "code": null, "e": 29034, "s": 29020, "text": "anshikajain26" }, { "code": null, "e": 29057, "s": 29034, "text": "cpp-containers-library" }, { "code": null, "e": 29067, "s": 29057, "text": "cpp-deque" }, { "code": null, "e": 29073, "s": 29067, "text": "deque" }, { "code": null, "e": 29077, "s": 29073, "text": "STL" }, { "code": null, "e": 29081, "s": 29077, "text": "C++" }, { "code": null, "e": 29085, "s": 29081, "text": "STL" }, { "code": null, "e": 29089, "s": 29085, "text": "CPP" }, { "code": null, "e": 29187, "s": 29089, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29196, "s": 29187, "text": "Comments" }, { "code": null, "e": 29209, "s": 29196, "text": "Old Comments" }, { "code": null, "e": 29227, "s": 29209, "text": "Vector in C++ STL" }, { "code": null, "e": 29273, "s": 29227, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 29301, "s": 29273, "text": "Socket Programming in C/C++" }, { "code": null, "e": 29324, "s": 29301, "text": "std::sort() in C++ STL" }, { "code": null, "e": 29351, "s": 29324, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 29375, "s": 29351, "text": "Virtual Function in C++" }, { "code": null, "e": 29396, "s": 29375, "text": "Iterators in C++ STL" }, { "code": null, "e": 29427, "s": 29396, "text": "Templates in C++ with Examples" }, { "code": null, "e": 29455, "s": 29427, "text": "rand() and srand() in C/C++" } ]
How to edit the CSV file using PowerShell?
To edit the CSV file using PowerShell, you need to use the below commands. We already have the CSV file output.csv, we will import this file first. $csvfile = Import-csv C:\temp\Outfile.csv Below is the output of the CSV file. EMP_Name EMP_ID CITY -------- ------ ---- Charles 2000 New York James 2500 Scotland Charles 3000 Poland We need to update the above file. We will change the CITY of the EMP_ID ‘3000’ to MUMBAI. If we update the CITY name by the EMP_Name, it will update two rows as there two Charles, therefore we will use the EMP_ID token here. $csv |foreach{if($_.Emp_ID -eq "3000"){$_.City = "Mumbai"}} $csv |Export-Csv $outfile EMP_Name EMP_ID CITY -------- ------ ---- Charles 2000 New York James 2500 Scotland Charles 3000 Mumbai
[ { "code": null, "e": 1137, "s": 1062, "text": "To edit the CSV file using PowerShell, you need to use the below commands." }, { "code": null, "e": 1210, "s": 1137, "text": "We already have the CSV file output.csv, we will import this file first." }, { "code": null, "e": 1252, "s": 1210, "text": "$csvfile = Import-csv C:\\temp\\Outfile.csv" }, { "code": null, "e": 1289, "s": 1252, "text": "Below is the output of the CSV file." }, { "code": null, "e": 1439, "s": 1289, "text": "EMP_Name EMP_ID CITY\n-------- ------ ----\nCharles 2000 New York\nJames 2500 Scotland\nCharles 3000 Poland" }, { "code": null, "e": 1664, "s": 1439, "text": "We need to update the above file. We will change the CITY of the EMP_ID ‘3000’ to MUMBAI. If we update the CITY name by the EMP_Name, it will update two rows as there two Charles, therefore we will use the EMP_ID token here." }, { "code": null, "e": 1750, "s": 1664, "text": "$csv |foreach{if($_.Emp_ID -eq \"3000\"){$_.City = \"Mumbai\"}}\n$csv |Export-Csv $outfile" }, { "code": null, "e": 1925, "s": 1750, "text": "EMP_Name EMP_ID CITY\n-------- ------ ----\nCharles 2000 New York\nJames 2500 Scotland\nCharles 3000 Mumbai" } ]
Pandas DataFrame Group by Consecutive Certain Values | by Christopher Tao | Towards Data Science
It is very common that we want to segment a Pandas DataFrame by consecutive values. However, dealing with consecutive values is almost always not easy in any circumstances such as SQL, so does Pandas. Standard SQL provides a bunch of window functions to facilitate this kind of manipulation, but there are not too many window functions handy in Pandas. Fortunately, there are many workarounds in Python and sometimes make it even easier than classic window functions. In this article, I’ll demonstrate how to group Pandas DataFrame by certain values that appear arbitrary times. If the title is sort of confused to you, the following sample data will make it clear. Let’s create the sample DataFrame first. df = pd.DataFrame({ 'item':['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'], 'value':[12, 3, 5, 0, 0, 0, 23, 4, 2, 0, 0, 12, 0]}) In this example, we want to segment the DataFrame for whatever number of consecutive values 0. The red square indicates that three segments are expected to be separated from this original DataFrame. What we are trying to do here is generally two: Filter the DataFrame with rows having value == 0.Separate these rows if they are not consecutive. In other words, there is at least one row with value != 0. Filter the DataFrame with rows having value == 0. Separate these rows if they are not consecutive. In other words, there is at least one row with value != 0. The first step is very easy, but apparently not the second. Let’s have the intuitive steps before coding the solution. Create a “mask” series with all boolean values. True if the value == 0, otherwise False.Filter the DataFrame using the mask series. So, we have all the rows with value == 0.Inverse the mask series, so True become False and vice versa.Perform a cumulative sum on the inversed mask series.The cumulative sum series can be used to group by and achieve what we want. Create a “mask” series with all boolean values. True if the value == 0, otherwise False. Filter the DataFrame using the mask series. So, we have all the rows with value == 0. Inverse the mask series, so True become False and vice versa. Perform a cumulative sum on the inversed mask series. The cumulative sum series can be used to group by and achieve what we want. It is important to clarify that if we cum boolean values in Python, True will be treated as 1, whereas False will be treated as 0. I know, it might still be confusing. Let’s have a look at the following DataFrame which is created for this intuition only, not as part of the solution though. # This is not part of the solution, just for demo purposesdf_tmp = dfdf_tmp['mask'] = maskdf_tmp['inversed_mask'] = ~maskdf_tmp['inversed_mask_cumsum'] = (~mask).cumsum() The green rectangles show the expected groups of rows that we are expected to obtain. So, why do we need to perform a cumsum() on the inversed mask column here? The inversed mask will have True (1) for any non-zero values, and False (0) for any zeros.When we apply cumsum() on this inversed mask column, the result for the consecutive 0 will remain the same, while if it is not 0, the cumulative sum will make the value increased. The inversed mask will have True (1) for any non-zero values, and False (0) for any zeros. When we apply cumsum() on this inversed mask column, the result for the consecutive 0 will remain the same, while if it is not 0, the cumulative sum will make the value increased. After the intuition, you might think this is not easy. However, when you see the solution, you may laugh at how easy it is. df[df['value'] == 0].groupby((df['value'] != 0).cumsum()) Yes, that’s it. We can verify whether the groups are correct or not. for k, v in df[df['value'] == 0].groupby((df['value'] != 0).cumsum()): print(f'[group {k}]') print(v) print('\n') That’s exactly what we expected :) Indeed, I wouldn’t say that Pandas provides many useful window functions. However, Pandas in Python is a typical “programming language” not like SQL. So, it provides a lot more possibilities and sometimes can solve problems in even simpler ways. medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[ { "code": null, "e": 372, "s": 171, "text": "It is very common that we want to segment a Pandas DataFrame by consecutive values. However, dealing with consecutive values is almost always not easy in any circumstances such as SQL, so does Pandas." }, { "code": null, "e": 639, "s": 372, "text": "Standard SQL provides a bunch of window functions to facilitate this kind of manipulation, but there are not too many window functions handy in Pandas. Fortunately, there are many workarounds in Python and sometimes make it even easier than classic window functions." }, { "code": null, "e": 750, "s": 639, "text": "In this article, I’ll demonstrate how to group Pandas DataFrame by certain values that appear arbitrary times." }, { "code": null, "e": 878, "s": 750, "text": "If the title is sort of confused to you, the following sample data will make it clear. Let’s create the sample DataFrame first." }, { "code": null, "e": 1028, "s": 878, "text": "df = pd.DataFrame({ 'item':['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'], 'value':[12, 3, 5, 0, 0, 0, 23, 4, 2, 0, 0, 12, 0]})" }, { "code": null, "e": 1227, "s": 1028, "text": "In this example, we want to segment the DataFrame for whatever number of consecutive values 0. The red square indicates that three segments are expected to be separated from this original DataFrame." }, { "code": null, "e": 1275, "s": 1227, "text": "What we are trying to do here is generally two:" }, { "code": null, "e": 1432, "s": 1275, "text": "Filter the DataFrame with rows having value == 0.Separate these rows if they are not consecutive. In other words, there is at least one row with value != 0." }, { "code": null, "e": 1482, "s": 1432, "text": "Filter the DataFrame with rows having value == 0." }, { "code": null, "e": 1590, "s": 1482, "text": "Separate these rows if they are not consecutive. In other words, there is at least one row with value != 0." }, { "code": null, "e": 1709, "s": 1590, "text": "The first step is very easy, but apparently not the second. Let’s have the intuitive steps before coding the solution." }, { "code": null, "e": 2072, "s": 1709, "text": "Create a “mask” series with all boolean values. True if the value == 0, otherwise False.Filter the DataFrame using the mask series. So, we have all the rows with value == 0.Inverse the mask series, so True become False and vice versa.Perform a cumulative sum on the inversed mask series.The cumulative sum series can be used to group by and achieve what we want." }, { "code": null, "e": 2161, "s": 2072, "text": "Create a “mask” series with all boolean values. True if the value == 0, otherwise False." }, { "code": null, "e": 2247, "s": 2161, "text": "Filter the DataFrame using the mask series. So, we have all the rows with value == 0." }, { "code": null, "e": 2309, "s": 2247, "text": "Inverse the mask series, so True become False and vice versa." }, { "code": null, "e": 2363, "s": 2309, "text": "Perform a cumulative sum on the inversed mask series." }, { "code": null, "e": 2439, "s": 2363, "text": "The cumulative sum series can be used to group by and achieve what we want." }, { "code": null, "e": 2570, "s": 2439, "text": "It is important to clarify that if we cum boolean values in Python, True will be treated as 1, whereas False will be treated as 0." }, { "code": null, "e": 2730, "s": 2570, "text": "I know, it might still be confusing. Let’s have a look at the following DataFrame which is created for this intuition only, not as part of the solution though." }, { "code": null, "e": 2901, "s": 2730, "text": "# This is not part of the solution, just for demo purposesdf_tmp = dfdf_tmp['mask'] = maskdf_tmp['inversed_mask'] = ~maskdf_tmp['inversed_mask_cumsum'] = (~mask).cumsum()" }, { "code": null, "e": 2987, "s": 2901, "text": "The green rectangles show the expected groups of rows that we are expected to obtain." }, { "code": null, "e": 3062, "s": 2987, "text": "So, why do we need to perform a cumsum() on the inversed mask column here?" }, { "code": null, "e": 3332, "s": 3062, "text": "The inversed mask will have True (1) for any non-zero values, and False (0) for any zeros.When we apply cumsum() on this inversed mask column, the result for the consecutive 0 will remain the same, while if it is not 0, the cumulative sum will make the value increased." }, { "code": null, "e": 3423, "s": 3332, "text": "The inversed mask will have True (1) for any non-zero values, and False (0) for any zeros." }, { "code": null, "e": 3603, "s": 3423, "text": "When we apply cumsum() on this inversed mask column, the result for the consecutive 0 will remain the same, while if it is not 0, the cumulative sum will make the value increased." }, { "code": null, "e": 3727, "s": 3603, "text": "After the intuition, you might think this is not easy. However, when you see the solution, you may laugh at how easy it is." }, { "code": null, "e": 3785, "s": 3727, "text": "df[df['value'] == 0].groupby((df['value'] != 0).cumsum())" }, { "code": null, "e": 3801, "s": 3785, "text": "Yes, that’s it." }, { "code": null, "e": 3854, "s": 3801, "text": "We can verify whether the groups are correct or not." }, { "code": null, "e": 3977, "s": 3854, "text": "for k, v in df[df['value'] == 0].groupby((df['value'] != 0).cumsum()): print(f'[group {k}]') print(v) print('\\n')" }, { "code": null, "e": 4012, "s": 3977, "text": "That’s exactly what we expected :)" }, { "code": null, "e": 4258, "s": 4012, "text": "Indeed, I wouldn’t say that Pandas provides many useful window functions. However, Pandas in Python is a typical “programming language” not like SQL. So, it provides a lot more possibilities and sometimes can solve problems in even simpler ways." }, { "code": null, "e": 4269, "s": 4258, "text": "medium.com" } ]
Python | Numpy np.hypergeometric() method - GeeksforGeeks
18 Oct, 2019 With the help of np.hypergeometric() method, we can get the hypergeometric distribution in the form of an array by using np.hypergeometric() method. Syntax : np.hypergeometric(ngood, nbad, samples, size)Return : Return an array of hypergeometric distribution. Example #1 :In this example we can see that by using np.hypergeometric() method, we are able to get the hypergeometric distribution in the form of an array. # import numpyimport numpy as np # using np.hypergeometric() methodgfg = np.random.hypergeometric(50, 5, 5, 20) print(gfg) Output : array([4, 5, 5, 5, 4, 5, 5, 5, 4, 5, 4, 5, 4, 4, 5, 5, 3, 5, 4, 5]) Example #2 : # import numpyimport numpy as np # using np.hypergeometric() methodgfg = np.random.hypergeometric(150, 50, 50, 20) print(gfg) Output : [37 35 40 33 43 37 38 38 36 41 42 32 36 35 36 38 35 35 36 35] Python numpy-arrayManipulation Python-numpy 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 ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n18 Oct, 2019" }, { "code": null, "e": 24441, "s": 24292, "text": "With the help of np.hypergeometric() method, we can get the hypergeometric distribution in the form of an array by using np.hypergeometric() method." }, { "code": null, "e": 24552, "s": 24441, "text": "Syntax : np.hypergeometric(ngood, nbad, samples, size)Return : Return an array of hypergeometric distribution." }, { "code": null, "e": 24709, "s": 24552, "text": "Example #1 :In this example we can see that by using np.hypergeometric() method, we are able to get the hypergeometric distribution in the form of an array." }, { "code": "# import numpyimport numpy as np # using np.hypergeometric() methodgfg = np.random.hypergeometric(50, 5, 5, 20) print(gfg)", "e": 24834, "s": 24709, "text": null }, { "code": null, "e": 24843, "s": 24834, "text": "Output :" }, { "code": null, "e": 24911, "s": 24843, "text": "array([4, 5, 5, 5, 4, 5, 5, 5, 4, 5, 4, 5, 4, 4, 5, 5, 3, 5, 4, 5])" }, { "code": null, "e": 24924, "s": 24911, "text": "Example #2 :" }, { "code": "# import numpyimport numpy as np # using np.hypergeometric() methodgfg = np.random.hypergeometric(150, 50, 50, 20) print(gfg)", "e": 25052, "s": 24924, "text": null }, { "code": null, "e": 25061, "s": 25052, "text": "Output :" }, { "code": null, "e": 25123, "s": 25061, "text": "[37 35 40 33 43 37 38 38 36 41 42 32 36 35 36 38 35 35 36 35]" }, { "code": null, "e": 25154, "s": 25123, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 25167, "s": 25154, "text": "Python-numpy" }, { "code": null, "e": 25174, "s": 25167, "text": "Python" }, { "code": null, "e": 25272, "s": 25174, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25281, "s": 25272, "text": "Comments" }, { "code": null, "e": 25294, "s": 25281, "text": "Old Comments" }, { "code": null, "e": 25326, "s": 25294, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25381, "s": 25326, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25437, "s": 25381, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25479, "s": 25437, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25521, "s": 25479, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25560, "s": 25521, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25582, "s": 25560, "text": "Defaultdict in Python" }, { "code": null, "e": 25603, "s": 25582, "text": "Python OOPs Concepts" }, { "code": null, "e": 25634, "s": 25603, "text": "Python | os.path.join() method" } ]
Challenge Handshake Authentication Protocol (CHAP) - GeeksforGeeks
23 Aug, 2021 Challenge Handshake Authentication Protocol (CHAP) is a Point-to-point protocol (PPP) authentication protocol developed by IETF (Internet Engineering Task Force). It is used at the initial startup of the link. Also, it performs periodic checkups to check if the router is still communicating with the same host. Features : It uses 3-way handshaking protocol (not like TCP). First, the authenticator sends a challenge packet to the peer then, the peer responds with a value using its one way hash function. The authenticator then matches the received value with its own calculated hash value. If the values match then the authentication is acknowledged otherwise, the connection will be terminated. It uses one-way hash function called MD5. It also authenticates periodically to check if the communication is taking place with the same device or not. Also, it provides more security than PAP (Password Authentication Procedure) as the value used (find out by hash function) is changed variably. CHAP requires to know the plaintext of the secret as it is never sent over the network. CHAP packets : There are 4 types of CHAP packets – Challenge packet : It is a packet sent, by the authenticator to peer, at the starting of the CHAP 3-way Handshake. Challenge packet is also sent periodically to check if the connection is not altered. It contains Identifier value, value field which contains random value and also contains name field which contains name of the authenticator. The name field is used for password look up. The name field is also fed to MD5 hash generator and a one-way hash value is generated.Response Packet : It is used to response to the challenge packet. It contains the Value field which contains one-way hash value generated, identifier value and the name field. The Name field of the Response packet is set to the hostname of the peer router. Now, the Name field of Challenge packet is looked up for the password. The router looks up for an entry that matches the username in the Name field of the Challenge packet and gets the password. Then, this password is hashed by feeding it to MD5 hash generator and one way hash value is generated. This value is inserted into the value field of response packet and sent to the authenticator.Success packet : Now, the authenticator also performs the same thing by looking up in name field (if it has an entry for that username) of the response packet and by using that it generates a hash value. If the value generated is same as that of peer then the success packet is send.Failure packet : If the generated value is different then the failure packet is send to the peer. Challenge packet : It is a packet sent, by the authenticator to peer, at the starting of the CHAP 3-way Handshake. Challenge packet is also sent periodically to check if the connection is not altered. It contains Identifier value, value field which contains random value and also contains name field which contains name of the authenticator. The name field is used for password look up. The name field is also fed to MD5 hash generator and a one-way hash value is generated. Response Packet : It is used to response to the challenge packet. It contains the Value field which contains one-way hash value generated, identifier value and the name field. The Name field of the Response packet is set to the hostname of the peer router. Now, the Name field of Challenge packet is looked up for the password. The router looks up for an entry that matches the username in the Name field of the Challenge packet and gets the password. Then, this password is hashed by feeding it to MD5 hash generator and one way hash value is generated. This value is inserted into the value field of response packet and sent to the authenticator. Success packet : Now, the authenticator also performs the same thing by looking up in name field (if it has an entry for that username) of the response packet and by using that it generates a hash value. If the value generated is same as that of peer then the success packet is send. Failure packet : If the generated value is different then the failure packet is send to the peer. Configuration : There is a small topology with 2-routers, namely Router1 and Router2. Router1 having IP address 10.1.1.1/30 on s0/0 and Router2 have IP address 10.1.1.2/30 on s0/0. Remember, by default HDLC is configured on Cisco routers therefore, first change the encapsulation to PPP. Configure R1 : Router1(config)# int s0/0 Router1(config-if)# encapsulation ppp Configure R2 : Router2(config)# int s0/0 Router2(config-if)# encapsulation ppp Change hostname of both routers. Router1(config)# hostname R1 Router2(config)# hostname R2 Provide username and password one by one. R1(config)# username R2 password GeeksforGeeks R2(config)# username R1 password GeeksforGeeks Notice that username and password are case-sensitive. Also, on router R1, we have to give username of other router i.e R2 and vice-versa. adnanirshad158 Computer Networks-Network Layer Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP TCP Server-Client implementation in C Differences between IPv4 and IPv6 Socket Programming in Python Types of Network Topology TCP 3-Way Handshake Process Types of Transmission Media UDP Server-Client implementation in C User Datagram Protocol (UDP) Hamming Code in Computer Network
[ { "code": null, "e": 25699, "s": 25671, "text": "\n23 Aug, 2021" }, { "code": null, "e": 26012, "s": 25699, "text": "Challenge Handshake Authentication Protocol (CHAP) is a Point-to-point protocol (PPP) authentication protocol developed by IETF (Internet Engineering Task Force). It is used at the initial startup of the link. Also, it performs periodic checkups to check if the router is still communicating with the same host. " }, { "code": null, "e": 26025, "s": 26012, "text": "Features : " }, { "code": null, "e": 26400, "s": 26025, "text": "It uses 3-way handshaking protocol (not like TCP). First, the authenticator sends a challenge packet to the peer then, the peer responds with a value using its one way hash function. The authenticator then matches the received value with its own calculated hash value. If the values match then the authentication is acknowledged otherwise, the connection will be terminated." }, { "code": null, "e": 26442, "s": 26400, "text": "It uses one-way hash function called MD5." }, { "code": null, "e": 26552, "s": 26442, "text": "It also authenticates periodically to check if the communication is taking place with the same device or not." }, { "code": null, "e": 26696, "s": 26552, "text": "Also, it provides more security than PAP (Password Authentication Procedure) as the value used (find out by hash function) is changed variably." }, { "code": null, "e": 26784, "s": 26696, "text": "CHAP requires to know the plaintext of the secret as it is never sent over the network." }, { "code": null, "e": 26836, "s": 26784, "text": "CHAP packets : There are 4 types of CHAP packets – " }, { "code": null, "e": 28339, "s": 26836, "text": "Challenge packet : It is a packet sent, by the authenticator to peer, at the starting of the CHAP 3-way Handshake. Challenge packet is also sent periodically to check if the connection is not altered. It contains Identifier value, value field which contains random value and also contains name field which contains name of the authenticator. The name field is used for password look up. The name field is also fed to MD5 hash generator and a one-way hash value is generated.Response Packet : It is used to response to the challenge packet. It contains the Value field which contains one-way hash value generated, identifier value and the name field. The Name field of the Response packet is set to the hostname of the peer router. Now, the Name field of Challenge packet is looked up for the password. The router looks up for an entry that matches the username in the Name field of the Challenge packet and gets the password. Then, this password is hashed by feeding it to MD5 hash generator and one way hash value is generated. This value is inserted into the value field of response packet and sent to the authenticator.Success packet : Now, the authenticator also performs the same thing by looking up in name field (if it has an entry for that username) of the response packet and by using that it generates a hash value. If the value generated is same as that of peer then the success packet is send.Failure packet : If the generated value is different then the failure packet is send to the peer." }, { "code": null, "e": 28814, "s": 28339, "text": "Challenge packet : It is a packet sent, by the authenticator to peer, at the starting of the CHAP 3-way Handshake. Challenge packet is also sent periodically to check if the connection is not altered. It contains Identifier value, value field which contains random value and also contains name field which contains name of the authenticator. The name field is used for password look up. The name field is also fed to MD5 hash generator and a one-way hash value is generated." }, { "code": null, "e": 29463, "s": 28814, "text": "Response Packet : It is used to response to the challenge packet. It contains the Value field which contains one-way hash value generated, identifier value and the name field. The Name field of the Response packet is set to the hostname of the peer router. Now, the Name field of Challenge packet is looked up for the password. The router looks up for an entry that matches the username in the Name field of the Challenge packet and gets the password. Then, this password is hashed by feeding it to MD5 hash generator and one way hash value is generated. This value is inserted into the value field of response packet and sent to the authenticator." }, { "code": null, "e": 29747, "s": 29463, "text": "Success packet : Now, the authenticator also performs the same thing by looking up in name field (if it has an entry for that username) of the response packet and by using that it generates a hash value. If the value generated is same as that of peer then the success packet is send." }, { "code": null, "e": 29845, "s": 29747, "text": "Failure packet : If the generated value is different then the failure packet is send to the peer." }, { "code": null, "e": 29863, "s": 29845, "text": "Configuration : " }, { "code": null, "e": 30136, "s": 29863, "text": "There is a small topology with 2-routers, namely Router1 and Router2. Router1 having IP address 10.1.1.1/30 on s0/0 and Router2 have IP address 10.1.1.2/30 on s0/0. Remember, by default HDLC is configured on Cisco routers therefore, first change the encapsulation to PPP. " }, { "code": null, "e": 30153, "s": 30136, "text": "Configure R1 : " }, { "code": null, "e": 30217, "s": 30153, "text": "Router1(config)# int s0/0\nRouter1(config-if)# encapsulation ppp" }, { "code": null, "e": 30234, "s": 30217, "text": "Configure R2 : " }, { "code": null, "e": 30298, "s": 30234, "text": "Router2(config)# int s0/0\nRouter2(config-if)# encapsulation ppp" }, { "code": null, "e": 30333, "s": 30298, "text": "Change hostname of both routers. " }, { "code": null, "e": 30391, "s": 30333, "text": "Router1(config)# hostname R1\nRouter2(config)# hostname R2" }, { "code": null, "e": 30434, "s": 30391, "text": "Provide username and password one by one. " }, { "code": null, "e": 30483, "s": 30434, "text": "R1(config)# username R2 password GeeksforGeeks " }, { "code": null, "e": 30531, "s": 30483, "text": "R2(config)# username R1 password GeeksforGeeks " }, { "code": null, "e": 30669, "s": 30531, "text": "Notice that username and password are case-sensitive. Also, on router R1, we have to give username of other router i.e R2 and vice-versa." }, { "code": null, "e": 30684, "s": 30669, "text": "adnanirshad158" }, { "code": null, "e": 30716, "s": 30684, "text": "Computer Networks-Network Layer" }, { "code": null, "e": 30734, "s": 30716, "text": "Computer Networks" }, { "code": null, "e": 30752, "s": 30734, "text": "Computer Networks" }, { "code": null, "e": 30850, "s": 30752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30882, "s": 30850, "text": "Differences between TCP and UDP" }, { "code": null, "e": 30920, "s": 30882, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 30954, "s": 30920, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 30983, "s": 30954, "text": "Socket Programming in Python" }, { "code": null, "e": 31009, "s": 30983, "text": "Types of Network Topology" }, { "code": null, "e": 31037, "s": 31009, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 31065, "s": 31037, "text": "Types of Transmission Media" }, { "code": null, "e": 31103, "s": 31065, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 31132, "s": 31103, "text": "User Datagram Protocol (UDP)" } ]
Python - Channel Drop using Pillow - GeeksforGeeks
17 May, 2020 A channel drop is a method of removing one of the channels of a multichannel image. By removing means turning the color value of a particular channel to 0 (all pixels), i.e. that particular channel doesn’t have any effect on the final image (assuming colors are blended `normally`). Color theory (Color Wheel) is followed when dropping color channels. Once a channel is removed, the values of other channels are added to create the new image. This method is used extensively in image processing packages such as Adobe Photoshop, Gimp etc. We would be using pillow library for implementing channel drop. To install the library, execute the following command in the command-line: pip install pillow In one of the later methods we would be utilizing elementwise operations offered by the numpy library. To install numpy, execute the following command in the command-line: pip install numpy METHOD 1: In this method we would be using the transform matrix passed as an argument to Image.convert(). The transform matrix is: newRed = 1*oldRed + 0*oldGreen + 0*oldBlue + constant newGreen = 0*oldRed + 1*OldGreen + 0*OldBlue + constant newBlue = 0*oldRed + 0*OldGreen + 1*OldBlue + constant A normal RGB image would have a matrix as shown above. (1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0) In the above matrix, by changing the 1 to 0 would remove that particular channel. For our purpose we don’t have to change values at other offsets, as they lead to different effects which isn’t required. SAMPLE IMAGE: CODE: from PIL import Image # Creating a image object, of the sample imageimg = Image.open(r'sample.jpg') # A 12-value tuple which is a transform matrix for dropping # green channel (in this case)matrix = ( 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0) # Transforming the image to RGB using the aforementioned matrix img = img.convert("RGB", matrix) # Displaying the image img.show() OUTPUT IMAGE: EXPLANATION: Firstly, we created the image object by opening the image using Image.open() and then saving the returned object in variable img. Then we populated our transform matrix (matrix variable) with values, that would lead to Green channel being removed from the image. Since, the green channel is removed (null’d) from the imagethe final image would have pixel values dependent on red and blue channel of the image (giving shades of magenta, as red+blue = magenta). Then we sent the transform matrix to the convert() method and saved the returned image. In the end, we displayed the image using img.show(). The same effect could be applied on multiple channels, by changing several 1’s to 0’s. Examples: The same code but with the matrix: matrix = ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0) would produce the image Which is an image in which the red and green channels are dropped (as their positional values are 0). Due to which the resultant image is blue in color. The same code with the matrix: matrix = ( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0) would produce the image Which is the original image as all the positional values are 1, therefore all the color channels are preserved. METHOD 2: In this method, we would use elementiwise multiplication operation (broadcasting in our case) offered by the numpy library, to negate a color channel of the image. CODE: from PIL import Imageimport numpy as np # Opening the test image and saving its objectimg = Image.open(r'sample.jpg') # Creating an array out of pixel values of the imageimg_arr = np.array(img, np.uint8) # Setting the value of every pixel in the 3rd channel to 0# Change the 2 to 1 if wanting to drop the green channel # Change the 2 to 0 if wanting to drop the red channelimg_arr[::, ::, 2] = 0 # Creating an image from the modified arrayimg = Image.fromarray(img_arr) # Displaying the imageimg.show() OUTPUT IMAGE: EXPLANATION: Firstly, we obtained an image object for our sample image, and stored it in the variable img. Then we converted the image to an numpy array using the function np.array() with the datatype np.uint8 (8 bit unsigned integer). After which we assigned 0 as value of every pixel in the Blue channel, using the img_arr[::, ::, 2] = 0 which means give every row and column of the 3’rd channel (blue) of this multichannel matrix a value of 0. Then we used this array to create a new image using Image.fromarray(). In the end, we displayed the image. NOTE:The reason why 2 at the third argument is treated as blue channel (3rd channel) is because numpy uses 0 based indexing, due to which the first element is at index 0 rather then 1 consequently making the element at index 2 the third element. Image-Processing Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25741, "s": 25713, "text": "\n17 May, 2020" }, { "code": null, "e": 26280, "s": 25741, "text": "A channel drop is a method of removing one of the channels of a multichannel image. By removing means turning the color value of a particular channel to 0 (all pixels), i.e. that particular channel doesn’t have any effect on the final image (assuming colors are blended `normally`). Color theory (Color Wheel) is followed when dropping color channels. Once a channel is removed, the values of other channels are added to create the new image. This method is used extensively in image processing packages such as Adobe Photoshop, Gimp etc." }, { "code": null, "e": 26419, "s": 26280, "text": "We would be using pillow library for implementing channel drop. To install the library, execute the following command in the command-line:" }, { "code": null, "e": 26439, "s": 26419, "text": "pip install pillow\n" }, { "code": null, "e": 26611, "s": 26439, "text": "In one of the later methods we would be utilizing elementwise operations offered by the numpy library. To install numpy, execute the following command in the command-line:" }, { "code": null, "e": 26630, "s": 26611, "text": "pip install numpy\n" }, { "code": null, "e": 26640, "s": 26630, "text": "METHOD 1:" }, { "code": null, "e": 26761, "s": 26640, "text": "In this method we would be using the transform matrix passed as an argument to Image.convert(). The transform matrix is:" }, { "code": null, "e": 26945, "s": 26761, "text": "newRed = 1*oldRed + 0*oldGreen + 0*oldBlue + constant\nnewGreen = 0*oldRed + 1*OldGreen + 0*OldBlue + constant\nnewBlue = 0*oldRed + 0*OldGreen + 1*OldBlue + constant\n" }, { "code": null, "e": 27000, "s": 26945, "text": "A normal RGB image would have a matrix as shown above." }, { "code": null, "e": 27040, "s": 27000, "text": "(1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0)\n" }, { "code": null, "e": 27243, "s": 27040, "text": "In the above matrix, by changing the 1 to 0 would remove that particular channel. For our purpose we don’t have to change values at other offsets, as they lead to different effects which isn’t required." }, { "code": null, "e": 27257, "s": 27243, "text": "SAMPLE IMAGE:" }, { "code": null, "e": 27263, "s": 27257, "text": "CODE:" }, { "code": "from PIL import Image # Creating a image object, of the sample imageimg = Image.open(r'sample.jpg') # A 12-value tuple which is a transform matrix for dropping # green channel (in this case)matrix = ( 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0) # Transforming the image to RGB using the aforementioned matrix img = img.convert(\"RGB\", matrix) # Displaying the image img.show()", "e": 27655, "s": 27263, "text": null }, { "code": null, "e": 27669, "s": 27655, "text": "OUTPUT IMAGE:" }, { "code": null, "e": 27682, "s": 27669, "text": "EXPLANATION:" }, { "code": null, "e": 28283, "s": 27682, "text": "Firstly, we created the image object by opening the image using Image.open() and then saving the returned object in variable img. Then we populated our transform matrix (matrix variable) with values, that would lead to Green channel being removed from the image. Since, the green channel is removed (null’d) from the imagethe final image would have pixel values dependent on red and blue channel of the image (giving shades of magenta, as red+blue = magenta). Then we sent the transform matrix to the convert() method and saved the returned image. In the end, we displayed the image using img.show()." }, { "code": null, "e": 28370, "s": 28283, "text": "The same effect could be applied on multiple channels, by changing several 1’s to 0’s." }, { "code": null, "e": 28380, "s": 28370, "text": "Examples:" }, { "code": null, "e": 28415, "s": 28380, "text": "The same code but with the matrix:" }, { "code": null, "e": 28485, "s": 28415, "text": "matrix = ( 0, 0, 0, 0,\n 0, 0, 0, 0,\n 0, 0, 1, 0)\n" }, { "code": null, "e": 28509, "s": 28485, "text": "would produce the image" }, { "code": null, "e": 28662, "s": 28509, "text": "Which is an image in which the red and green channels are dropped (as their positional values are 0). Due to which the resultant image is blue in color." }, { "code": null, "e": 28693, "s": 28662, "text": "The same code with the matrix:" }, { "code": null, "e": 28763, "s": 28693, "text": "matrix = ( 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0)\n" }, { "code": null, "e": 28787, "s": 28763, "text": "would produce the image" }, { "code": null, "e": 28899, "s": 28787, "text": "Which is the original image as all the positional values are 1, therefore all the color channels are preserved." }, { "code": null, "e": 28909, "s": 28899, "text": "METHOD 2:" }, { "code": null, "e": 29073, "s": 28909, "text": "In this method, we would use elementiwise multiplication operation (broadcasting in our case) offered by the numpy library, to negate a color channel of the image." }, { "code": null, "e": 29079, "s": 29073, "text": "CODE:" }, { "code": "from PIL import Imageimport numpy as np # Opening the test image and saving its objectimg = Image.open(r'sample.jpg') # Creating an array out of pixel values of the imageimg_arr = np.array(img, np.uint8) # Setting the value of every pixel in the 3rd channel to 0# Change the 2 to 1 if wanting to drop the green channel # Change the 2 to 0 if wanting to drop the red channelimg_arr[::, ::, 2] = 0 # Creating an image from the modified arrayimg = Image.fromarray(img_arr) # Displaying the imageimg.show()", "e": 29587, "s": 29079, "text": null }, { "code": null, "e": 29601, "s": 29587, "text": "OUTPUT IMAGE:" }, { "code": null, "e": 29614, "s": 29601, "text": "EXPLANATION:" }, { "code": null, "e": 30155, "s": 29614, "text": "Firstly, we obtained an image object for our sample image, and stored it in the variable img. Then we converted the image to an numpy array using the function np.array() with the datatype np.uint8 (8 bit unsigned integer). After which we assigned 0 as value of every pixel in the Blue channel, using the img_arr[::, ::, 2] = 0 which means give every row and column of the 3’rd channel (blue) of this multichannel matrix a value of 0. Then we used this array to create a new image using Image.fromarray(). In the end, we displayed the image." }, { "code": null, "e": 30401, "s": 30155, "text": "NOTE:The reason why 2 at the third argument is treated as blue channel (3rd channel) is because numpy uses 0 based indexing, due to which the first element is at index 0 rather then 1 consequently making the element at index 2 the third element." }, { "code": null, "e": 30418, "s": 30401, "text": "Image-Processing" }, { "code": null, "e": 30429, "s": 30418, "text": "Python-pil" }, { "code": null, "e": 30436, "s": 30429, "text": "Python" }, { "code": null, "e": 30534, "s": 30436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30552, "s": 30534, "text": "Python Dictionary" }, { "code": null, "e": 30587, "s": 30552, "text": "Read a file line by line in Python" }, { "code": null, "e": 30619, "s": 30587, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30641, "s": 30619, "text": "Enumerate() in Python" }, { "code": null, "e": 30683, "s": 30641, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30713, "s": 30683, "text": "Iterate over a list in Python" }, { "code": null, "e": 30739, "s": 30713, "text": "Python String | replace()" }, { "code": null, "e": 30783, "s": 30739, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30812, "s": 30783, "text": "*args and **kwargs in Python" } ]
How to change spinner text size and text color in Android App using Kotlin?
This example demonstrates how to change spinner text size and text color in Android App using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context=".MainActivity"> <Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.widget.ArrayAdapter import android.widget.Spinner import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var spinner: Spinner override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" spinner = findViewById(R.id.spinner) val superHero = arrayOf<String?>("Batman", "SuperMan", "Flash", "AquaMan", "Shazam") val arrayAdapter: ArrayAdapter<Any?> = ArrayAdapter<Any?>(this, R.layout.spinner_list, superHero) arrayAdapter.setDropDownViewResource(R.layout.spinner_list) spinner.adapter = arrayAdapter } } Step 4 − Create a layout resource file and add the following code in spinner_list.xml <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:textColor="@android:color/holo_red_light" android:textSize="16sp" android:textStyle="bold|italic" /> Step 5 − Add the following code to androidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
[ { "code": null, "e": 1164, "s": 1062, "text": "This example demonstrates how to change spinner text size and text color in Android App using Kotlin." }, { "code": null, "e": 1293, "s": 1164, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1358, "s": 1293, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1773, "s": 1358, "text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\"> \n <Spinner\n android:id=\"@+id/spinner\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</RelativeLayout>" }, { "code": null, "e": 1828, "s": 1773, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 2561, "s": 1828, "text": "import android.os.Bundle\nimport android.widget.ArrayAdapter\nimport android.widget.Spinner\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var spinner: Spinner\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n spinner = findViewById(R.id.spinner)\n val superHero = arrayOf<String?>(\"Batman\", \"SuperMan\", \"Flash\", \"AquaMan\", \"Shazam\")\n val arrayAdapter: ArrayAdapter<Any?> = ArrayAdapter<Any?>(this, R.layout.spinner_list, superHero)\n arrayAdapter.setDropDownViewResource(R.layout.spinner_list)\n spinner.adapter = arrayAdapter\n }\n}" }, { "code": null, "e": 2647, "s": 2561, "text": "Step 4 − Create a layout resource file and add the following code in spinner_list.xml" }, { "code": null, "e": 2978, "s": 2647, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<TextView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:padding=\"10dp\"\n android:textColor=\"@android:color/holo_red_light\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold|italic\" />" }, { "code": null, "e": 3033, "s": 2978, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3661, "s": 3033, "text": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4010, "s": 3661, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." } ]
Number of operations required to make all array elements Equal in Python
We have given an array of elements, and we have to make them all equal by incrementing the elements by 1. We are allowed to increment n - 1 element at each step. Our goal is to calculate the total number of operations required to make all the array elements equal. For example, if you take the list [1, 2, 3], it took three operations to make all the elements equal. One solution to the problem is. Find the most significant number at each step and increment the rest of the elements by 1. Let's write the code. Live Demo def main(): # intializing the array arr = [1, 2, 3] # initializing operations count to 0 no_of_operations = 0 flag = 0 # performing the operations on array to make them equal while not are_equal(arr): flag = 1 # finding the maximum from the list maximum = max(arr) # incrementing all the elements except maximum for i in range(len(arr)): if arr[i] != maximum: arr[i] += 1 # incrementing the operations count by 1 no_of_operations += 1 print(no_of_operations) if flag == 0 else print(no_of_operations + 1) # checking whether all the elements are equal or not def are_equal(arr): global no_of_operations for i in range(len(arr) - 1): if arr[i] != arr[i + 1]: return False return True if __name__ == '__main__': main() If you run the above program, you will get the following results. 3 The above method takes more time to compute for large arrays. We can find the number of operations by finding the sum and the smallest element of the array. Find the sum of the array. Find the smallest of all elements in the array. Print the value get from the expression sum - (length - smallest). See the code below. Live Demo # initializing an array arr = [1, 2, 3] # length length = len(arr) # sum of element fo the array elements_sum = sum(arr) # smallest among all the elements smallest = min(arr) # calculating the number of operations print(elements_sum - (length * smallest)) If you run the above code, you will get the following results. 3 The second method that we discussed is easier and takes less time compared to the first method. If you have any doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1327, "s": 1062, "text": "We have given an array of elements, and we have to make them all equal by incrementing the elements by 1. We are allowed to increment n - 1 element at each step. Our goal is to calculate the total number of operations required to make all the array elements equal." }, { "code": null, "e": 1574, "s": 1327, "text": "For example, if you take the list [1, 2, 3], it took three operations to make all the elements equal. One solution to the problem is. Find the most significant number at each step and increment the rest of the elements by 1. Let's write the code." }, { "code": null, "e": 1585, "s": 1574, "text": " Live Demo" }, { "code": null, "e": 2415, "s": 1585, "text": "def main():\n # intializing the array\n arr = [1, 2, 3]\n # initializing operations count to 0\n no_of_operations = 0\n flag = 0\n # performing the operations on array to make them equal\n while not are_equal(arr):\n flag = 1\n # finding the maximum from the list\n maximum = max(arr)\n # incrementing all the elements except maximum\n for i in range(len(arr)):\n if arr[i] != maximum:\n arr[i] += 1\n # incrementing the operations count by 1\n no_of_operations += 1\n print(no_of_operations) if flag == 0 else print(no_of_operations + 1)\n# checking whether all the elements are equal or not\ndef are_equal(arr):\n global no_of_operations\n for i in range(len(arr) - 1):\n if arr[i] != arr[i + 1]:\n return False\n return True\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 2481, "s": 2415, "text": "If you run the above program, you will get the following results." }, { "code": null, "e": 2483, "s": 2481, "text": "3" }, { "code": null, "e": 2640, "s": 2483, "text": "The above method takes more time to compute for large arrays. We can find the number of operations by finding the sum and the smallest element of the array." }, { "code": null, "e": 2667, "s": 2640, "text": "Find the sum of the array." }, { "code": null, "e": 2715, "s": 2667, "text": "Find the smallest of all elements in the array." }, { "code": null, "e": 2782, "s": 2715, "text": "Print the value get from the expression sum - (length - smallest)." }, { "code": null, "e": 2802, "s": 2782, "text": "See the code below." }, { "code": null, "e": 2813, "s": 2802, "text": " Live Demo" }, { "code": null, "e": 3069, "s": 2813, "text": "# initializing an array\narr = [1, 2, 3]\n# length\nlength = len(arr)\n# sum of element fo the array\nelements_sum = sum(arr)\n# smallest among all the elements\nsmallest = min(arr)\n# calculating the number of operations\nprint(elements_sum - (length * smallest))" }, { "code": null, "e": 3132, "s": 3069, "text": "If you run the above code, you will get the following results." }, { "code": null, "e": 3134, "s": 3132, "text": "3" }, { "code": null, "e": 3307, "s": 3134, "text": "The second method that we discussed is easier and takes less time compared to the first method. If you have any doubts in the tutorial, mention them in the comment section." } ]
Python - Maxwell Distribution in Statistics - GeeksforGeeks
31 Dec, 2019 scipy.stats.maxwell() is a Maxwell (Pareto of the second kind) continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’). Results : Maxwell continuous random variable Code #1 : Creating Maxwell continuous random variable # importing library from scipy.stats import maxwell numargs = maxwell.numargs a, b = 4.32, 3.18rv = maxwell(a, b) print ("RV : \n", rv) Output : RV : scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D66DEC88 Code #2 : Maxwell continuous variates and probability distribution import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = maxwell.rvs(a, b) print ("Random Variates : \n", R) # PDF R = maxwell.pdf(a, b, quantile) print ("\nProbability Distribution : \n", R) Output : Random Variates : 8.999401872992793 Probability Distribution : [0.00000000e+00 3.70579394e-21 4.46576264e-05 4.02803131e-02 3.15216150e-01 6.42768234e-01 7.96800760e-01 7.98281605e-01 7.24720266e-01 6.27826999e-01] Code #3 : Graphical Representation. import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) Output : Distribution : [0. 0.06122449 0.12244898 0.18367347 0.24489796 0.30612245 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449 0.67346939 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633 1.10204082 1.16326531 1.2244898 1.28571429 1.34693878 1.40816327 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714 2.20408163 2.26530612 2.32653061 2.3877551 2.44897959 2.51020408 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102 2.93877551 3. ] Code #4 : Varying Positional Arguments import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = maxwell .pdf(x, 1, 3) y2 = maxwell .pdf(x, 1, 4) plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists *args and **kwargs in Python sum() function in Python How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 24272, "s": 24244, "text": "\n31 Dec, 2019" }, { "code": null, "e": 24531, "s": 24272, "text": "scipy.stats.maxwell() is a Maxwell (Pareto of the second kind) continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution." }, { "code": null, "e": 24544, "s": 24531, "text": "Parameters :" }, { "code": null, "e": 24890, "s": 24544, "text": "q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)." }, { "code": null, "e": 24935, "s": 24890, "text": "Results : Maxwell continuous random variable" }, { "code": null, "e": 24989, "s": 24935, "text": "Code #1 : Creating Maxwell continuous random variable" }, { "code": "# importing library from scipy.stats import maxwell numargs = maxwell.numargs a, b = 4.32, 3.18rv = maxwell(a, b) print (\"RV : \\n\", rv) ", "e": 25137, "s": 24989, "text": null }, { "code": null, "e": 25146, "s": 25137, "text": "Output :" }, { "code": null, "e": 25227, "s": 25146, "text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D66DEC88\n" }, { "code": null, "e": 25294, "s": 25227, "text": "Code #2 : Maxwell continuous variates and probability distribution" }, { "code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = maxwell.rvs(a, b) print (\"Random Variates : \\n\", R) # PDF R = maxwell.pdf(a, b, quantile) print (\"\\nProbability Distribution : \\n\", R) ", "e": 25511, "s": 25294, "text": null }, { "code": null, "e": 25520, "s": 25511, "text": "Output :" }, { "code": null, "e": 25744, "s": 25520, "text": "Random Variates : \n 8.999401872992793\n\nProbability Distribution : \n [0.00000000e+00 3.70579394e-21 4.46576264e-05 4.02803131e-02\n 3.15216150e-01 6.42768234e-01 7.96800760e-01 7.98281605e-01\n 7.24720266e-01 6.27826999e-01]\n\n" }, { "code": null, "e": 25780, "s": 25744, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) ", "e": 25991, "s": 25780, "text": null }, { "code": null, "e": 26000, "s": 25991, "text": "Output :" }, { "code": null, "e": 26578, "s": 26000, "text": "Distribution : \n [0. 0.06122449 0.12244898 0.18367347 0.24489796 0.30612245\n 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449 0.67346939\n 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633\n 1.10204082 1.16326531 1.2244898 1.28571429 1.34693878 1.40816327\n 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102\n 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714\n 2.20408163 2.26530612 2.32653061 2.3877551 2.44897959 2.51020408\n 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102\n 2.93877551 3. ]\n " }, { "code": null, "e": 26617, "s": 26578, "text": "Code #4 : Varying Positional Arguments" }, { "code": "import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = maxwell .pdf(x, 1, 3) y2 = maxwell .pdf(x, 1, 4) plt.plot(x, y1, \"*\", x, y2, \"r--\") ", "e": 26826, "s": 26617, "text": null }, { "code": null, "e": 26835, "s": 26826, "text": "Output :" }, { "code": null, "e": 26864, "s": 26835, "text": "Python scipy-stats-functions" }, { "code": null, "e": 26871, "s": 26864, "text": "Python" }, { "code": null, "e": 26969, "s": 26871, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26978, "s": 26969, "text": "Comments" }, { "code": null, "e": 26991, "s": 26978, "text": "Old Comments" }, { "code": null, "e": 27013, "s": 26991, "text": "Enumerate() in Python" }, { "code": null, "e": 27045, "s": 27013, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27087, "s": 27045, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27113, "s": 27087, "text": "Python String | replace()" }, { "code": null, "e": 27150, "s": 27113, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27179, "s": 27150, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27204, "s": 27179, "text": "sum() function in Python" }, { "code": null, "e": 27260, "s": 27204, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27315, "s": 27260, "text": "Selecting rows in pandas DataFrame based on conditions" } ]
Instruction type MOV M, r in 8085 Microprocessor
In 8085 Instruction set, this instruction MOV M, r will copy 8-bit value from the register r to the memory location as pointed by HL register pair.This instruction uses register addressing for specifying the data. As “r” can have any one of the seven values − r = A, B, C, D, E, H, or L Thus there are seven opcodes for this type of instruction. It occupies only 1-Byte in memory. MOV M, E is an example instruction of this type. It is a 1-Byte instruction. Let us suppose, E is having the initial value ABH, HL register pair is pointing to the memory location 4050H, 4050H memory location’s content is CDH. Then after execution of the instruction MOV M, E, E register’s content will be CDH. The result of execution of this instruction is shown with this example is shown below − (E) (HL) (4050H) Here is the timing diagram of the instruction MOV M, E as below. Summary − So this instruction MOV M, E requires 1-Byte, 2-Machine Cycles (Opcode Fetch, Memory Read) and 7 T-States for execution as shown in the timing diagram.
[ { "code": null, "e": 1276, "s": 1062, "text": "In 8085 Instruction set, this instruction MOV M, r will copy 8-bit value from the register r to the memory location as pointed by HL register pair.This instruction uses register addressing for specifying the data." }, { "code": null, "e": 1322, "s": 1276, "text": "As “r” can have any one of the seven values −" }, { "code": null, "e": 1350, "s": 1322, "text": "r = A, B, C, D, E, H, or L\n" }, { "code": null, "e": 1444, "s": 1350, "text": "Thus there are seven opcodes for this type of instruction. It occupies only 1-Byte in memory." }, { "code": null, "e": 1843, "s": 1444, "text": "MOV M, E is an example instruction of this type. It is a 1-Byte instruction. Let us suppose, E is having the initial value ABH, HL register pair is pointing to the memory location 4050H, 4050H memory location’s content is CDH. Then after execution of the instruction MOV M, E, E register’s content will be CDH. The result of execution of this instruction is shown with this example is shown below −" }, { "code": null, "e": 1847, "s": 1843, "text": "(E)" }, { "code": null, "e": 1852, "s": 1847, "text": "(HL)" }, { "code": null, "e": 1860, "s": 1852, "text": "(4050H)" }, { "code": null, "e": 1925, "s": 1860, "text": "Here is the timing diagram of the instruction MOV M, E as below." }, { "code": null, "e": 2087, "s": 1925, "text": "Summary − So this instruction MOV M, E requires 1-Byte, 2-Machine Cycles (Opcode Fetch, Memory Read) and 7 T-States for execution as shown in the timing diagram." } ]
Program to convert a Vector to List in Java
Let’s say the following is our vector with values − Vector<String> v = new Vector<String>(); v.add("20"); v.add("40"); v.add("60"); v.add("80"); v.add("100"); Now, convert the above Vector to List − List<String>myList = new ArrayList<String>(v); Following is the program to convert a Vector to List in Java − import java.util.*; public class Demo { public static void main(String[] args) { Vector<String> v = new Vector<String>(); v.add("20"); v.add("40"); v.add("60"); v.add("80"); v.add("100"); v.add("120"); v.add("140"); v.add("160"); v.add("200"); System.out.println("Vector elements = " + v); List<String>myList = new ArrayList<String>(v); System.out.println("List (Vector to List) = " + myList); } } Vector elements = [20, 40, 60, 80, 100, 120, 140, 160, 200] List (Vector to List) = [20, 40, 60, 80, 100, 120, 140, 160, 200] Let us see another example − import java.util.*; public class Demo { public static void main(String[] args) { Vector<String> v = new Vector<String>(); v.add("20"); v.add("40"); v.add("60"); v.add("80"); v.add("100"); v.add("120"); v.add("140"); v.add("160"); v.add("200"); System.out.println("Vector elements = " + v); List<String>myList = Collections.list(v.elements()); System.out.println("List (Vector to List) = " + myList); } } Vector elements = [20, 40, 60, 80, 100, 120, 140, 160, 200] List (Vector to List) = [20, 40, 60, 80, 100, 120, 140, 160, 200]
[ { "code": null, "e": 1114, "s": 1062, "text": "Let’s say the following is our vector with values −" }, { "code": null, "e": 1221, "s": 1114, "text": "Vector<String> v = new Vector<String>();\nv.add(\"20\");\nv.add(\"40\");\nv.add(\"60\");\nv.add(\"80\");\nv.add(\"100\");" }, { "code": null, "e": 1261, "s": 1221, "text": "Now, convert the above Vector to List −" }, { "code": null, "e": 1308, "s": 1261, "text": "List<String>myList = new ArrayList<String>(v);" }, { "code": null, "e": 1371, "s": 1308, "text": "Following is the program to convert a Vector to List in Java −" }, { "code": null, "e": 1853, "s": 1371, "text": "import java.util.*;\npublic class Demo {\n public static void main(String[] args) {\n Vector<String> v = new Vector<String>();\n v.add(\"20\");\n v.add(\"40\");\n v.add(\"60\");\n v.add(\"80\");\n v.add(\"100\");\n v.add(\"120\");\n v.add(\"140\");\n v.add(\"160\");\n v.add(\"200\");\n System.out.println(\"Vector elements = \" + v);\n List<String>myList = new ArrayList<String>(v);\n System.out.println(\"List (Vector to List) = \" + myList);\n }\n}" }, { "code": null, "e": 1979, "s": 1853, "text": "Vector elements = [20, 40, 60, 80, 100, 120, 140, 160, 200]\nList (Vector to List) = [20, 40, 60, 80, 100, 120, 140, 160, 200]" }, { "code": null, "e": 2008, "s": 1979, "text": "Let us see another example −" }, { "code": null, "e": 2496, "s": 2008, "text": "import java.util.*;\npublic class Demo {\n public static void main(String[] args) {\n Vector<String> v = new Vector<String>();\n v.add(\"20\");\n v.add(\"40\");\n v.add(\"60\");\n v.add(\"80\");\n v.add(\"100\");\n v.add(\"120\");\n v.add(\"140\");\n v.add(\"160\");\n v.add(\"200\");\n System.out.println(\"Vector elements = \" + v);\n List<String>myList = Collections.list(v.elements());\n System.out.println(\"List (Vector to List) = \" + myList);\n }\n}" }, { "code": null, "e": 2622, "s": 2496, "text": "Vector elements = [20, 40, 60, 80, 100, 120, 140, 160, 200]\nList (Vector to List) = [20, 40, 60, 80, 100, 120, 140, 160, 200]" } ]
How to read a file from assets on android?
This example demonstrates how do I read a file from assets 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"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:padding="12sp" android:textStyle="bold"/> <Button android:id="@+id/btnReadText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Read text from assets" android:layout_centerHorizontal="true" android:layout_marginTop="20sp" android:textStyle="bold"> </Button> </RelativeLayout> Step 3 – Right click app >> New >> Folder >> Assets folder. Right click on the assets folder, select New >> file (myText.txt) and your text. “Darkness cannot drive out darkness: only light can do that. Hate cannot drive out hate: only love can do that.” Step 4 − Add the following code to src/MainActivity.java package app.com.sample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.io.IOException; import java.io.InputStream; public class MainActivity extends AppCompatActivity{ TextView textView; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); button = findViewById(R.id.btnReadText); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String string = ""; try { InputStream inputStream = getAssets().open("myText.txt"); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); string = new String(buffer); } catch (IOException e) { e.printStackTrace(); } textView.setText(string); } }); } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <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": 1133, "s": 1062, "text": "This example demonstrates how do I read a file from assets in android." }, { "code": null, "e": 1262, "s": 1133, "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": 1327, "s": 1262, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2161, "s": 1327, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:padding=\"12sp\"\n android:textStyle=\"bold\"/>\n <Button\n android:id=\"@+id/btnReadText\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Read text from assets\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"20sp\"\n android:textStyle=\"bold\">\n </Button>\n</RelativeLayout>" }, { "code": null, "e": 2302, "s": 2161, "text": "Step 3 – Right click app >> New >> Folder >> Assets folder. Right click on the assets folder, select New >> file (myText.txt) and your text." }, { "code": null, "e": 2415, "s": 2302, "text": "“Darkness cannot drive out darkness: only light can do that. Hate cannot drive out hate: only love can do that.”" }, { "code": null, "e": 2472, "s": 2415, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3637, "s": 2472, "text": "package app.com.sample;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport java.io.IOException;\nimport java.io.InputStream;\npublic class MainActivity extends AppCompatActivity{\n TextView textView;\n Button button;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n button = findViewById(R.id.btnReadText);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String string = \"\";\n try {\n InputStream inputStream = getAssets().open(\"myText.txt\");\n int size = inputStream.available();\n byte[] buffer = new byte[size];\n inputStream.read(buffer);\n string = new String(buffer);\n } catch (IOException e) {\n e.printStackTrace();\n }\n textView.setText(string);\n }\n });\n }\n}" }, { "code": null, "e": 3692, "s": 3637, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4362, "s": 3692, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\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": 4709, "s": 4362, "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": 4750, "s": 4709, "text": "Click here to download the project code." } ]
How to make MySQL table primary key auto increment?
To make MySQL table primary key auto increment, use the below syntax CREATE TABLE yourTableName ( yourColumnName INT(6) ZEROFILL NOT NULL AUTO_INCREMENT, PRIMARY KEY(yourColumnName) ); Let us first create a table and set primary key auto increment − mysql> CREATE TABLE DemoTable ( UserId INT(6) ZEROFILL NOT NULL AUTO_INCREMENT, PRIMARY KEY(UserId) ); Query OK, 0 rows affected (0.81 sec) Insert some records in the table using insert command − mysql> INSERT INTO DemoTable values(); Query OK, 1 row affected (0.12 sec) mysql> INSERT INTO DemoTable values(); Query OK, 1 row affected (0.13 sec) mysql> INSERT INTO DemoTable values(); Query OK, 1 row affected (0.10 sec) mysql> INSERT INTO DemoTable values(); Query OK, 1 row affected (0.44 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +--------+ | UserId | +--------+ | 000001 | | 000002 | | 000003 | | 000004 | +--------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1131, "s": 1062, "text": "To make MySQL table primary key auto increment, use the below syntax" }, { "code": null, "e": 1259, "s": 1131, "text": "CREATE TABLE yourTableName\n (\n yourColumnName INT(6) ZEROFILL NOT NULL AUTO_INCREMENT,\n PRIMARY KEY(yourColumnName)\n );" }, { "code": null, "e": 1324, "s": 1259, "text": "Let us first create a table and set primary key auto increment −" }, { "code": null, "e": 1476, "s": 1324, "text": "mysql> CREATE TABLE DemoTable\n (\n UserId INT(6) ZEROFILL NOT NULL AUTO_INCREMENT,\n PRIMARY KEY(UserId)\n );\nQuery OK, 0 rows affected (0.81 sec)" }, { "code": null, "e": 1532, "s": 1476, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1835, "s": 1532, "text": "mysql> INSERT INTO DemoTable values();\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> INSERT INTO DemoTable values();\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> INSERT INTO DemoTable values();\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> INSERT INTO DemoTable values();\nQuery OK, 1 row affected (0.44 sec)" }, { "code": null, "e": 1895, "s": 1835, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1926, "s": 1895, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1967, "s": 1926, "text": "This will produce the following output −" }, { "code": null, "e": 2080, "s": 1967, "text": "+--------+\n| UserId |\n+--------+\n| 000001 |\n| 000002 |\n| 000003 |\n| 000004 |\n+--------+\n4 rows in set (0.00 sec)" } ]
\rlap - Tex Command
\rlap - Used for right overlap. { \rlap #1 } \rlap command is used for right overlap. It creates a box of width zero; the argument is then placed just to the right of this zero-width box and hence will overlap whatever lies to the right. a\mathrel{\rlap{\;/}{=}}b a/=b a\mathrel{\rlap{\;/}{=}}b a/=b a\mathrel{\rlap{\;/}{=}}b 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8018, "s": 7986, "text": "\\rlap - Used for right overlap." }, { "code": null, "e": 8031, "s": 8018, "text": "{ \\rlap #1 }" }, { "code": null, "e": 8224, "s": 8031, "text": "\\rlap command is used for right overlap. It creates a box of width zero; the argument is then placed just to the right of this zero-width box and hence will overlap whatever lies to the right." }, { "code": null, "e": 8260, "s": 8224, "text": "\na\\mathrel{\\rlap{\\;/}{=}}b\n\na/=b\n\n\n" }, { "code": null, "e": 8294, "s": 8260, "text": "a\\mathrel{\\rlap{\\;/}{=}}b\n\na/=b\n\n" }, { "code": null, "e": 8320, "s": 8294, "text": "a\\mathrel{\\rlap{\\;/}{=}}b" }, { "code": null, "e": 8352, "s": 8320, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8365, "s": 8352, "text": " Ashraf Said" }, { "code": null, "e": 8398, "s": 8365, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8411, "s": 8398, "text": " Ashraf Said" }, { "code": null, "e": 8443, "s": 8411, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8479, "s": 8443, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8514, "s": 8479, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8531, "s": 8514, "text": " Mohammad Nauman" }, { "code": null, "e": 8564, "s": 8531, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8578, "s": 8564, "text": " Daniel Stern" }, { "code": null, "e": 8610, "s": 8578, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8625, "s": 8610, "text": " Nishant Kumar" }, { "code": null, "e": 8632, "s": 8625, "text": " Print" }, { "code": null, "e": 8643, "s": 8632, "text": " Add Notes" } ]
How to call a stored procedure that accepts input parameters, using JDBC program?
A. Stored procedures are sub routines, segment of SQL statements which are stored in SQL catalog. All the applications that can access Relational databases (Java, Python, PHP etc.), can access stored procedures. Stored procedures contain IN and OUT parameters or both. They may return result sets in case you use SELECT statements. Stored procedures can return multiple result sets. You can call a stored procedure using the following syntax: CALL procedure_name (input_parameter1, input_parameter2, input_parameter3) JDBC provides a standard stored procedure SQL escape syntax using which you can procedures in all RDBMSs To call a stored procedure using a JDBC program you need to: Register the driver: class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter. Register the driver: class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter. Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it. Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it. Create Statement: Create a CallableStatement object using the prepareCall() method of the Connection interface. Create Statement: Create a CallableStatement object using the prepareCall() method of the Connection interface. Execute the Query: Execute the query using the execute() method of the Statement interface. Execute the Query: Execute the query using the execute() method of the Statement interface. Assume we have a table named customers in the database with the following contents: +----+-----------+-----+---------+----------------+ | ID | NAME | AGE | SALARY | ADDRESS | +----+-----------+-----+---------+----------------+ | 1 | Amit | 25 | 3000.00 | Hyderabad | | 2 | Kalyan | 27 | 4000.00 | Vishakhapatnam | | 3 | Renuka | 30 | 5000.00 | Delhi | | 4 | Archana | 24 | 1500.00 | Delhi | | 5 | Koushik | 30 | 9000.00 | Delhi | | 6 | Hardik | 45 | 6400.00 | Delhi | +----+-----------+-----+---------+----------------+ We have created a stored procedure named insertData in the database as shown below: mysql> DELIMITER //; mysql> Create procedure insertData( IN c_id INT, IN c_name VARCHAR(255), IN c_age INT, IN c_sal INT, IN c_add VARCHAR(255)) BEGIN INSERT INTO CUSTOMERS VALUES (c_id, c_name, c_age, c_sal, c_add); END// mysql> DELIMITER ; Query OK, 0 rows affected (0.00 sec) This procedure accepts id (integer), name (String), age (integer), salary (integer) and, address (String) as IN parameters and inserts a new record in the customers table. Following JDBC program establishes connection with MySQL database, inserts 6 records in the customers table using the procedure named insertData. import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class CallngStoredProcedureExample_IN { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Preparing a CallableStatement to call a procedure CallableStatement cstmt = con.prepareCall("{call insertData(?, ?, ?, ?, ?)}"); //Setting values for the IN parameters of the procedure cstmt.setInt(1, 7); cstmt.setString(2, "Trupthi"); cstmt.setInt(3, 33); cstmt.setInt(4, 4360); cstmt.setString(5, "Ahmedabad"); cstmt.execute(); cstmt.setInt(1, 8); cstmt.setString(2, "Mithili"); cstmt.setInt(3, 26); cstmt.setInt(4, 4100); cstmt.setString(5, "Vijayawada"); cstmt.execute(); cstmt.setInt(1, 9); cstmt.setString(2, "Maneesh"); cstmt.setInt(3, 39); cstmt.setInt(4, 4000); cstmt.setString(5, "Hyderabad"); cstmt.execute(); cstmt.setInt(1, 10); cstmt.setString(2, "Rajaneesh"); cstmt.setInt(3, 30); cstmt.setInt(4, 6400); cstmt.setString(5, "Delhi"); cstmt.execute(); cstmt.setInt(1, 11); cstmt.setString(2, "Komal"); cstmt.setInt(3, 29); cstmt.setInt(4, 8000); cstmt.setString(5, "Ahmedabad"); cstmt.execute(); cstmt.setInt(1, 12); cstmt.setString(2, "Manyata"); cstmt.setInt(3, 25); cstmt.setInt(4, 5000); cstmt.setString(5, "Vijayawada"); cstmt.execute(); System.out.println("Procedure called by passing required values......"); } } Connection established...... Procedure called by passing required values...... If you retrieve the contents of the customers table using the select command, you can observe the newly added records as: mysql> select * from customers; +----+-----------+-----+---------+----------------+ | ID | NAME | AGE | SALARY | ADDRESS | +----+-----------+-----+---------+----------------+ | 1 | Amit | 25 | 3000.00 | Hyderabad | | 2 | Kalyan | 27 | 4000.00 | Vishakhapatnam | | 3 | Renuka | 30 | 5000.00 | Delhi | | 4 | Archana | 24 | 1500.00 | Delhi | | 5 | Koushik | 30 | 9000.00 | Delhi | | 6 | Hardik | 45 | 6400.00 | Delhi | | 7 | Trupthi | 33 | 4360.00 | Ahmedabad | | 8 | Mithili | 26 | 4100.00 | Vijayawada | | 9 | Maneesh | 39 | 4000.00 | Hyderabad | | 10 | Rajaneesh | 30 | 6400.00 | Delhi | | 11 | Komal | 29 | 8000.00 | Ahmedabad | | 12 | Manyata | 25 | 5000.00 | Vijayawada | +----+-----------+-----+---------+----------------+ 12 rows in set (0.00 sec)
[ { "code": null, "e": 1274, "s": 1062, "text": "A. Stored procedures are sub routines, segment of SQL statements which are stored in SQL catalog. All the applications that can access Relational databases (Java, Python, PHP etc.), can access stored procedures." }, { "code": null, "e": 1445, "s": 1274, "text": "Stored procedures contain IN and OUT parameters or both. They may return result sets in case you use SELECT statements. Stored procedures can return multiple result sets." }, { "code": null, "e": 1505, "s": 1445, "text": "You can call a stored procedure using the following syntax:" }, { "code": null, "e": 1580, "s": 1505, "text": "CALL procedure_name (input_parameter1, input_parameter2, input_parameter3)" }, { "code": null, "e": 1685, "s": 1580, "text": "JDBC provides a standard stored procedure SQL escape syntax using which you can procedures in all RDBMSs" }, { "code": null, "e": 1746, "s": 1685, "text": "To call a stored procedure using a JDBC program you need to:" }, { "code": null, "e": 1883, "s": 1746, "text": "Register the driver: class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter." }, { "code": null, "e": 2020, "s": 1883, "text": "Register the driver: class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter." }, { "code": null, "e": 2209, "s": 2020, "text": "Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it." }, { "code": null, "e": 2398, "s": 2209, "text": "Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it." }, { "code": null, "e": 2510, "s": 2398, "text": "Create Statement: Create a CallableStatement object using the prepareCall() method of the Connection interface." }, { "code": null, "e": 2622, "s": 2510, "text": "Create Statement: Create a CallableStatement object using the prepareCall() method of the Connection interface." }, { "code": null, "e": 2714, "s": 2622, "text": "Execute the Query: Execute the query using the execute() method of the Statement interface." }, { "code": null, "e": 2806, "s": 2714, "text": "Execute the Query: Execute the query using the execute() method of the Statement interface." }, { "code": null, "e": 2890, "s": 2806, "text": "Assume we have a table named customers in the database with the following contents:" }, { "code": null, "e": 3410, "s": 2890, "text": "+----+-----------+-----+---------+----------------+\n| ID | NAME | AGE | SALARY | ADDRESS |\n+----+-----------+-----+---------+----------------+\n| 1 | Amit | 25 | 3000.00 | Hyderabad |\n| 2 | Kalyan | 27 | 4000.00 | Vishakhapatnam |\n| 3 | Renuka | 30 | 5000.00 | Delhi |\n| 4 | Archana | 24 | 1500.00 | Delhi |\n| 5 | Koushik | 30 | 9000.00 | Delhi |\n| 6 | Hardik | 45 | 6400.00 | Delhi |\n+----+-----------+-----+---------+----------------+" }, { "code": null, "e": 3494, "s": 3410, "text": "We have created a stored procedure named insertData in the database as shown below:" }, { "code": null, "e": 3847, "s": 3494, "text": "mysql> DELIMITER //;\nmysql> Create procedure insertData(\n IN c_id INT,\n IN c_name VARCHAR(255),\n IN c_age INT,\n IN c_sal INT,\n IN c_add VARCHAR(255))\n BEGIN\n INSERT INTO CUSTOMERS VALUES (c_id, c_name, c_age, c_sal, c_add);\n END//\nmysql> DELIMITER ;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 4019, "s": 3847, "text": "This procedure accepts id (integer), name (String), age (integer), salary (integer) and, address (String) as IN parameters and inserts a new record in the customers table." }, { "code": null, "e": 4165, "s": 4019, "text": "Following JDBC program establishes connection with MySQL database, inserts 6 records in the customers table using the procedure named insertData." }, { "code": null, "e": 6107, "s": 4165, "text": "import java.sql.CallableStatement;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\npublic class CallngStoredProcedureExample_IN {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Preparing a CallableStatement to call a procedure\n CallableStatement cstmt = con.prepareCall(\"{call insertData(?, ?, ?, ?, ?)}\");\n //Setting values for the IN parameters of the procedure\n cstmt.setInt(1, 7);\n cstmt.setString(2, \"Trupthi\");\n cstmt.setInt(3, 33);\n cstmt.setInt(4, 4360);\n cstmt.setString(5, \"Ahmedabad\");\n cstmt.execute();\n cstmt.setInt(1, 8);\n cstmt.setString(2, \"Mithili\");\n cstmt.setInt(3, 26);\n cstmt.setInt(4, 4100);\n cstmt.setString(5, \"Vijayawada\");\n cstmt.execute();\n cstmt.setInt(1, 9);\n cstmt.setString(2, \"Maneesh\");\n cstmt.setInt(3, 39);\n cstmt.setInt(4, 4000);\n cstmt.setString(5, \"Hyderabad\");\n cstmt.execute();\n cstmt.setInt(1, 10);\n cstmt.setString(2, \"Rajaneesh\");\n cstmt.setInt(3, 30);\n cstmt.setInt(4, 6400);\n cstmt.setString(5, \"Delhi\");\n cstmt.execute();\n cstmt.setInt(1, 11);\n cstmt.setString(2, \"Komal\");\n cstmt.setInt(3, 29);\n cstmt.setInt(4, 8000);\n cstmt.setString(5, \"Ahmedabad\");\n cstmt.execute();\n cstmt.setInt(1, 12);\n cstmt.setString(2, \"Manyata\");\n cstmt.setInt(3, 25);\n cstmt.setInt(4, 5000);\n cstmt.setString(5, \"Vijayawada\");\n cstmt.execute();\n System.out.println(\"Procedure called by passing required values......\");\n }\n}" }, { "code": null, "e": 6186, "s": 6107, "text": "Connection established......\nProcedure called by passing required values......" }, { "code": null, "e": 6308, "s": 6186, "text": "If you retrieve the contents of the customers table using the select command, you can observe the newly added records as:" }, { "code": null, "e": 7198, "s": 6308, "text": "mysql> select * from customers;\n+----+-----------+-----+---------+----------------+\n| ID | NAME | AGE | SALARY | ADDRESS |\n+----+-----------+-----+---------+----------------+\n| 1 | Amit | 25 | 3000.00 | Hyderabad |\n| 2 | Kalyan | 27 | 4000.00 | Vishakhapatnam |\n| 3 | Renuka | 30 | 5000.00 | Delhi |\n| 4 | Archana | 24 | 1500.00 | Delhi |\n| 5 | Koushik | 30 | 9000.00 | Delhi |\n| 6 | Hardik | 45 | 6400.00 | Delhi |\n| 7 | Trupthi | 33 | 4360.00 | Ahmedabad |\n| 8 | Mithili | 26 | 4100.00 | Vijayawada |\n| 9 | Maneesh | 39 | 4000.00 | Hyderabad |\n| 10 | Rajaneesh | 30 | 6400.00 | Delhi |\n| 11 | Komal | 29 | 8000.00 | Ahmedabad |\n| 12 | Manyata | 25 | 5000.00 | Vijayawada |\n+----+-----------+-----+---------+----------------+\n12 rows in set (0.00 sec)" } ]
Web-Scraping and Pre-Processing for NLP | by James Briggs | Towards Data Science
For Natural Language Processing, clean data is important. Even more so when that data is coming from the web. In this article we will go through a real example of web scraping and data pre-processing for a Stoic philosophy text generator. The data we will be using is Epistulae Morales Ad Lucilium (Moral Letters to Lucilius) written by exiled Roman senator Seneca during the late Stoa. The letters are sourced from WikiSource here. This page consists of a list of all 124 letters. Where each letter is contained in it’s own page. First, we must extract the HTML from this contents page. For this we use Python’s requests and BeautifulSoup libraries. This gives us a BeautifulSoup object, which contains the raw html we have given via html. Let’s take a look what this looks like. In this, we must extract the local paths to each letter. The BeautifulSoup object allows us to extract all <a> elements with soup.find_all('a'). However, this returns all <a> elements, so we then need to filter for just those which link to the letters. We do this using regular expressions, which is incredibly simple, we build our regex to search for anything that begins with Letter followed by one or more spaces \s+ and finally ending with one to three digits \d{1,3}. This gives us re.compile(r"^Letter\s+\d{1,3}$"). By applying this regex to the list of <a> elements provided by BeautifulSoup, we will get the following. Now we need to define a function to parse the HTML from each page. This is actually very straight-forward, as the letter text is all contained in the only <p> elements on the page. So, similar to before, we extract all <p> elements. We then do a small amount of formatting to make the text more readable, before returning the letter text. With our pull_letter function and letters_regex, we can read all letters, which we will place in moral_letters. At this point we have all the data we need, neatly stored in moral_letters. Formatting our data into a NLP friendly format is much simpler to write, albeit much more abstracted. We will need to convert the text we have at the moment into numbers, creating a numeric representation of our data, which we will call data_idx. To do this we will create a char2idx dictionary, which stands for character-to-index. This, as is given away by the name, converts characters 'a', 'b', 'c' to indices 0, 1, 2. Every character in char2idx must also map to a unique index. For this we must create a set of all characters in the data (a set is simply list unique values). This set of characters is known as a vocabulary, which we will define as vocab. So now, let’s read the first letter from Seneca in our new format. Although it seems like nonsense, this is exactly what we want when formatting text data for NLP. Now all that remains is slicing and shuffling our data, then it is ready to be input into a model. In our case we are using tensorflow. TensorFlow allows us to to use tf.data.Dataset, an API we can use to simplify the dataset transformation process. To create a dataset from our Numpy array data_idx, we use tf.data.Dataset.from_tensor_slices. During training, we will only look at one segment of text at once. To split the data into sequences we use the Dataset .batch method. As this is a text generator, our target data will simply consist of the input data, shifted one character forward. For this we will define a function called split_xy. Finally, we create batches of 64 sequences, again using .batch, which are then shuffled using .shuffle. Inside dataset, we have 175 batches (due to len(txt) / (SEQLEN * BATCHSIZE)). Every single batch contains an input and target array, built by the split_xy function. This data is now fully prepared, ready to be input into a model for training. Despite the outward appearance of complexity. The implementation of machine learning is no longer an gargantuan task, reserved for the brightest minds of our time. We are now living in an age where we can teach a computer to reproduce philosophy from some of the greatest minds in human history. Not only can we do it, but it is incredibly easy to do. It is a fascinating time, and one which I hope we all make the most of. Thanks for reading! I’ve written about designing neural networks to reproduce Stoic philosophy before. If you’re interested, you can read about it here: towardsdatascience.com For anyone that is curious, here are my (attempted) Latin translations of the article headers.Epistulae: LettersUnum Epistula Legimus: We read one letterOmnis Epistulae: All lettersPraeparatio: Preparation (eg preparing the data)Simplex Munditiis: Elegance through simplicityQui Conclusioni: Here concludes / the conclusion
[ { "code": null, "e": 410, "s": 171, "text": "For Natural Language Processing, clean data is important. Even more so when that data is coming from the web. In this article we will go through a real example of web scraping and data pre-processing for a Stoic philosophy text generator." }, { "code": null, "e": 558, "s": 410, "text": "The data we will be using is Epistulae Morales Ad Lucilium (Moral Letters to Lucilius) written by exiled Roman senator Seneca during the late Stoa." }, { "code": null, "e": 702, "s": 558, "text": "The letters are sourced from WikiSource here. This page consists of a list of all 124 letters. Where each letter is contained in it’s own page." }, { "code": null, "e": 822, "s": 702, "text": "First, we must extract the HTML from this contents page. For this we use Python’s requests and BeautifulSoup libraries." }, { "code": null, "e": 952, "s": 822, "text": "This gives us a BeautifulSoup object, which contains the raw html we have given via html. Let’s take a look what this looks like." }, { "code": null, "e": 1205, "s": 952, "text": "In this, we must extract the local paths to each letter. The BeautifulSoup object allows us to extract all <a> elements with soup.find_all('a'). However, this returns all <a> elements, so we then need to filter for just those which link to the letters." }, { "code": null, "e": 1474, "s": 1205, "text": "We do this using regular expressions, which is incredibly simple, we build our regex to search for anything that begins with Letter followed by one or more spaces \\s+ and finally ending with one to three digits \\d{1,3}. This gives us re.compile(r\"^Letter\\s+\\d{1,3}$\")." }, { "code": null, "e": 1579, "s": 1474, "text": "By applying this regex to the list of <a> elements provided by BeautifulSoup, we will get the following." }, { "code": null, "e": 1760, "s": 1579, "text": "Now we need to define a function to parse the HTML from each page. This is actually very straight-forward, as the letter text is all contained in the only <p> elements on the page." }, { "code": null, "e": 1918, "s": 1760, "text": "So, similar to before, we extract all <p> elements. We then do a small amount of formatting to make the text more readable, before returning the letter text." }, { "code": null, "e": 2030, "s": 1918, "text": "With our pull_letter function and letters_regex, we can read all letters, which we will place in moral_letters." }, { "code": null, "e": 2106, "s": 2030, "text": "At this point we have all the data we need, neatly stored in moral_letters." }, { "code": null, "e": 2208, "s": 2106, "text": "Formatting our data into a NLP friendly format is much simpler to write, albeit much more abstracted." }, { "code": null, "e": 2353, "s": 2208, "text": "We will need to convert the text we have at the moment into numbers, creating a numeric representation of our data, which we will call data_idx." }, { "code": null, "e": 2529, "s": 2353, "text": "To do this we will create a char2idx dictionary, which stands for character-to-index. This, as is given away by the name, converts characters 'a', 'b', 'c' to indices 0, 1, 2." }, { "code": null, "e": 2768, "s": 2529, "text": "Every character in char2idx must also map to a unique index. For this we must create a set of all characters in the data (a set is simply list unique values). This set of characters is known as a vocabulary, which we will define as vocab." }, { "code": null, "e": 2835, "s": 2768, "text": "So now, let’s read the first letter from Seneca in our new format." }, { "code": null, "e": 2932, "s": 2835, "text": "Although it seems like nonsense, this is exactly what we want when formatting text data for NLP." }, { "code": null, "e": 3068, "s": 2932, "text": "Now all that remains is slicing and shuffling our data, then it is ready to be input into a model. In our case we are using tensorflow." }, { "code": null, "e": 3276, "s": 3068, "text": "TensorFlow allows us to to use tf.data.Dataset, an API we can use to simplify the dataset transformation process. To create a dataset from our Numpy array data_idx, we use tf.data.Dataset.from_tensor_slices." }, { "code": null, "e": 3410, "s": 3276, "text": "During training, we will only look at one segment of text at once. To split the data into sequences we use the Dataset .batch method." }, { "code": null, "e": 3577, "s": 3410, "text": "As this is a text generator, our target data will simply consist of the input data, shifted one character forward. For this we will define a function called split_xy." }, { "code": null, "e": 3681, "s": 3577, "text": "Finally, we create batches of 64 sequences, again using .batch, which are then shuffled using .shuffle." }, { "code": null, "e": 3846, "s": 3681, "text": "Inside dataset, we have 175 batches (due to len(txt) / (SEQLEN * BATCHSIZE)). Every single batch contains an input and target array, built by the split_xy function." }, { "code": null, "e": 3924, "s": 3846, "text": "This data is now fully prepared, ready to be input into a model for training." }, { "code": null, "e": 4088, "s": 3924, "text": "Despite the outward appearance of complexity. The implementation of machine learning is no longer an gargantuan task, reserved for the brightest minds of our time." }, { "code": null, "e": 4276, "s": 4088, "text": "We are now living in an age where we can teach a computer to reproduce philosophy from some of the greatest minds in human history. Not only can we do it, but it is incredibly easy to do." }, { "code": null, "e": 4348, "s": 4276, "text": "It is a fascinating time, and one which I hope we all make the most of." }, { "code": null, "e": 4368, "s": 4348, "text": "Thanks for reading!" }, { "code": null, "e": 4501, "s": 4368, "text": "I’ve written about designing neural networks to reproduce Stoic philosophy before. If you’re interested, you can read about it here:" }, { "code": null, "e": 4524, "s": 4501, "text": "towardsdatascience.com" } ]
How to save the summary statistics into a data frame in R?
When we find the summary statistics of a data frame then the output is returned as a table and each of the column records the minimum, first quartile, median, median, third quartile, and maximum with their names. If we want to save this summary as a data frame then it is better to calculate it with apply function and store it as data.frame. Consider the below data frame − Live Demo x1<-rpois(20,5) x2<-rexp(20,2) x3<-rexp(20,5) x4<-runif(20,5,10) x5<-runif(20,5,12) df1<-data.frame(x1,x2,x3,x4,x5) df1 x1 x2 x3 x4 x5 1 10 0.318955383 0.021788087 6.418559 8.407760 2 2 0.682127794 0.354887266 7.915153 7.691196 3 8 0.093838493 0.750094498 5.825129 5.047835 4 7 0.298823558 0.008525539 5.481506 5.025790 5 7 0.031303249 0.491977567 7.143065 11.964555 6 4 0.125743637 0.165031313 6.778808 5.755208 7 2 0.245636217 0.274977357 9.224668 7.930684 8 4 1.222748429 0.034911250 6.300662 10.025192 9 4 0.447608813 0.122677772 5.115722 10.197774 10 7 0.114562157 0.400451206 9.311998 11.103992 11 4 0.252932058 0.200755263 6.672940 9.255076 12 4 0.164882561 0.085901924 8.158944 10.293423 13 6 0.236620346 0.132488792 7.732131 10.930689 14 7 0.019540590 0.076331686 6.882222 9.289458 15 5 0.002908304 0.008934306 5.929365 10.552569 16 6 0.547663136 0.350376081 7.144703 5.159983 17 2 0.345556123 0.144144203 8.153868 7.918402 18 3 0.306435164 0.053920204 7.604212 11.124177 19 9 1.121258744 0.015824366 8.298107 9.531429 20 6 1.139374780 0.301424552 8.646805 11.471353 Finding the summary of df1 − summary(df1) x1 x2 x3 x4 Min. : 2.00 Min. :0.002908 Min. :0.008526 Min. :5.116 1st Qu.: 4.00 1st Qu.:0.122948 1st Qu.:0.049168 1st Qu.:6.389 Median : 5.50 Median :0.275878 Median :0.138317 Median :7.144 Mean : 5.35 Mean :0.385926 Mean :0.199771 Mean :7.237 3rd Qu.: 7.00 3rd Qu.:0.472622 3rd Qu.:0.313662 3rd Qu.:8.155 Max. :10.00 Max. :1.222748 Max. :0.750094 Max. :9.312 x5 Min. : 5.026 1st Qu.: 7.862 Median : 9.410 Mean : 8.934 3rd Qu.:10.647 Max. :11.965 Finding the summary of df1 and saving it as a data frame in a new object − df1_summary<-as.data.frame(apply(df1,2,summary)) df1_summary x1 x2 x3 x4 x5 Min. 2.00 0.002908304 0.008525539 5.115722 5.025790 1st Qu. 4.00 0.122948267 0.049167965 6.389085 7.861600 Median 5.50 0.275877808 0.138316497 7.143884 9.410443 Mean 5.35 0.385925977 0.199771162 7.236928 8.933827 3rd Qu. 7.00 0.472622394 0.313662434 8.155137 10.647099 Max. 10.00 1.222748429 0.750094498 9.311998 11.964555 is.data.frame(df1_summary) [1] TRUE Let’s have a look at another example − Live Demo y1<-sample(1:100,20) y2<-sample(1:10,20,replace=TRUE) y3<-sample(20:100,20,replace=TRUE) y4<-sample(50:100,20,replace=TRUE) y5<-rpois(20,15) df2<-data.frame(y1,y2,y3,y4,y5) df2 y1 y2 y3 y4 y5 1 23 6 64 52 17 2 90 2 95 93 17 3 45 8 44 95 14 4 8 10 32 86 10 5 79 8 29 63 14 6 36 9 60 77 16 7 67 8 31 55 16 8 39 9 27 58 11 9 33 9 90 82 15 10 38 4 34 95 11 11 99 1 68 68 19 12 28 3 58 86 6 13 81 8 54 83 16 14 87 2 25 50 20 15 53 1 90 77 10 16 10 9 23 79 14 17 41 7 93 53 12 18 97 7 100 75 17 19 1 4 67 60 15 20 80 7 27 54 17 df2_summary<-as.data.frame(apply(df2,2,summary)) df2_summary y1 y2 y3 y4 y5 Min. 1.00 1.00 23.00 50.00 6.00 1st Qu. 31.75 3.75 30.50 57.25 11.75 Median 43.00 7.00 56.00 76.00 15.00 Mean 51.75 6.10 55.55 72.05 14.35 3rd Qu. 80.25 8.25 73.50 83.75 17.00 Max. 99.00 10.00 100.00 95.00 20.00
[ { "code": null, "e": 1405, "s": 1062, "text": "When we find the summary statistics of a data frame then the output is returned as a table and each of the column records the minimum, first quartile, median, median, third quartile, and maximum with their names. If we want to save this summary as a data frame then it is better to calculate it with apply function and store it as data.frame." }, { "code": null, "e": 1437, "s": 1405, "text": "Consider the below data frame −" }, { "code": null, "e": 1448, "s": 1437, "text": " Live Demo" }, { "code": null, "e": 1568, "s": 1448, "text": "x1<-rpois(20,5)\nx2<-rexp(20,2)\nx3<-rexp(20,5)\nx4<-runif(20,5,10)\nx5<-runif(20,5,12)\ndf1<-data.frame(x1,x2,x3,x4,x5)\ndf1" }, { "code": null, "e": 2553, "s": 1568, "text": " x1 x2 x3 x4 x5\n1 10 0.318955383 0.021788087 6.418559 8.407760\n2 2 0.682127794 0.354887266 7.915153 7.691196\n3 8 0.093838493 0.750094498 5.825129 5.047835\n4 7 0.298823558 0.008525539 5.481506 5.025790\n5 7 0.031303249 0.491977567 7.143065 11.964555\n6 4 0.125743637 0.165031313 6.778808 5.755208\n7 2 0.245636217 0.274977357 9.224668 7.930684\n8 4 1.222748429 0.034911250 6.300662 10.025192\n9 4 0.447608813 0.122677772 5.115722 10.197774\n10 7 0.114562157 0.400451206 9.311998 11.103992\n11 4 0.252932058 0.200755263 6.672940 9.255076\n12 4 0.164882561 0.085901924 8.158944 10.293423\n13 6 0.236620346 0.132488792 7.732131 10.930689\n14 7 0.019540590 0.076331686 6.882222 9.289458\n15 5 0.002908304 0.008934306 5.929365 10.552569\n16 6 0.547663136 0.350376081 7.144703 5.159983\n17 2 0.345556123 0.144144203 8.153868 7.918402\n18 3 0.306435164 0.053920204 7.604212 11.124177\n19 9 1.121258744 0.015824366 8.298107 9.531429\n20 6 1.139374780 0.301424552 8.646805 11.471353" }, { "code": null, "e": 2582, "s": 2553, "text": "Finding the summary of df1 −" }, { "code": null, "e": 2595, "s": 2582, "text": "summary(df1)" }, { "code": null, "e": 3132, "s": 2595, "text": " x1 x2 x3 x4\nMin. : 2.00 Min. :0.002908 Min. :0.008526 Min. :5.116\n1st Qu.: 4.00 1st Qu.:0.122948 1st Qu.:0.049168 1st Qu.:6.389\nMedian : 5.50 Median :0.275878 Median :0.138317 Median :7.144\nMean : 5.35 Mean :0.385926 Mean :0.199771 Mean :7.237\n3rd Qu.: 7.00 3rd Qu.:0.472622 3rd Qu.:0.313662 3rd Qu.:8.155\nMax. :10.00 Max. :1.222748 Max. :0.750094 Max. :9.312\n x5\nMin. : 5.026\n1st Qu.: 7.862\nMedian : 9.410\nMean : 8.934\n3rd Qu.:10.647\nMax. :11.965" }, { "code": null, "e": 3207, "s": 3132, "text": "Finding the summary of df1 and saving it as a data frame in a new object −" }, { "code": null, "e": 3268, "s": 3207, "text": "df1_summary<-as.data.frame(apply(df1,2,summary))\ndf1_summary" }, { "code": null, "e": 3736, "s": 3268, "text": " x1 x2 x3 x4 x5\nMin. 2.00 0.002908304 0.008525539 5.115722 5.025790\n1st Qu. 4.00 0.122948267 0.049167965 6.389085 7.861600\nMedian 5.50 0.275877808 0.138316497 7.143884 9.410443\nMean 5.35 0.385925977 0.199771162 7.236928 8.933827\n3rd Qu. 7.00 0.472622394 0.313662434 8.155137 10.647099\nMax. 10.00 1.222748429 0.750094498 9.311998 11.964555" }, { "code": null, "e": 3763, "s": 3736, "text": "is.data.frame(df1_summary)" }, { "code": null, "e": 3772, "s": 3763, "text": "[1] TRUE" }, { "code": null, "e": 3811, "s": 3772, "text": "Let’s have a look at another example −" }, { "code": null, "e": 3822, "s": 3811, "text": " Live Demo" }, { "code": null, "e": 3999, "s": 3822, "text": "y1<-sample(1:100,20)\ny2<-sample(1:10,20,replace=TRUE)\ny3<-sample(20:100,20,replace=TRUE)\ny4<-sample(50:100,20,replace=TRUE)\ny5<-rpois(20,15)\ndf2<-data.frame(y1,y2,y3,y4,y5)\ndf2" }, { "code": null, "e": 4356, "s": 3999, "text": " y1 y2 y3 y4 y5\n1 23 6 64 52 17\n2 90 2 95 93 17\n3 45 8 44 95 14\n4 8 10 32 86 10\n5 79 8 29 63 14\n6 36 9 60 77 16\n7 67 8 31 55 16\n8 39 9 27 58 11\n9 33 9 90 82 15\n10 38 4 34 95 11\n11 99 1 68 68 19\n12 28 3 58 86 6\n13 81 8 54 83 16\n14 87 2 25 50 20\n15 53 1 90 77 10\n16 10 9 23 79 14\n17 41 7 93 53 12\n18 97 7 100 75 17\n19 1 4 67 60 15\n20 80 7 27 54 17" }, { "code": null, "e": 4417, "s": 4356, "text": "df2_summary<-as.data.frame(apply(df2,2,summary))\ndf2_summary" }, { "code": null, "e": 4751, "s": 4417, "text": " y1 y2 y3 y4 y5\nMin. 1.00 1.00 23.00 50.00 6.00\n1st Qu. 31.75 3.75 30.50 57.25 11.75\nMedian 43.00 7.00 56.00 76.00 15.00\nMean 51.75 6.10 55.55 72.05 14.35\n3rd Qu. 80.25 8.25 73.50 83.75 17.00\nMax. 99.00 10.00 100.00 95.00 20.00" } ]
Delete multiple occurrences of key in Linked list using double pointer - GeeksforGeeks
05 Jun, 2018 Given a singly linked list, delete all occurrences of a given key in it. For example, consider the following list. Input: 2 -> 2 -> 4 -> 3 -> 2 Key to delete = 2 Output: 4 -> 3 This is mainly an alternative of this post which deletes multiple occurrences of a given key using separate condition loops for head and remaining nodes. Here we use a double pointer approach to use a single loop irrespective of the position of the element (head, tail or between). The original method to delete a node from a linked list without an extra check for the head was explained by Linus Torvalds in his “25th Anniversary of Linux” TED talk. This article uses that logic to delete multiple recurrences of the key without an extra check for the head. Explanation:1. Store address of head in a double pointer till we find a non “key” node. This takes care of the 1st while loop to handle the special case of the head.2. If a node is not “key” node then store the address of node->next in pp.3. if we find a “key” node later on then change pp (ultimately node->next) to point to current node->next. Following is C++ implementation for the same. // CPP program to delete multiple// occurrences of a key using single// loop.#include <iostream>using namespace std; // A linked list nodestruct Node { int data; struct Node* next;}; struct Node* head = NULL; void printList(struct Node* node){ while (node != NULL) { printf(" %d ", node->data); node = node->next; }} void push(int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (head); (head) = new_node;} void deleteEntry(int key){ // Start from head struct Node** pp = &head; while (*pp) { struct Node* entry = *pp; // If key found, then put // next at the address of pp // delete entry. if (entry->data == key) { *pp = entry->next; delete (entry); } // Else move to next else pp = &(entry->next); }} int main(){ push(2); push(2); push(4); push(3); push(2); int key = 2; // key to delete puts("Created Linked List: "); printList(head); printf("\n"); deleteEntry(key); printf("\nLinked List after Deletion of 2: \n"); printList(head); return 0;} Created Linked List: 2 3 4 2 2 Linked List after Deletion of 2: 3 4 cpp-double-pointer cpp-pointer Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Delete a node in a Doubly Linked List Given a linked list which is sorted, how will you insert in sorted way Insert a node at a specific position in a linked list Circular Linked List | Set 2 (Traversal) Program to implement Singly Linked List in C++ using class Swap nodes in a linked list without swapping data Priority Queue using Linked List Circular Singly Linked List | Insertion Real-time application of Data Structures Insertion Sort for Singly Linked List
[ { "code": null, "e": 24567, "s": 24539, "text": "\n05 Jun, 2018" }, { "code": null, "e": 24682, "s": 24567, "text": "Given a singly linked list, delete all occurrences of a given key in it. For example, consider the following list." }, { "code": null, "e": 24754, "s": 24682, "text": "Input: 2 -> 2 -> 4 -> 3 -> 2\n Key to delete = 2\nOutput: 4 -> 3 \n" }, { "code": null, "e": 25313, "s": 24754, "text": "This is mainly an alternative of this post which deletes multiple occurrences of a given key using separate condition loops for head and remaining nodes. Here we use a double pointer approach to use a single loop irrespective of the position of the element (head, tail or between). The original method to delete a node from a linked list without an extra check for the head was explained by Linus Torvalds in his “25th Anniversary of Linux” TED talk. This article uses that logic to delete multiple recurrences of the key without an extra check for the head." }, { "code": null, "e": 25659, "s": 25313, "text": "Explanation:1. Store address of head in a double pointer till we find a non “key” node. This takes care of the 1st while loop to handle the special case of the head.2. If a node is not “key” node then store the address of node->next in pp.3. if we find a “key” node later on then change pp (ultimately node->next) to point to current node->next." }, { "code": null, "e": 25705, "s": 25659, "text": "Following is C++ implementation for the same." }, { "code": "// CPP program to delete multiple// occurrences of a key using single// loop.#include <iostream>using namespace std; // A linked list nodestruct Node { int data; struct Node* next;}; struct Node* head = NULL; void printList(struct Node* node){ while (node != NULL) { printf(\" %d \", node->data); node = node->next; }} void push(int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (head); (head) = new_node;} void deleteEntry(int key){ // Start from head struct Node** pp = &head; while (*pp) { struct Node* entry = *pp; // If key found, then put // next at the address of pp // delete entry. if (entry->data == key) { *pp = entry->next; delete (entry); } // Else move to next else pp = &(entry->next); }} int main(){ push(2); push(2); push(4); push(3); push(2); int key = 2; // key to delete puts(\"Created Linked List: \"); printList(head); printf(\"\\n\"); deleteEntry(key); printf(\"\\nLinked List after Deletion of 2: \\n\"); printList(head); return 0;}", "e": 26888, "s": 25705, "text": null }, { "code": null, "e": 26968, "s": 26888, "text": "Created Linked List: \n 2 3 4 2 2 \n\nLinked List after Deletion of 2: \n 3 4\n" }, { "code": null, "e": 26987, "s": 26968, "text": "cpp-double-pointer" }, { "code": null, "e": 26999, "s": 26987, "text": "cpp-pointer" }, { "code": null, "e": 27011, "s": 26999, "text": "Linked List" }, { "code": null, "e": 27023, "s": 27011, "text": "Linked List" }, { "code": null, "e": 27121, "s": 27023, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27130, "s": 27121, "text": "Comments" }, { "code": null, "e": 27143, "s": 27130, "text": "Old Comments" }, { "code": null, "e": 27181, "s": 27143, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 27252, "s": 27181, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 27306, "s": 27252, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 27347, "s": 27306, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 27406, "s": 27347, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 27456, "s": 27406, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 27489, "s": 27456, "text": "Priority Queue using Linked List" }, { "code": null, "e": 27529, "s": 27489, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 27570, "s": 27529, "text": "Real-time application of Data Structures" } ]
Read Fixed Width Text File in R
17 Jun, 2021 In this article, we are going to see how to read fixed-width text files in R Programming language. In text files, columns will have fixed widths, specified in characters, which determines the maximum amount of data it can contain. No delimiters are used to separate the fields in the file. Instead, smaller quantities of data are padded with spaces to fill the allotted space, such that the start of a given column can always be specified as an offset from the beginning of a line. There are many methods to read the data in fixed width text file: Using read.fwf( ) function Using readLines( ) function. Using Fortran style format specification. This method is done using read.fwf function from utils package. We have to use column widths for reading. Syntax: read.fwf(file, widths, header = FALSE, sep = “\t”, skip = 0, row.names, col.names, n = -1, buffersize = 2000, fileEncoding = “”, ...) Now, we use read.fwf() for reading the fixed-width text file named “abcd.txt”. R # Creating fileabcd.txt<-tempfile() cat(file=abcd.txt,"Rahul2023","Ravi 2521", "Jaggu2130",sep="\n") # Reading fixed widthread.fwf(abcd.txt, width = c(5, 2, 2), col.names = c("Studentname","Test1", "Test2"))unlink(abcd.txt) Output: Here we take widths in (5,2,2) format as student names are in 4,5 string length and marks are in 2-sized string length. In the above output, we can observe that it reads the “abcd.txt” file and displays in format of 5,2,2 lengths(example: rahul,20,23 from “rahul2023”), with column names as Studentnames,Test1,Test2. Here we are going to use readLines function. readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines. Syntax: readLines(path) Parameter:path: path of the file Code: R abcd.txt<-tempfile() # adding data to the empty tempfilecat(file = abcd.txt, "Rahul2023", "Ravi 2521", "Jaggu2130", sep = "\n") readLines(abcd.txt)unlink(abcd.txt) Output: Here we will use read.fortran() function. It is used to read fixed-format data files using Fortran-style format specifications Syntax: read.fortran(file, format, ..., as.is = TRUE, colClasses = NA) Parameters: file: File or connection to read from. format: Character vector or list of vectors. See ‘Details’ below. as.is: Keep characters as characters? colClasses: Variable classes to override defaults. Here we have created a file named “abcd.txt” for example purpose as shown in the below code. By using read.fortran function, we can read the data in fixed-width text file using fortran style format specifications. R abcd.txt<-tempfile()cat(file = abcd.txt, "Rahul2023", "Ravi 2521", "Jaggu2130", sep = "\n") # format of character length=5, 2 # integers of 2-sized widthread.fortran(abcd.txt,c("A5","2I2")) # format of 5 characters of width=1,4# integers of width-1read.fortran(abcd.txt,c("5A1","4I1")) # using list of formats for each entry # of data for special casesread.fortran(abcd.txt,list(c("A5","2I2"), c("A4","X1","2I2"), c("A5","2I2"))) unlink(abcd.txt) Output: Picked R-FileHandling R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Joining of Dataframes in R Programming Control Statements in R Programming How to import an Excel File into R ? How to change Colors in ggplot2 Line Plot in R ? Normal Distribution in R
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 128, "s": 28, "text": "In this article, we are going to see how to read fixed-width text files in R Programming language. " }, { "code": null, "e": 513, "s": 128, "text": "In text files, columns will have fixed widths, specified in characters, which determines the maximum amount of data it can contain. No delimiters are used to separate the fields in the file. Instead, smaller quantities of data are padded with spaces to fill the allotted space, such that the start of a given column can always be specified as an offset from the beginning of a line." }, { "code": null, "e": 579, "s": 513, "text": "There are many methods to read the data in fixed width text file:" }, { "code": null, "e": 606, "s": 579, "text": "Using read.fwf( ) function" }, { "code": null, "e": 635, "s": 606, "text": "Using readLines( ) function." }, { "code": null, "e": 677, "s": 635, "text": "Using Fortran style format specification." }, { "code": null, "e": 783, "s": 677, "text": "This method is done using read.fwf function from utils package. We have to use column widths for reading." }, { "code": null, "e": 925, "s": 783, "text": "Syntax: read.fwf(file, widths, header = FALSE, sep = “\\t”, skip = 0, row.names, col.names, n = -1, buffersize = 2000, fileEncoding = “”, ...)" }, { "code": null, "e": 1004, "s": 925, "text": "Now, we use read.fwf() for reading the fixed-width text file named “abcd.txt”." }, { "code": null, "e": 1006, "s": 1004, "text": "R" }, { "code": "# Creating fileabcd.txt<-tempfile() cat(file=abcd.txt,\"Rahul2023\",\"Ravi 2521\", \"Jaggu2130\",sep=\"\\n\") # Reading fixed widthread.fwf(abcd.txt, width = c(5, 2, 2), col.names = c(\"Studentname\",\"Test1\", \"Test2\"))unlink(abcd.txt)", "e": 1265, "s": 1006, "text": null }, { "code": null, "e": 1273, "s": 1265, "text": "Output:" }, { "code": null, "e": 1394, "s": 1273, "text": "Here we take widths in (5,2,2) format as student names are in 4,5 string length and marks are in 2-sized string length. " }, { "code": null, "e": 1591, "s": 1394, "text": "In the above output, we can observe that it reads the “abcd.txt” file and displays in format of 5,2,2 lengths(example: rahul,20,23 from “rahul2023”), with column names as Studentnames,Test1,Test2." }, { "code": null, "e": 1849, "s": 1591, "text": "Here we are going to use readLines function. readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines." }, { "code": null, "e": 1873, "s": 1849, "text": "Syntax: readLines(path)" }, { "code": null, "e": 1906, "s": 1873, "text": "Parameter:path: path of the file" }, { "code": null, "e": 1912, "s": 1906, "text": "Code:" }, { "code": null, "e": 1914, "s": 1912, "text": "R" }, { "code": "abcd.txt<-tempfile() # adding data to the empty tempfilecat(file = abcd.txt, \"Rahul2023\", \"Ravi 2521\", \"Jaggu2130\", sep = \"\\n\") readLines(abcd.txt)unlink(abcd.txt)", "e": 2083, "s": 1914, "text": null }, { "code": null, "e": 2091, "s": 2083, "text": "Output:" }, { "code": null, "e": 2218, "s": 2091, "text": "Here we will use read.fortran() function. It is used to read fixed-format data files using Fortran-style format specifications" }, { "code": null, "e": 2289, "s": 2218, "text": "Syntax: read.fortran(file, format, ..., as.is = TRUE, colClasses = NA)" }, { "code": null, "e": 2301, "s": 2289, "text": "Parameters:" }, { "code": null, "e": 2340, "s": 2301, "text": "file: File or connection to read from." }, { "code": null, "e": 2406, "s": 2340, "text": "format: Character vector or list of vectors. See ‘Details’ below." }, { "code": null, "e": 2444, "s": 2406, "text": "as.is: Keep characters as characters?" }, { "code": null, "e": 2495, "s": 2444, "text": "colClasses: Variable classes to override defaults." }, { "code": null, "e": 2709, "s": 2495, "text": "Here we have created a file named “abcd.txt” for example purpose as shown in the below code. By using read.fortran function, we can read the data in fixed-width text file using fortran style format specifications." }, { "code": null, "e": 2711, "s": 2709, "text": "R" }, { "code": "abcd.txt<-tempfile()cat(file = abcd.txt, \"Rahul2023\", \"Ravi 2521\", \"Jaggu2130\", sep = \"\\n\") # format of character length=5, 2 # integers of 2-sized widthread.fortran(abcd.txt,c(\"A5\",\"2I2\")) # format of 5 characters of width=1,4# integers of width-1read.fortran(abcd.txt,c(\"5A1\",\"4I1\")) # using list of formats for each entry # of data for special casesread.fortran(abcd.txt,list(c(\"A5\",\"2I2\"), c(\"A4\",\"X1\",\"2I2\"), c(\"A5\",\"2I2\"))) unlink(abcd.txt)", "e": 3217, "s": 2711, "text": null }, { "code": null, "e": 3225, "s": 3217, "text": "Output:" }, { "code": null, "e": 3232, "s": 3225, "text": "Picked" }, { "code": null, "e": 3247, "s": 3232, "text": "R-FileHandling" }, { "code": null, "e": 3258, "s": 3247, "text": "R Language" }, { "code": null, "e": 3356, "s": 3258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3391, "s": 3356, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3449, "s": 3391, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3498, "s": 3449, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3550, "s": 3498, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3588, "s": 3550, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3627, "s": 3588, "text": "Joining of Dataframes in R Programming" }, { "code": null, "e": 3663, "s": 3627, "text": "Control Statements in R Programming" }, { "code": null, "e": 3700, "s": 3663, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 3749, "s": 3700, "text": "How to change Colors in ggplot2 Line Plot in R ?" } ]
Stooge Sort
14 Jun, 2022 Stooge Sort is a recursive sorting algorithm. It is not much efficient but interesting sorting algorithm. It generally divides the array into two overlapping parts (2/3 each). After that it performs sorting in first 2/3 part and then it performs sorting in last 2/3 part. And then, sorting is done on first 2/3 part to ensure that the array is sorted. The key idea is that sorting the overlapping part twice exchanges the elements between the other two sections accordingly. Approach: Step 1: If value at index 0 is greater than value at last index, swap them.Step 2: Recursively, Stooge sort the initial 2/3rd of the array. Stooge sort the last 2/3rd of the array. Stooge sort the initial 2/3rd again to confirm. NOTE: Always take the ceil of ((2/3)*N) for selecting elements. Illustration: Lets consider an example: arr[] = {2, 4, 5, 3, 1} Step1: Initially, First and last elements are compared and if last is greater than first then they are swapped. Step2: Now, recursively sort initial 2/3rd of the elements as shown below: Step3: Then, recursively sort last 2/3rd of the elements, as shown below: Step4: Again, sort the initial 2/3rd of the elements to confirm final data is sorted.Resulted array: Resulted array: Below is the implementation for the above approach: C++ Java Python3 C# Javascript // C++ code to implement stooge sort#include <iostream>using namespace std; // Function to implement stooge sortvoid stoogesort(int arr[], int l, int h){ if (l >= h) return; // If first element is smaller than last, // swap them if (arr[l] > arr[h]) swap(arr[l], arr[h]); // If there are more than 2 elements in // the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort first 2/3 elements stoogesort(arr, l, h - t); // Recursively sort last 2/3 elements stoogesort(arr, l + t, h); // Recursively sort first 2/3 elements // again to confirm stoogesort(arr, l, h - t); }} // Driver Codeint main(){ int arr[] = { 2, 4, 5, 3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // Calling Stooge Sort function to sort // the array stoogesort(arr, 0, n - 1); // Display the sorted array for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program to implement stooge sortimport java.io.*; public class stooge { // Function to implement stooge sort static void stoogesort(int arr[], int l, int h) { if (l >= h) return; // If first element is smaller // than last, swap them if (arr[l] > arr[h]) { int t = arr[l]; arr[l] = arr[h]; arr[h] = t; } // If there are more than 2 elements in // the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort first 2/3 elements stoogesort(arr, l, h - t); // Recursively sort last 2/3 elements stoogesort(arr, l + t, h); // Recursively sort first 2/3 elements // again to confirm stoogesort(arr, l, h - t); } } // Driver Code public static void main(String args[]) { int arr[] = { 2, 4, 5, 3, 1 }; int n = arr.length; stoogesort(arr, 0, n - 1); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }}// Code Contributed by Mohit Gupta_OMG <(0_o)> # Python program to implement stooge sort def stoogesort(arr, l, h): if l >= h: return # If first element is smaller # than last, swap them if arr[l]>arr[h]: t = arr[l] arr[l] = arr[h] arr[h] = t # If there are more than 2 elements in # the array if h-l + 1 > 2: t = (int)((h-l + 1)/3) # Recursively sort first 2 / 3 elements stoogesort(arr, l, (h-t)) # Recursively sort last 2 / 3 elements stoogesort(arr, l + t, (h)) # Recursively sort first 2 / 3 elements # again to confirm stoogesort(arr, l, (h-t)) # deriver arr = [2, 4, 5, 3, 1]n = len(arr) stoogesort(arr, 0, n-1) for i in range(0, n): print(arr[i], end = ' ') # Code Contributed by Mohit Gupta_OMG <(0_o)> // C# program to implement stooge sortusing System; class GFG { // Function to implement stooge sort static void stoogesort(int[] arr, int l, int h) { if (l >= h) return; // If first element is smaller // than last, swap them if (arr[l] > arr[h]) { int t = arr[l]; arr[l] = arr[h]; arr[h] = t; } // If there are more than 2 // elements in the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort first // 2/3 elements stoogesort(arr, l, h - t); // Recursively sort last // 2/3 elements stoogesort(arr, l + t, h); // Recursively sort first // 2/3 elements again to // confirm stoogesort(arr, l, h - t); } } // Driver Code public static void Main() { int[] arr = { 2, 4, 5, 3, 1 }; int n = arr.Length; // Calling Stooge Sort function // to sort the array stoogesort(arr, 0, n - 1); // Display the sorted array for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by Sam007. <script> // Javascript program to implement stooge sort // Function to implement stooge sort function stoogesort(arr, l, h) { if (l >= h) return; // If first element is smaller // than last, swap them if (arr[l] > arr[h]) { let t = arr[l]; arr[l] = arr[h]; arr[h] = t; } // If there are more than 2 // elements in the array if (h - l + 1 > 2) { let t = parseInt((h - l + 1) / 3, 10); // Recursively sort first // 2/3 elements stoogesort(arr, l, h - t); // Recursively sort last // 2/3 elements stoogesort(arr, l + t, h); // Recursively sort first // 2/3 elements again to // confirm stoogesort(arr, l, h - t); } } let arr = [ 2, 4, 5, 3, 1 ]; let n = arr.length; // Calling Stooge Sort function // to sort the array stoogesort(arr, 0, n - 1); // Display the sorted array for (let i = 0; i < n; i++) document.write(arr[i] + " "); </script> 1 2 3 4 5 The running time complexity of stooge sort can be written as,T(n) = 3T(3n/2) + ?(1) Solution of above recurrence is O(n(log3/log1.5)) = O(n2.709), hence it is slower than even bubble sort(n^2). This article is contributed by DANISH KALEEM. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Sam007 divyesh072019 kashishkumar2 Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Chocolate Distribution Problem Sort an array of 0s, 1s and 2s | Dutch National Flag problem Longest Consecutive Subsequence k largest(or smallest) elements in an array Find a triplet that sum to a given value Merge Sort for Linked Lists sort() in Python Sort string of characters Minimum number of swaps required to sort an array
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 404, "s": 52, "text": "Stooge Sort is a recursive sorting algorithm. It is not much efficient but interesting sorting algorithm. It generally divides the array into two overlapping parts (2/3 each). After that it performs sorting in first 2/3 part and then it performs sorting in last 2/3 part. And then, sorting is done on first 2/3 part to ensure that the array is sorted." }, { "code": null, "e": 527, "s": 404, "text": "The key idea is that sorting the overlapping part twice exchanges the elements between the other two sections accordingly." }, { "code": null, "e": 537, "s": 527, "text": "Approach:" }, { "code": null, "e": 634, "s": 537, "text": "Step 1: If value at index 0 is greater than value at last index, swap them.Step 2: Recursively, " }, { "code": null, "e": 678, "s": 634, "text": "Stooge sort the initial 2/3rd of the array." }, { "code": null, "e": 719, "s": 678, "text": "Stooge sort the last 2/3rd of the array." }, { "code": null, "e": 767, "s": 719, "text": "Stooge sort the initial 2/3rd again to confirm." }, { "code": null, "e": 833, "s": 767, "text": "NOTE: Always take the ceil of ((2/3)*N) for selecting elements. " }, { "code": null, "e": 849, "s": 833, "text": "Illustration: " }, { "code": null, "e": 899, "s": 849, "text": "Lets consider an example: arr[] = {2, 4, 5, 3, 1}" }, { "code": null, "e": 1011, "s": 899, "text": "Step1: Initially, First and last elements are compared and if last is greater than first then they are swapped." }, { "code": null, "e": 1086, "s": 1011, "text": "Step2: Now, recursively sort initial 2/3rd of the elements as shown below:" }, { "code": null, "e": 1160, "s": 1086, "text": "Step3: Then, recursively sort last 2/3rd of the elements, as shown below:" }, { "code": null, "e": 1261, "s": 1160, "text": "Step4: Again, sort the initial 2/3rd of the elements to confirm final data is sorted.Resulted array:" }, { "code": null, "e": 1277, "s": 1261, "text": "Resulted array:" }, { "code": null, "e": 1329, "s": 1277, "text": "Below is the implementation for the above approach:" }, { "code": null, "e": 1333, "s": 1329, "text": "C++" }, { "code": null, "e": 1338, "s": 1333, "text": "Java" }, { "code": null, "e": 1346, "s": 1338, "text": "Python3" }, { "code": null, "e": 1349, "s": 1346, "text": "C#" }, { "code": null, "e": 1360, "s": 1349, "text": "Javascript" }, { "code": "// C++ code to implement stooge sort#include <iostream>using namespace std; // Function to implement stooge sortvoid stoogesort(int arr[], int l, int h){ if (l >= h) return; // If first element is smaller than last, // swap them if (arr[l] > arr[h]) swap(arr[l], arr[h]); // If there are more than 2 elements in // the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort first 2/3 elements stoogesort(arr, l, h - t); // Recursively sort last 2/3 elements stoogesort(arr, l + t, h); // Recursively sort first 2/3 elements // again to confirm stoogesort(arr, l, h - t); }} // Driver Codeint main(){ int arr[] = { 2, 4, 5, 3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // Calling Stooge Sort function to sort // the array stoogesort(arr, 0, n - 1); // Display the sorted array for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 2359, "s": 1360, "text": null }, { "code": "// Java program to implement stooge sortimport java.io.*; public class stooge { // Function to implement stooge sort static void stoogesort(int arr[], int l, int h) { if (l >= h) return; // If first element is smaller // than last, swap them if (arr[l] > arr[h]) { int t = arr[l]; arr[l] = arr[h]; arr[h] = t; } // If there are more than 2 elements in // the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort first 2/3 elements stoogesort(arr, l, h - t); // Recursively sort last 2/3 elements stoogesort(arr, l + t, h); // Recursively sort first 2/3 elements // again to confirm stoogesort(arr, l, h - t); } } // Driver Code public static void main(String args[]) { int arr[] = { 2, 4, 5, 3, 1 }; int n = arr.length; stoogesort(arr, 0, n - 1); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }}// Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 3509, "s": 2359, "text": null }, { "code": "# Python program to implement stooge sort def stoogesort(arr, l, h): if l >= h: return # If first element is smaller # than last, swap them if arr[l]>arr[h]: t = arr[l] arr[l] = arr[h] arr[h] = t # If there are more than 2 elements in # the array if h-l + 1 > 2: t = (int)((h-l + 1)/3) # Recursively sort first 2 / 3 elements stoogesort(arr, l, (h-t)) # Recursively sort last 2 / 3 elements stoogesort(arr, l + t, (h)) # Recursively sort first 2 / 3 elements # again to confirm stoogesort(arr, l, (h-t)) # deriver arr = [2, 4, 5, 3, 1]n = len(arr) stoogesort(arr, 0, n-1) for i in range(0, n): print(arr[i], end = ' ') # Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 4306, "s": 3509, "text": null }, { "code": "// C# program to implement stooge sortusing System; class GFG { // Function to implement stooge sort static void stoogesort(int[] arr, int l, int h) { if (l >= h) return; // If first element is smaller // than last, swap them if (arr[l] > arr[h]) { int t = arr[l]; arr[l] = arr[h]; arr[h] = t; } // If there are more than 2 // elements in the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort first // 2/3 elements stoogesort(arr, l, h - t); // Recursively sort last // 2/3 elements stoogesort(arr, l + t, h); // Recursively sort first // 2/3 elements again to // confirm stoogesort(arr, l, h - t); } } // Driver Code public static void Main() { int[] arr = { 2, 4, 5, 3, 1 }; int n = arr.Length; // Calling Stooge Sort function // to sort the array stoogesort(arr, 0, n - 1); // Display the sorted array for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by Sam007.", "e": 5599, "s": 4306, "text": null }, { "code": "<script> // Javascript program to implement stooge sort // Function to implement stooge sort function stoogesort(arr, l, h) { if (l >= h) return; // If first element is smaller // than last, swap them if (arr[l] > arr[h]) { let t = arr[l]; arr[l] = arr[h]; arr[h] = t; } // If there are more than 2 // elements in the array if (h - l + 1 > 2) { let t = parseInt((h - l + 1) / 3, 10); // Recursively sort first // 2/3 elements stoogesort(arr, l, h - t); // Recursively sort last // 2/3 elements stoogesort(arr, l + t, h); // Recursively sort first // 2/3 elements again to // confirm stoogesort(arr, l, h - t); } } let arr = [ 2, 4, 5, 3, 1 ]; let n = arr.length; // Calling Stooge Sort function // to sort the array stoogesort(arr, 0, n - 1); // Display the sorted array for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); </script>", "e": 6752, "s": 5599, "text": null }, { "code": null, "e": 6763, "s": 6752, "text": "1 2 3 4 5 " }, { "code": null, "e": 6847, "s": 6763, "text": "The running time complexity of stooge sort can be written as,T(n) = 3T(3n/2) + ?(1)" }, { "code": null, "e": 6957, "s": 6847, "text": "Solution of above recurrence is O(n(log3/log1.5)) = O(n2.709), hence it is slower than even bubble sort(n^2)." }, { "code": null, "e": 7254, "s": 6957, "text": "This article is contributed by DANISH KALEEM. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 7261, "s": 7254, "text": "Sam007" }, { "code": null, "e": 7275, "s": 7261, "text": "divyesh072019" }, { "code": null, "e": 7289, "s": 7275, "text": "kashishkumar2" }, { "code": null, "e": 7297, "s": 7289, "text": "Sorting" }, { "code": null, "e": 7305, "s": 7297, "text": "Sorting" }, { "code": null, "e": 7403, "s": 7305, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7427, "s": 7403, "text": "Merge two sorted arrays" }, { "code": null, "e": 7458, "s": 7427, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 7519, "s": 7458, "text": "Sort an array of 0s, 1s and 2s | Dutch National Flag problem" }, { "code": null, "e": 7551, "s": 7519, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 7595, "s": 7551, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 7636, "s": 7595, "text": "Find a triplet that sum to a given value" }, { "code": null, "e": 7664, "s": 7636, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 7681, "s": 7664, "text": "sort() in Python" }, { "code": null, "e": 7707, "s": 7681, "text": "Sort string of characters" } ]