title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
DateTime.ToOADate() Method in C# - GeeksforGeeks
13 Feb, 2019 This method is used to convert the value of this instance to the equivalent OLE Automation date. Syntax: public double ToOADate (); Return Value: This method returns a double-precision floating-point number that contains an OLE Automation date equivalent to the value of this instance. Exception:OverflowException: If the value of this instance cannot be represented as an OLE Automation Date. Below programs illustrate the use of DateTime.ToOADate() Method Example 1: // C# program to demonstrate the// DateTime.ToOADate() Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2011, 1, 1, 4, 0, 15); // Converts the value of this instance to // the equivalent OLE Automation date. // using ToOADate() method; double value = date.ToOADate(); // Display the time Console.WriteLine("OLE Automation date is {0}", value); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} OLE Automation date is 40544.1668402778 Example 2: For OverflowException // C# program to demonstrate the// DateTime.ToOADate() Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(0099, 1, 1, 4, 0, 15); // Converts the value of this instance // to the equivalent OLE Automation date. // using ToOADate() method; double value = date.ToOADate(); // Display the time Console.WriteLine("OLE Automation date is {0}", value); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} Exception Thrown: System.OverflowException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tooadate?view=netframework-4.7.2 CSharp DateTime Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n13 Feb, 2019" }, { "code": null, "e": 24399, "s": 24302, "text": "This method is used to convert the value of this instance to the equivalent OLE Automation date." }, { "code": null, "e": 24434, "s": 24399, "text": "Syntax: public double ToOADate ();" }, { "code": null, "e": 24588, "s": 24434, "text": "Return Value: This method returns a double-precision floating-point number that contains an OLE Automation date equivalent to the value of this instance." }, { "code": null, "e": 24696, "s": 24588, "text": "Exception:OverflowException: If the value of this instance cannot be represented as an OLE Automation Date." }, { "code": null, "e": 24760, "s": 24696, "text": "Below programs illustrate the use of DateTime.ToOADate() Method" }, { "code": null, "e": 24771, "s": 24760, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTime.ToOADate() Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2011, 1, 1, 4, 0, 15); // Converts the value of this instance to // the equivalent OLE Automation date. // using ToOADate() method; double value = date.ToOADate(); // Display the time Console.WriteLine(\"OLE Automation date is {0}\", value); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 25551, "s": 24771, "text": null }, { "code": null, "e": 25592, "s": 25551, "text": "OLE Automation date is 40544.1668402778\n" }, { "code": null, "e": 25625, "s": 25592, "text": "Example 2: For OverflowException" }, { "code": "// C# program to demonstrate the// DateTime.ToOADate() Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(0099, 1, 1, 4, 0, 15); // Converts the value of this instance // to the equivalent OLE Automation date. // using ToOADate() method; double value = date.ToOADate(); // Display the time Console.WriteLine(\"OLE Automation date is {0}\", value); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}", "e": 26417, "s": 25625, "text": null }, { "code": null, "e": 26461, "s": 26417, "text": "Exception Thrown: System.OverflowException\n" }, { "code": null, "e": 26472, "s": 26461, "text": "Reference:" }, { "code": null, "e": 26565, "s": 26472, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tooadate?view=netframework-4.7.2" }, { "code": null, "e": 26588, "s": 26565, "text": "CSharp DateTime Struct" }, { "code": null, "e": 26602, "s": 26588, "text": "CSharp-method" }, { "code": null, "e": 26605, "s": 26602, "text": "C#" }, { "code": null, "e": 26703, "s": 26605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26721, "s": 26703, "text": "Destructors in C#" }, { "code": null, "e": 26744, "s": 26721, "text": "Extension Method in C#" }, { "code": null, "e": 26772, "s": 26744, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26812, "s": 26772, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26855, "s": 26812, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26877, "s": 26855, "text": "Partial Classes in C#" }, { "code": null, "e": 26894, "s": 26877, "text": "C# | Inheritance" }, { "code": null, "e": 26910, "s": 26894, "text": "C# | List Class" }, { "code": null, "e": 26960, "s": 26910, "text": "Difference between Hashtable and Dictionary in C#" } ]
Django REST Framework Installation - GeeksforGeeks
05 Oct, 2021 Django REST Framework can be installed via pip package similar to Django installation. Since Django REST Framework is a wrapper over default Django Framework, to install it, Django should be installed already. Now to install rest framework follow the below process. Python Pip DjangoHow to install Django REST FrameworkTo install Django REST Framework on Windows, Linux or any operating system, one would need pip package. To check how to install pip on your operating system, checkoout – PIP Installation – Windows || Linux.Now, run a simple command,pip install djangorestframeworkWait and relax, REST framework would be installed shortly.Install Django REST Framework using Source codeOne can install Django REST Framework, using source code directly, install git command line utlity first, thengit clone https://github.com/encode/django-rest-frameworkafter cloning, it add it to bin directory where django is installed.Add rest_framework to INSTALLED_APPSFor Django REST Framework to work on top of Django, you need to add rest_framework in INSTALLED_APPS, in settings.py.INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework' ) Bingo..!! Django REST Framework is successfully installed, one case use it in any app of Django.My Personal Notes arrow_drop_upSave To install Django REST Framework on Windows, Linux or any operating system, one would need pip package. To check how to install pip on your operating system, checkoout – PIP Installation – Windows || Linux.Now, run a simple command, pip install djangorestframework Wait and relax, REST framework would be installed shortly. One can install Django REST Framework, using source code directly, install git command line utlity first, then git clone https://github.com/encode/django-rest-framework after cloning, it add it to bin directory where django is installed. For Django REST Framework to work on top of Django, you need to add rest_framework in INSTALLED_APPS, in settings.py. INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework' ) Bingo..!! Django REST Framework is successfully installed, one case use it in any app of Django. nidhi_biet Django-REST how-to-install Python Django Installation Guide Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Install Anaconda on Windows? How to Install and Run Apache Kafka on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS? Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25675, "s": 25647, "text": "\n05 Oct, 2021" }, { "code": null, "e": 25941, "s": 25675, "text": "Django REST Framework can be installed via pip package similar to Django installation. Since Django REST Framework is a wrapper over default Django Framework, to install it, Django should be installed already. Now to install rest framework follow the below process." }, { "code": null, "e": 25948, "s": 25941, "text": "Python" }, { "code": null, "e": 25952, "s": 25948, "text": "Pip" }, { "code": null, "e": 27110, "s": 25952, "text": "DjangoHow to install Django REST FrameworkTo install Django REST Framework on Windows, Linux or any operating system, one would need pip package. To check how to install pip on your operating system, checkoout – PIP Installation – Windows || Linux.Now, run a simple command,pip install djangorestframeworkWait and relax, REST framework would be installed shortly.Install Django REST Framework using Source codeOne can install Django REST Framework, using source code directly, install git command line utlity first, thengit clone https://github.com/encode/django-rest-frameworkafter cloning, it add it to bin directory where django is installed.Add rest_framework to INSTALLED_APPSFor Django REST Framework to work on top of Django, you need to add rest_framework in INSTALLED_APPS, in settings.py.INSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework'\n)\nBingo..!! Django REST Framework is successfully installed, one case use it in any app of Django.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 27343, "s": 27110, "text": "To install Django REST Framework on Windows, Linux or any operating system, one would need pip package. To check how to install pip on your operating system, checkoout – PIP Installation – Windows || Linux.Now, run a simple command," }, { "code": null, "e": 27375, "s": 27343, "text": "pip install djangorestframework" }, { "code": null, "e": 27434, "s": 27375, "text": "Wait and relax, REST framework would be installed shortly." }, { "code": null, "e": 27545, "s": 27434, "text": "One can install Django REST Framework, using source code directly, install git command line utlity first, then" }, { "code": null, "e": 27603, "s": 27545, "text": "git clone https://github.com/encode/django-rest-framework" }, { "code": null, "e": 27672, "s": 27603, "text": "after cloning, it add it to bin directory where django is installed." }, { "code": null, "e": 27790, "s": 27672, "text": "For Django REST Framework to work on top of Django, you need to add rest_framework in INSTALLED_APPS, in settings.py." }, { "code": null, "e": 28019, "s": 27790, "text": "INSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework'\n)\n" }, { "code": null, "e": 28116, "s": 28019, "text": "Bingo..!! Django REST Framework is successfully installed, one case use it in any app of Django." }, { "code": null, "e": 28127, "s": 28116, "text": "nidhi_biet" }, { "code": null, "e": 28139, "s": 28127, "text": "Django-REST" }, { "code": null, "e": 28154, "s": 28139, "text": "how-to-install" }, { "code": null, "e": 28168, "s": 28154, "text": "Python Django" }, { "code": null, "e": 28187, "s": 28168, "text": "Installation Guide" }, { "code": null, "e": 28194, "s": 28187, "text": "Python" }, { "code": null, "e": 28292, "s": 28194, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28326, "s": 28292, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28362, "s": 28326, "text": "How to Install Anaconda on Windows?" }, { "code": null, "e": 28410, "s": 28362, "text": "How to Install and Run Apache Kafka on Windows?" }, { "code": null, "e": 28468, "s": 28410, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 28510, "s": 28468, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 28538, "s": 28510, "text": "Read JSON file using Python" }, { "code": null, "e": 28588, "s": 28538, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28610, "s": 28588, "text": "Python map() function" } ]
get_property() element method - Selenium Python - GeeksforGeeks
27 Apr, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies This article revolves around how to use get_property method in Selenium. get_property method is used to get properties of an element, such as getting text_length property of anchor tag. This method will first try to return the value of a property with the given name. If a property with that name doesn’t exist, it returns the value of the property with the same name.Args:name – Name of the property to retrieve. element.get_property("property name") Example – <a href="https://www.geeksforgeeks.org/" id="link" />Text Here</a> To find an element one needs to use one of the locating strategies, For example, element = driver.find_element_by_id("link") element = driver.find_element_by_xpath("//a[@id='link']") Also, to find multiple elements, we can use – elements = driver.find_elements_by_id("link") Now one can get property of this field with text_length = element.get_property("text_length") Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we get href property of courses tab in navigation bar at geeksforgeeks.Program – # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # get text_length propertyprint(element.get_property('href')) Output- Terminal Output – Python-selenium selenium 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() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25865, "s": 25837, "text": "\n27 Apr, 2020" }, { "code": null, "e": 26422, "s": 25865, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies" }, { "code": null, "e": 26836, "s": 26422, "text": "This article revolves around how to use get_property method in Selenium. get_property method is used to get properties of an element, such as getting text_length property of anchor tag. This method will first try to return the value of a property with the given name. If a property with that name doesn’t exist, it returns the value of the property with the same name.Args:name – Name of the property to retrieve." }, { "code": null, "e": 26874, "s": 26836, "text": "element.get_property(\"property name\")" }, { "code": null, "e": 26884, "s": 26874, "text": "Example –" }, { "code": "<a href=\"https://www.geeksforgeeks.org/\" id=\"link\" />Text Here</a>", "e": 26951, "s": 26884, "text": null }, { "code": null, "e": 27032, "s": 26951, "text": "To find an element one needs to use one of the locating strategies, For example," }, { "code": null, "e": 27134, "s": 27032, "text": "element = driver.find_element_by_id(\"link\")\nelement = driver.find_element_by_xpath(\"//a[@id='link']\")" }, { "code": null, "e": 27180, "s": 27134, "text": "Also, to find multiple elements, we can use –" }, { "code": null, "e": 27226, "s": 27180, "text": "elements = driver.find_elements_by_id(\"link\")" }, { "code": null, "e": 27270, "s": 27226, "text": "Now one can get property of this field with" }, { "code": null, "e": 27320, "s": 27270, "text": "text_length = element.get_property(\"text_length\")" }, { "code": null, "e": 27494, "s": 27320, "text": "Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we get href property of courses tab in navigation bar at geeksforgeeks.Program –" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # get text_length propertyprint(element.get_property('href'))", "e": 27799, "s": 27494, "text": null }, { "code": null, "e": 27807, "s": 27799, "text": "Output-" }, { "code": null, "e": 27825, "s": 27807, "text": "Terminal Output –" }, { "code": null, "e": 27841, "s": 27825, "text": "Python-selenium" }, { "code": null, "e": 27850, "s": 27841, "text": "selenium" }, { "code": null, "e": 27857, "s": 27850, "text": "Python" }, { "code": null, "e": 27955, "s": 27857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27973, "s": 27955, "text": "Python Dictionary" }, { "code": null, "e": 28008, "s": 27973, "text": "Read a file line by line in Python" }, { "code": null, "e": 28040, "s": 28008, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28062, "s": 28040, "text": "Enumerate() in Python" }, { "code": null, "e": 28104, "s": 28062, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28134, "s": 28104, "text": "Iterate over a list in Python" }, { "code": null, "e": 28160, "s": 28134, "text": "Python String | replace()" }, { "code": null, "e": 28189, "s": 28160, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28233, "s": 28189, "text": "Reading and Writing to text files in Python" } ]
Node.js process.send() Method - GeeksforGeeks
18 May, 2021 The process.send() method is an inbuilt application programming interface of the process module which is used by the child process to communicate with the parent process. This method does not work for the root process because it does not have any parent process. Syntax: process.send(message, [sendHandle]) Parameters: This method accepts the following parameter: message: The message that has to be sent. sendHandle: A Socket or Server object. It is an optional parameter. Return Value: Boolean value. Returns true if the message was sent successfully else returns false. Example 1: First, in Parent.js, we spawn the child process. Then start listening to the child process. In Child.js, we get the message in Child.js. Then we check if send method is available and then send a message to the parent using process.send(). Parent.js // Require fork method from child_process // to spawn child processconst fork = require('child_process').fork; // Child process fileconst child_file = 'Child.js'; // Spawn child processconst child = fork(child_file); // Start listening to the child processchild.on('message', message => { // Message from the child process console.log('Message from child:', message);}); Child.js console.log('In Child.js') // If the send method is availableif(process.send) { // Send Hello process.send("Hello, this is child process.");} Run Parent.js file using the below command: node Parent.js Output: In Child.js Message from child: Hello, this is child process. Example 2: Multiple messages from the child process. Parent.js // Require fork method from child_process // to spawn child processconst fork = require('child_process').fork; // Child process fileconst child_file = 'Child.js'; // Spawn child processconst child = fork(child_file); // Start listening to the child processchild.on('message', message => { // Message from the child process console.log('Message from child:', message);}); Child.js console.log('In Child.js') // If the send method is availableif(process.send) { // Send Hello process.send("Hello, this is child process."); // Send multiple messages setTimeout((function() { return process.send("This was send after 1 second."); }), 1000); setTimeout((function() { return process.send("This was send after 2 seconds."); }), 2000); setTimeout((function() { return process.send("This was send after 3 seconds."); }), 3000); } Run Parent.js file using the below command: node Parent.js Output: In Child.js Message from child: Hello, this is child process. Message from child: This was sent after 1 second. Message from child: This was sent after 2 seconds. Message from child: This was sent after 3 seconds. Reference: https://nodejs.org/api/process.html#process_process_send_message_sendhandle_options_callback Node.js-Methods Node.js-process-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies How to connect Node.js with React.js ? Node.js Export Module Mongoose find() Function Mongoose Populate() Method Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n18 May, 2021" }, { "code": null, "e": 26530, "s": 26267, "text": "The process.send() method is an inbuilt application programming interface of the process module which is used by the child process to communicate with the parent process. This method does not work for the root process because it does not have any parent process." }, { "code": null, "e": 26538, "s": 26530, "text": "Syntax:" }, { "code": null, "e": 26574, "s": 26538, "text": "process.send(message, [sendHandle])" }, { "code": null, "e": 26631, "s": 26574, "text": "Parameters: This method accepts the following parameter:" }, { "code": null, "e": 26673, "s": 26631, "text": "message: The message that has to be sent." }, { "code": null, "e": 26741, "s": 26673, "text": "sendHandle: A Socket or Server object. It is an optional parameter." }, { "code": null, "e": 26840, "s": 26741, "text": "Return Value: Boolean value. Returns true if the message was sent successfully else returns false." }, { "code": null, "e": 27090, "s": 26840, "text": "Example 1: First, in Parent.js, we spawn the child process. Then start listening to the child process. In Child.js, we get the message in Child.js. Then we check if send method is available and then send a message to the parent using process.send()." }, { "code": null, "e": 27100, "s": 27090, "text": "Parent.js" }, { "code": "// Require fork method from child_process // to spawn child processconst fork = require('child_process').fork; // Child process fileconst child_file = 'Child.js'; // Spawn child processconst child = fork(child_file); // Start listening to the child processchild.on('message', message => { // Message from the child process console.log('Message from child:', message);});", "e": 27482, "s": 27100, "text": null }, { "code": null, "e": 27491, "s": 27482, "text": "Child.js" }, { "code": "console.log('In Child.js') // If the send method is availableif(process.send) { // Send Hello process.send(\"Hello, this is child process.\");}", "e": 27642, "s": 27491, "text": null }, { "code": null, "e": 27686, "s": 27642, "text": "Run Parent.js file using the below command:" }, { "code": null, "e": 27701, "s": 27686, "text": "node Parent.js" }, { "code": null, "e": 27709, "s": 27701, "text": "Output:" }, { "code": null, "e": 27771, "s": 27709, "text": "In Child.js\nMessage from child: Hello, this is child process." }, { "code": null, "e": 27824, "s": 27771, "text": "Example 2: Multiple messages from the child process." }, { "code": null, "e": 27834, "s": 27824, "text": "Parent.js" }, { "code": "// Require fork method from child_process // to spawn child processconst fork = require('child_process').fork; // Child process fileconst child_file = 'Child.js'; // Spawn child processconst child = fork(child_file); // Start listening to the child processchild.on('message', message => { // Message from the child process console.log('Message from child:', message);});", "e": 28216, "s": 27834, "text": null }, { "code": null, "e": 28225, "s": 28216, "text": "Child.js" }, { "code": "console.log('In Child.js') // If the send method is availableif(process.send) { // Send Hello process.send(\"Hello, this is child process.\"); // Send multiple messages setTimeout((function() { return process.send(\"This was send after 1 second.\"); }), 1000); setTimeout((function() { return process.send(\"This was send after 2 seconds.\"); }), 2000); setTimeout((function() { return process.send(\"This was send after 3 seconds.\"); }), 3000); }", "e": 28723, "s": 28225, "text": null }, { "code": null, "e": 28767, "s": 28723, "text": "Run Parent.js file using the below command:" }, { "code": null, "e": 28782, "s": 28767, "text": "node Parent.js" }, { "code": null, "e": 28790, "s": 28782, "text": "Output:" }, { "code": null, "e": 29004, "s": 28790, "text": "In Child.js\nMessage from child: Hello, this is child process.\nMessage from child: This was sent after 1 second.\nMessage from child: This was sent after 2 seconds.\nMessage from child: This was sent after 3 seconds." }, { "code": null, "e": 29108, "s": 29004, "text": "Reference: https://nodejs.org/api/process.html#process_process_send_message_sendhandle_options_callback" }, { "code": null, "e": 29124, "s": 29108, "text": "Node.js-Methods" }, { "code": null, "e": 29147, "s": 29124, "text": "Node.js-process-module" }, { "code": null, "e": 29154, "s": 29147, "text": "Picked" }, { "code": null, "e": 29162, "s": 29154, "text": "Node.js" }, { "code": null, "e": 29179, "s": 29162, "text": "Web Technologies" }, { "code": null, "e": 29277, "s": 29179, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29347, "s": 29277, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 29386, "s": 29347, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 29408, "s": 29386, "text": "Node.js Export Module" }, { "code": null, "e": 29433, "s": 29408, "text": "Mongoose find() Function" }, { "code": null, "e": 29460, "s": 29433, "text": "Mongoose Populate() Method" }, { "code": null, "e": 29500, "s": 29460, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29545, "s": 29500, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29588, "s": 29545, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29638, "s": 29588, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Marketing Incremental Lift Test 101 | Marketing Analytics | A/B Test in Advertising | Towards Data Science
Among so many different marketing platforms and tactics in the market, it can be overwhelming to choose the best strategy combinations that generate efficient marketing ROIs. Oftentimes, because of the fear of losing out on a potential marketing opportunity, more and more dollars were spent on additional marketing tech stacks or campaigns without knowing if the additional gain is worthy. To avoid wasteful spending, Lift Test is a statistical approach to evaluate your options before allocating budget on a project. Intro to Lift Test Lift Test helps identify the incremental return and causal effect of a dependent variable by applying one independent variable to the test group and not to the holdout group. For example, Lift Test can help you answer how much more the conversion rate (dependent variable) from a set of the audience can be improved by serving ads on Facebook (independent variable) versus not serving ads. The lift test result is then evaluated by the Hypothesis Testing method. If the lift between the Test and Holdout group is statistically significant, the Alternative Hypothesis is accepted to support that serving ads on Facebook will help the incremental conversion rate, and the Null Hypothesis, serving ads on Facebook will NOT help the incremental conversion rate, is rejected. What’s the difference between an A/B test vs. a Lift Test? Lift Test is a type of A/B Test. The essence of a Lift Test is about finding the incremental value of the Test group by not providing the treatment to the Holdout group. Therefore, you are not just measuring the absolute result of a single campaign but quantifying how many more conversions you could not otherwise generate without this additional campaign. On the other hand, A/B Test will provide treatments for both two groups but just different ones, and it’s not used to find the incremental return but the absolute relativity. Therefore, it’s typically called the Control group in the A/B test vs. the Holdout group in Lift Test. What’s Statistical Significance? Measuring Statistical Significance is to help you be confident that your test result was not random, and the level of confidence you want to have for the test result is related to the alpha level (Significance Level) you set when calculating the sample size, see the formulas in the Sample Size Calculator Template. Based on the P-Value test result yields (see Significance Calculation Template), if 1- (P-Value), Observed Significance, is greater than the target Significance Level, you accept the Alternative Hypothesis and reject the Null Hypothesis. Lift Test Use Case Examples: Is a new campaign worth launching considering people can convert from other existing campaigns?What’s my incremental ROI by using a new vendor to help increase reach to prospects?What’s my incremental CAC (Customers Acquisition Cost) when offering a discount to incentivize customers to place the first order versus not offering any discounts? Is a new campaign worth launching considering people can convert from other existing campaigns? What’s my incremental ROI by using a new vendor to help increase reach to prospects? What’s my incremental CAC (Customers Acquisition Cost) when offering a discount to incentivize customers to place the first order versus not offering any discounts? Step by Step Guide to Launch a Lift Test: 1. Outline testing objectives and the testing variable (independent variable) such as serving Facebook ads or not. Note that It’s always recommended to test only one variable at one time to control the data noise. 2. Based on the objectives, you will be able to choose the KPIs you want to use to measure the result including the dependent variable such as conversion rate and the allowable cost per acquisition. 3. Determine if the test will be one-tailed or two-tailed. The type of the test will affect how you calculate the required sample size in the next step. If the lift from the Test group is assumed to be only a positive impact, then it’s a one-tailed test. However, if the lift can cause negative impacts such as over-marketing, which can push away customers to not convert, then it will be a two-tailed test. 4. Determine the minimum required sample size based on different lift levels. First, set the α and β to get the desired significance and power level. The sample size will be different depending on the anticipating holdout group performance, the higher the performance in the holdout group, the smaller the sample size needed from the same level of lift. The same applies to lift level, the higher the lift, the smaller the sample size is required. Sample size calculator template 5. Based on the minimum required sample size, check if the required lift to meet the desired significance makes sense to your test scenario. If yes, estimate how much the test would cost to collect the required sample size. If the required lift is too high, look for a larger sample size and its required lift to see if achievable. The same thing applies to budget control. If a larger sample size requires cost over budget, then you can choose to go for a higher lift with a smaller sample. It is a balancing act. 6. Prepare the test audience and make sure the sample is randomly selected between the holdout and test group. For example, you can use Python pandas.DataFrame.sample function to create the randomly generated two groups if using a custom audience list. Note that adding the random_state parameter is useful to reproduce the same random selection for future validation. Code Example: #import pandas packagesimport Pandas as pd#Create a subset of audience for the test grouptest_female_under_30_ios = df[(df.segment_name == 'female_age_under_30') & (df.ios_user_flag == 1)].sample(n = 4442, random_state = 1) 7. Prepare the rest testing materials such as campaign creatives, campaign tracking setup, and so on depending on the test type. 8. Measure the test result by quantifying the lift of the dependent variable such as conversion rate between the holdout and test group to determine if the lift level based on the sample size reaches the desired statistical significance. 9. Reject or accept the Null Hypothesis based on the statistical significance. If it is to reject the Null Hypothesis (Accept that Serving ads help), then calculate business profitability metrics to evaluate if the treatment is cost-effective. If the incremental cost per acquisition falls within the allowable range, it means the testing variable (e.g., serving Facebook ads) yields enough incremental conversions (e.g., additional conversions than the holdout group), and it is worth implementing it. Metrics to calculate Statistical Significance Includes: Lift Analysis Template Note: n1= Test Sample Size, n2 = Holdout Sample Size •Test Conversion Rate: p1 •Holdout Conversion Rate: p2 •Test Standard Error (SE1): SQRT(p1×(1-p1)/n1) •Holdout Standard Error (SE2): SQRT(p2×(1-p2)/n2) •Z-Score: (p1-p2)/SQRT(POWER(SE1,2)+POWER(SE2,2)) •P-Value (Excel): 1- NORM.S.DIST(Z-Score, TRUE) •P-Value (Google Sheet): 1- NORM.S.DIST(Z-Score) •Observed Significance: 1- P-Value The above formula is written using the syntax in Excel and Google Sheet, so it can be directly applied to your Excel/Google workbook for analysis. Hope you enjoy the article and find it helpful. Feel free to leave a comment if you have any questions. I would love to hear your feedback!
[ { "code": null, "e": 691, "s": 172, "text": "Among so many different marketing platforms and tactics in the market, it can be overwhelming to choose the best strategy combinations that generate efficient marketing ROIs. Oftentimes, because of the fear of losing out on a potential marketing opportunity, more and more dollars were spent on additional marketing tech stacks or campaigns without knowing if the additional gain is worthy. To avoid wasteful spending, Lift Test is a statistical approach to evaluate your options before allocating budget on a project." }, { "code": null, "e": 710, "s": 691, "text": "Intro to Lift Test" }, { "code": null, "e": 885, "s": 710, "text": "Lift Test helps identify the incremental return and causal effect of a dependent variable by applying one independent variable to the test group and not to the holdout group." }, { "code": null, "e": 1100, "s": 885, "text": "For example, Lift Test can help you answer how much more the conversion rate (dependent variable) from a set of the audience can be improved by serving ads on Facebook (independent variable) versus not serving ads." }, { "code": null, "e": 1481, "s": 1100, "text": "The lift test result is then evaluated by the Hypothesis Testing method. If the lift between the Test and Holdout group is statistically significant, the Alternative Hypothesis is accepted to support that serving ads on Facebook will help the incremental conversion rate, and the Null Hypothesis, serving ads on Facebook will NOT help the incremental conversion rate, is rejected." }, { "code": null, "e": 1540, "s": 1481, "text": "What’s the difference between an A/B test vs. a Lift Test?" }, { "code": null, "e": 2176, "s": 1540, "text": "Lift Test is a type of A/B Test. The essence of a Lift Test is about finding the incremental value of the Test group by not providing the treatment to the Holdout group. Therefore, you are not just measuring the absolute result of a single campaign but quantifying how many more conversions you could not otherwise generate without this additional campaign. On the other hand, A/B Test will provide treatments for both two groups but just different ones, and it’s not used to find the incremental return but the absolute relativity. Therefore, it’s typically called the Control group in the A/B test vs. the Holdout group in Lift Test." }, { "code": null, "e": 2209, "s": 2176, "text": "What’s Statistical Significance?" }, { "code": null, "e": 2763, "s": 2209, "text": "Measuring Statistical Significance is to help you be confident that your test result was not random, and the level of confidence you want to have for the test result is related to the alpha level (Significance Level) you set when calculating the sample size, see the formulas in the Sample Size Calculator Template. Based on the P-Value test result yields (see Significance Calculation Template), if 1- (P-Value), Observed Significance, is greater than the target Significance Level, you accept the Alternative Hypothesis and reject the Null Hypothesis." }, { "code": null, "e": 2792, "s": 2763, "text": "Lift Test Use Case Examples:" }, { "code": null, "e": 3136, "s": 2792, "text": "Is a new campaign worth launching considering people can convert from other existing campaigns?What’s my incremental ROI by using a new vendor to help increase reach to prospects?What’s my incremental CAC (Customers Acquisition Cost) when offering a discount to incentivize customers to place the first order versus not offering any discounts?" }, { "code": null, "e": 3232, "s": 3136, "text": "Is a new campaign worth launching considering people can convert from other existing campaigns?" }, { "code": null, "e": 3317, "s": 3232, "text": "What’s my incremental ROI by using a new vendor to help increase reach to prospects?" }, { "code": null, "e": 3482, "s": 3317, "text": "What’s my incremental CAC (Customers Acquisition Cost) when offering a discount to incentivize customers to place the first order versus not offering any discounts?" }, { "code": null, "e": 3524, "s": 3482, "text": "Step by Step Guide to Launch a Lift Test:" }, { "code": null, "e": 3738, "s": 3524, "text": "1. Outline testing objectives and the testing variable (independent variable) such as serving Facebook ads or not. Note that It’s always recommended to test only one variable at one time to control the data noise." }, { "code": null, "e": 3937, "s": 3738, "text": "2. Based on the objectives, you will be able to choose the KPIs you want to use to measure the result including the dependent variable such as conversion rate and the allowable cost per acquisition." }, { "code": null, "e": 4345, "s": 3937, "text": "3. Determine if the test will be one-tailed or two-tailed. The type of the test will affect how you calculate the required sample size in the next step. If the lift from the Test group is assumed to be only a positive impact, then it’s a one-tailed test. However, if the lift can cause negative impacts such as over-marketing, which can push away customers to not convert, then it will be a two-tailed test." }, { "code": null, "e": 4793, "s": 4345, "text": "4. Determine the minimum required sample size based on different lift levels. First, set the α and β to get the desired significance and power level. The sample size will be different depending on the anticipating holdout group performance, the higher the performance in the holdout group, the smaller the sample size needed from the same level of lift. The same applies to lift level, the higher the lift, the smaller the sample size is required." }, { "code": null, "e": 4825, "s": 4793, "text": "Sample size calculator template" }, { "code": null, "e": 5340, "s": 4825, "text": "5. Based on the minimum required sample size, check if the required lift to meet the desired significance makes sense to your test scenario. If yes, estimate how much the test would cost to collect the required sample size. If the required lift is too high, look for a larger sample size and its required lift to see if achievable. The same thing applies to budget control. If a larger sample size requires cost over budget, then you can choose to go for a higher lift with a smaller sample. It is a balancing act." }, { "code": null, "e": 5451, "s": 5340, "text": "6. Prepare the test audience and make sure the sample is randomly selected between the holdout and test group." }, { "code": null, "e": 5709, "s": 5451, "text": "For example, you can use Python pandas.DataFrame.sample function to create the randomly generated two groups if using a custom audience list. Note that adding the random_state parameter is useful to reproduce the same random selection for future validation." }, { "code": null, "e": 5723, "s": 5709, "text": "Code Example:" }, { "code": null, "e": 5947, "s": 5723, "text": "#import pandas packagesimport Pandas as pd#Create a subset of audience for the test grouptest_female_under_30_ios = df[(df.segment_name == 'female_age_under_30') & (df.ios_user_flag == 1)].sample(n = 4442, random_state = 1)" }, { "code": null, "e": 6076, "s": 5947, "text": "7. Prepare the rest testing materials such as campaign creatives, campaign tracking setup, and so on depending on the test type." }, { "code": null, "e": 6314, "s": 6076, "text": "8. Measure the test result by quantifying the lift of the dependent variable such as conversion rate between the holdout and test group to determine if the lift level based on the sample size reaches the desired statistical significance." }, { "code": null, "e": 6817, "s": 6314, "text": "9. Reject or accept the Null Hypothesis based on the statistical significance. If it is to reject the Null Hypothesis (Accept that Serving ads help), then calculate business profitability metrics to evaluate if the treatment is cost-effective. If the incremental cost per acquisition falls within the allowable range, it means the testing variable (e.g., serving Facebook ads) yields enough incremental conversions (e.g., additional conversions than the holdout group), and it is worth implementing it." }, { "code": null, "e": 6873, "s": 6817, "text": "Metrics to calculate Statistical Significance Includes:" }, { "code": null, "e": 6896, "s": 6873, "text": "Lift Analysis Template" }, { "code": null, "e": 6949, "s": 6896, "text": "Note: n1= Test Sample Size, n2 = Holdout Sample Size" }, { "code": null, "e": 6975, "s": 6949, "text": "•Test Conversion Rate: p1" }, { "code": null, "e": 7004, "s": 6975, "text": "•Holdout Conversion Rate: p2" }, { "code": null, "e": 7051, "s": 7004, "text": "•Test Standard Error (SE1): SQRT(p1×(1-p1)/n1)" }, { "code": null, "e": 7101, "s": 7051, "text": "•Holdout Standard Error (SE2): SQRT(p2×(1-p2)/n2)" }, { "code": null, "e": 7151, "s": 7101, "text": "•Z-Score: (p1-p2)/SQRT(POWER(SE1,2)+POWER(SE2,2))" }, { "code": null, "e": 7199, "s": 7151, "text": "•P-Value (Excel): 1- NORM.S.DIST(Z-Score, TRUE)" }, { "code": null, "e": 7248, "s": 7199, "text": "•P-Value (Google Sheet): 1- NORM.S.DIST(Z-Score)" }, { "code": null, "e": 7283, "s": 7248, "text": "•Observed Significance: 1- P-Value" }, { "code": null, "e": 7430, "s": 7283, "text": "The above formula is written using the syntax in Excel and Google Sheet, so it can be directly applied to your Excel/Google workbook for analysis." } ]
How to detect the color using OpenCV in C++?
We will understand how to detect specific color and track object based on color. Performance of color detection and color detection based tracking system is environment dependent. If you change light of the room or if you change background color, there will be significant effect on color detection. The following program demonstrates how to detect the color using OpenCV in C++. #include<iostream> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> using namespace std; using namespace cv; int main(int argc, char** argv) { VideoCapture video_load(0);//capturing video from default camera// namedWindow("Adjust");//declaring window to show the image// int Hue_Lower_Value = 0;//initial hue value(lower)// int Hue_Lower_Upper_Value = 22;//initial hue value(upper)// int Saturation_Lower_Value = 0;//initial saturation(lower)// int Saturation_Upper_Value = 255;//initial saturation(upper)// int Value_Lower = 0;//initial value (lower)// int Value_Upper = 255;//initial saturation(upper)// createTrackbar("Hue_Lower", "Adjust", &Hue_Lower_Value, 179);//track-bar for lower hue// createTrackbar("Hue_Upper", "Adjust", &Hue_Lower_Upper_Value, 179);//track-bar for lower-upper hue// createTrackbar("Sat_Lower", "Adjust", &Saturation_Lower_Value, 255);//track-bar for lower saturation// createTrackbar("Sat_Upper", "Adjust", &Saturation_Upper_Value, 255);//track-bar for higher saturation// createTrackbar("Val_Lower", "Adjust", &Value_Lower, 255);//track-bar for lower value// createTrackbar("Val_Upper", "Adjust", &Value_Upper, 255);//track-bar for upper value// while (1) { Mat actual_Image;//matrix to load actual image// bool temp = video_load.read(actual_Image);//loading actual image to matrix from video stream// Mat convert_to_HSV;//declaring a matrix to store converted image// cvtColor(actual_Image, convert_to_HSV, COLOR_BGR2HSV);//converting BGR image to HSV and storing it in convert_to_HSV matrix// Mat detection_screen;//declaring matrix for window where object will be detected// inRange(convert_to_HSV,Scalar(Hue_Lower_Value,Saturation_Lower_Value, Value_Lower),Scalar(Hue_Lower_Upper_Value,Saturation_Upper_Value, Value_Upper), detection_screen);//applying track-bar modified value of track-bar// erode(detection_screen, detection_screen, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological opening for removing small objects from foreground// dilate(detection_screen, detection_screen, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological opening for removing small object from foreground// dilate(detection_screen, detection_screen, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological closing for filling up small holes in foreground// erode(detection_screen, detection_screen, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological closing for filling up small holes in foreground// imshow("Threesholded Image", detection_screen);//showing detected object// imshow("Original", actual_Image);//showing actual image// if (waitKey(30) == 27){ //if esc is press break the loop// break; } } return 0; }
[ { "code": null, "e": 1242, "s": 1062, "text": "We will understand how to detect specific color and track object based on color. Performance of color detection and color detection based tracking system is environment dependent." }, { "code": null, "e": 1362, "s": 1242, "text": "If you change light of the room or if you change background color, there will be significant effect on color detection." }, { "code": null, "e": 1442, "s": 1362, "text": "The following program demonstrates how to detect the color using OpenCV in C++." }, { "code": null, "e": 4297, "s": 1442, "text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\n#include<opencv2/imgproc/imgproc.hpp>\nusing namespace std;\nusing namespace cv;\nint main(int argc, char** argv) {\n VideoCapture video_load(0);//capturing video from default camera//\n namedWindow(\"Adjust\");//declaring window to show the image//\n int Hue_Lower_Value = 0;//initial hue value(lower)//\n int Hue_Lower_Upper_Value = 22;//initial hue value(upper)//\n int Saturation_Lower_Value = 0;//initial saturation(lower)//\n int Saturation_Upper_Value = 255;//initial saturation(upper)//\n int Value_Lower = 0;//initial value (lower)//\n int Value_Upper = 255;//initial saturation(upper)//\n createTrackbar(\"Hue_Lower\", \"Adjust\", &Hue_Lower_Value, 179);//track-bar for lower hue//\n createTrackbar(\"Hue_Upper\", \"Adjust\", &Hue_Lower_Upper_Value, 179);//track-bar for lower-upper hue//\n createTrackbar(\"Sat_Lower\", \"Adjust\", &Saturation_Lower_Value, 255);//track-bar for lower saturation//\n createTrackbar(\"Sat_Upper\", \"Adjust\", &Saturation_Upper_Value, 255);//track-bar for higher saturation//\n createTrackbar(\"Val_Lower\", \"Adjust\", &Value_Lower, 255);//track-bar for lower value//\n createTrackbar(\"Val_Upper\", \"Adjust\", &Value_Upper, 255);//track-bar for upper value//\n while (1) {\n Mat actual_Image;//matrix to load actual image//\n bool temp = video_load.read(actual_Image);//loading actual image to matrix from video stream//\n Mat convert_to_HSV;//declaring a matrix to store converted image//\n cvtColor(actual_Image, convert_to_HSV, COLOR_BGR2HSV);//converting BGR image to HSV and storing it in convert_to_HSV matrix//\n Mat detection_screen;//declaring matrix for window where object will be detected//\n inRange(convert_to_HSV,Scalar(Hue_Lower_Value,Saturation_Lower_Value, Value_Lower),Scalar(Hue_Lower_Upper_Value,Saturation_Upper_Value, Value_Upper), detection_screen);//applying track-bar modified value of track-bar//\n erode(detection_screen, detection_screen, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological opening for removing small objects from foreground//\n dilate(detection_screen, detection_screen, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological opening for removing small object from foreground//\n dilate(detection_screen, detection_screen, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological closing for filling up small holes in foreground//\n erode(detection_screen, detection_screen, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological closing for filling up small holes in foreground//\n imshow(\"Threesholded Image\", detection_screen);//showing detected object//\n imshow(\"Original\", actual_Image);//showing actual image//\n if (waitKey(30) == 27){ //if esc is press break the loop//\n break;\n }\n }\n return 0;\n}" } ]
Python Program to Convert Decimal to Hexadecimal - GeeksforGeeks
14 Sep, 2021 In this article, we will learn how to convert a decimal value(base 10) to a hexadecimal value (base 16) in Python. hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form. Syntax : hex(x) Parameters : x – an integer number (int object) Returns : Returns hexadecimal string. Errors and Exceptions : TypeError : Returns TypeError when anything other than integer type constants are passed as parameters. Code : Python3 # Python3 program to illustrate# hex() function print("The hexadecimal form of 69 is " + hex(69)) Output: The hexadecimal form of 69 is 0x45 The conventional method for converting decimal to hexadecimal is to divide it by 16 until it equals zero. The hexadecimal version of the given decimal number is the sequence of remainders from last to first in hexadecimal form. To convert remainders to hexadecimal form, use the following conversion table: Code : Python3 # Conversion table of remainders to# hexadecimal equivalentconversion_table = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'} # function which converts decimal value# to hexadecimal valuedef decimalToHexadecimal(decimal): hexadecimal = '' while(decimal > 0): remainder = decimal % 16 hexadecimal = conversion_table[remainder] + hexadecimal decimal = decimal // 16 return hexadecimal decimal_number = 69print("The hexadecimal form of", decimal_number, "is", decimalToHexadecimal(decimal_number)) Output: The hexadecimal form of 69 is 45 The idea is similar to that used in the iterative approach. Code : Python3 # Conversion table of remainders to# hexadecimal equivalentconversion_table = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'} # function which converts decimal value# to hexadecimal valuedef decimalToHexadecimal(decimal): if(decimal <= 0): return '' remainder = decimal % 16 return decimalToHexadecimal(decimal//16) + conversion_table[remainder] decimal_number = 69print("The hexadecimal form of", decimal_number, "is", decimalToHexadecimal(decimal_number)) Output: The hexadecimal form of 69 is 45 Blogathon-2021 Numbers Picked Blogathon Python Python Programs Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create a Table With Multiple Foreign Keys in SQL? How to Import JSON Data into SQL Server? Stratified Sampling in Pandas How to pass data into table from a form using React Components SQL Query to Convert Datetime to Date Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 26233, "s": 26205, "text": "\n14 Sep, 2021" }, { "code": null, "e": 26349, "s": 26233, "text": "In this article, we will learn how to convert a decimal value(base 10) to a hexadecimal value (base 16) in Python. " }, { "code": null, "e": 26493, "s": 26349, "text": "hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form." }, { "code": null, "e": 26510, "s": 26493, "text": "Syntax : hex(x) " }, { "code": null, "e": 26524, "s": 26510, "text": "Parameters : " }, { "code": null, "e": 26559, "s": 26524, "text": "x – an integer number (int object)" }, { "code": null, "e": 26598, "s": 26559, "text": "Returns : Returns hexadecimal string." }, { "code": null, "e": 26622, "s": 26598, "text": "Errors and Exceptions :" }, { "code": null, "e": 26678, "s": 26622, "text": "TypeError : Returns TypeError when anything other than" }, { "code": null, "e": 26743, "s": 26678, "text": " integer type constants are passed as parameters. " }, { "code": null, "e": 26750, "s": 26743, "text": "Code :" }, { "code": null, "e": 26758, "s": 26750, "text": "Python3" }, { "code": "# Python3 program to illustrate# hex() function print(\"The hexadecimal form of 69 is \" + hex(69))", "e": 26862, "s": 26758, "text": null }, { "code": null, "e": 26870, "s": 26862, "text": "Output:" }, { "code": null, "e": 26905, "s": 26870, "text": "The hexadecimal form of 69 is 0x45" }, { "code": null, "e": 27212, "s": 26905, "text": "The conventional method for converting decimal to hexadecimal is to divide it by 16 until it equals zero. The hexadecimal version of the given decimal number is the sequence of remainders from last to first in hexadecimal form. To convert remainders to hexadecimal form, use the following conversion table:" }, { "code": null, "e": 27219, "s": 27212, "text": "Code :" }, { "code": null, "e": 27227, "s": 27219, "text": "Python3" }, { "code": "# Conversion table of remainders to# hexadecimal equivalentconversion_table = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'} # function which converts decimal value# to hexadecimal valuedef decimalToHexadecimal(decimal): hexadecimal = '' while(decimal > 0): remainder = decimal % 16 hexadecimal = conversion_table[remainder] + hexadecimal decimal = decimal // 16 return hexadecimal decimal_number = 69print(\"The hexadecimal form of\", decimal_number, \"is\", decimalToHexadecimal(decimal_number))", "e": 27909, "s": 27227, "text": null }, { "code": null, "e": 27917, "s": 27909, "text": "Output:" }, { "code": null, "e": 27950, "s": 27917, "text": "The hexadecimal form of 69 is 45" }, { "code": null, "e": 28010, "s": 27950, "text": "The idea is similar to that used in the iterative approach." }, { "code": null, "e": 28017, "s": 28010, "text": "Code :" }, { "code": null, "e": 28025, "s": 28017, "text": "Python3" }, { "code": "# Conversion table of remainders to# hexadecimal equivalentconversion_table = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'} # function which converts decimal value# to hexadecimal valuedef decimalToHexadecimal(decimal): if(decimal <= 0): return '' remainder = decimal % 16 return decimalToHexadecimal(decimal//16) + conversion_table[remainder] decimal_number = 69print(\"The hexadecimal form of\", decimal_number, \"is\", decimalToHexadecimal(decimal_number))", "e": 28654, "s": 28025, "text": null }, { "code": null, "e": 28662, "s": 28654, "text": "Output:" }, { "code": null, "e": 28695, "s": 28662, "text": "The hexadecimal form of 69 is 45" }, { "code": null, "e": 28710, "s": 28695, "text": "Blogathon-2021" }, { "code": null, "e": 28718, "s": 28710, "text": "Numbers" }, { "code": null, "e": 28725, "s": 28718, "text": "Picked" }, { "code": null, "e": 28735, "s": 28725, "text": "Blogathon" }, { "code": null, "e": 28742, "s": 28735, "text": "Python" }, { "code": null, "e": 28758, "s": 28742, "text": "Python Programs" }, { "code": null, "e": 28766, "s": 28758, "text": "Numbers" }, { "code": null, "e": 28864, "s": 28766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28921, "s": 28864, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28962, "s": 28921, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 28992, "s": 28962, "text": "Stratified Sampling in Pandas" }, { "code": null, "e": 29055, "s": 28992, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 29093, "s": 29055, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 29121, "s": 29093, "text": "Read JSON file using Python" }, { "code": null, "e": 29171, "s": 29121, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29193, "s": 29171, "text": "Python map() function" } ]
Importance of Hashcode method in Java - GeeksforGeeks
18 Jan, 2018 Prerequisite: Equals() and hashCode() methods in Java HashMap and HashSet use hashing to manipulate data. They use hashCode() method to check hash values. The default implementation of hashCode() in Object class returns distinct integers for different objects. Sometimes, we have to implement hashCode method in our program.Consider the following example // Java puzzle to illustrate use// of hashcode() and equals() methodimport java.util.*;public class Name { private final String first, last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Object o) { if (!(o instanceof Name)) return false; Name n = (Name)o; return n.first.equals(first) && n.last.equals(last); } public static void main(String[] args) { Set<Name> s = new HashSet<Name>(); s.add(new Name("Shubham", "Juneja")); System.out.println( s.contains(new Name("Shubham", "Juneja"))); }} Output: false A Name instance consists of a first name and a last name. Two Name instances are equal, as computed by the equals method, if their first names are equal and their last names are equal. First names and last names are compared using the equals method defined in String. Two strings are equal if they consist of the same characters in the same order. Therefore, two Name instances are equal if they represent the same name. For example, the following method invocation returns true: new Name(“Shubham”, “Juneja”).equals(new Name(“Shubham”, “Juneja”)) The main method of the program creates two Name instances, both representing Shubham Juneja. The program puts the first instance into a hash set and then checks whether the set contains the second. The two Name instances are equal, so it might seem that the program should print true. If you run it, it almost certainly printed false.Why not expected output?The bug is that Name violates the hashCode contract. This might seem strange, as Name doesn’t even have a hashCode method, but that is precisely the problem. The Name class overrides the equals method, and the hashCode contract demands that equal objects have equal hash codes. To fulfill this contract, you must override hashCode whenever you override equals.Because it fails to override hashCode, the Name class inherits its hashCode implementation from Object. This implementation returns an identity-based hash code. In other words, distinct objects are likely to have unequal hash values, even if they are equal. Name does not fulfill the hashCode contract, so the behavior of a hash set containing Name elements is unspecified.When the program puts the first Name instance into the hash set, the set puts an entry for this instance into a hash bucket. The set chooses the hash bucket based on the hash value of the instance, as computed by its hashCode method. When it checks whether the second Name instance is contained in the hash set, the program chooses which bucket to search based on the hash value of the second instance. Because the second instance is distinct from the first, it is likely to have a different hash value.Solution:If the two hash values map to different buckets, the contains method will return false. Suppose that the two Name instances map to the same bucket.All HashSet implementations that we know of have an optimization in which each entry stores the hash value of its element in addition to the element itself. When searching for an element, the implementation selects the appropriate hash bucket and traverses its entries, comparing the hash value stored in each entry with the hash value of the desired element. Only if the two hash values are equal does the implementation check the elements for equality. This optimization makes sense because it is usually much cheaper to compare hash codes than elements.Because of this optimization, it is not enough for the hash set to search in the right bucket; the two Name instances must have equal hash values in order for the hash set to recognize them as equal. The odds that the program prints true are therefore the odds that two consecutively created objects have the same identity hash code.Results may vary depending on which Java implementation is used, but you are highly unlikely to see the program print true on any JRE we know of. To fix the problem, simply add an appropriate hashCode method to the Name class. Once this method is added, the program will print true as expected:public int hashCode() { return 63 * first.hashCode() + last.hashCode(); } This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave Why not expected output? The bug is that Name violates the hashCode contract. This might seem strange, as Name doesn’t even have a hashCode method, but that is precisely the problem. The Name class overrides the equals method, and the hashCode contract demands that equal objects have equal hash codes. To fulfill this contract, you must override hashCode whenever you override equals. Because it fails to override hashCode, the Name class inherits its hashCode implementation from Object. This implementation returns an identity-based hash code. In other words, distinct objects are likely to have unequal hash values, even if they are equal. Name does not fulfill the hashCode contract, so the behavior of a hash set containing Name elements is unspecified. When the program puts the first Name instance into the hash set, the set puts an entry for this instance into a hash bucket. The set chooses the hash bucket based on the hash value of the instance, as computed by its hashCode method. When it checks whether the second Name instance is contained in the hash set, the program chooses which bucket to search based on the hash value of the second instance. Because the second instance is distinct from the first, it is likely to have a different hash value. Solution: If the two hash values map to different buckets, the contains method will return false. Suppose that the two Name instances map to the same bucket.All HashSet implementations that we know of have an optimization in which each entry stores the hash value of its element in addition to the element itself. When searching for an element, the implementation selects the appropriate hash bucket and traverses its entries, comparing the hash value stored in each entry with the hash value of the desired element. Only if the two hash values are equal does the implementation check the elements for equality. This optimization makes sense because it is usually much cheaper to compare hash codes than elements. Because of this optimization, it is not enough for the hash set to search in the right bucket; the two Name instances must have equal hash values in order for the hash set to recognize them as equal. The odds that the program prints true are therefore the odds that two consecutively created objects have the same identity hash code. Results may vary depending on which Java implementation is used, but you are highly unlikely to see the program print true on any JRE we know of. To fix the problem, simply add an appropriate hashCode method to the Name class. Once this method is added, the program will print true as expected:public int hashCode() { return 63 * first.hashCode() + last.hashCode(); } This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave public int hashCode() { return 63 * first.hashCode() + last.hashCode(); } Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-HashMap java-hashset Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java HashMap in Java with Examples How to iterate any Map in Java ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Multidimensional Arrays in Java Stack Class in Java LinkedList in Java Overriding in Java Set in Java
[ { "code": null, "e": 24234, "s": 24206, "text": "\n18 Jan, 2018" }, { "code": null, "e": 24288, "s": 24234, "text": "Prerequisite: Equals() and hashCode() methods in Java" }, { "code": null, "e": 24589, "s": 24288, "text": "HashMap and HashSet use hashing to manipulate data. They use hashCode() method to check hash values. The default implementation of hashCode() in Object class returns distinct integers for different objects. Sometimes, we have to implement hashCode method in our program.Consider the following example" }, { "code": "// Java puzzle to illustrate use// of hashcode() and equals() methodimport java.util.*;public class Name { private final String first, last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Object o) { if (!(o instanceof Name)) return false; Name n = (Name)o; return n.first.equals(first) && n.last.equals(last); } public static void main(String[] args) { Set<Name> s = new HashSet<Name>(); s.add(new Name(\"Shubham\", \"Juneja\")); System.out.println( s.contains(new Name(\"Shubham\", \"Juneja\"))); }}", "e": 25247, "s": 24589, "text": null }, { "code": null, "e": 25255, "s": 25247, "text": "Output:" }, { "code": null, "e": 25261, "s": 25255, "text": "false" }, { "code": null, "e": 25446, "s": 25261, "text": "A Name instance consists of a first name and a last name. Two Name instances are equal, as computed by the equals method, if their first names are equal and their last names are equal." }, { "code": null, "e": 25902, "s": 25446, "text": "First names and last names are compared using the equals method defined in String. Two strings are equal if they consist of the same characters in the same order. Therefore, two Name instances are equal if they represent the same name. For example, the following method invocation returns true: new Name(“Shubham”, “Juneja”).equals(new Name(“Shubham”, “Juneja”)) The main method of the program creates two Name instances, both representing Shubham Juneja." }, { "code": null, "e": 29277, "s": 25902, "text": "The program puts the first instance into a hash set and then checks whether the set contains the second. The two Name instances are equal, so it might seem that the program should print true. If you run it, it almost certainly printed false.Why not expected output?The bug is that Name violates the hashCode contract. This might seem strange, as Name doesn’t even have a hashCode method, but that is precisely the problem. The Name class overrides the equals method, and the hashCode contract demands that equal objects have equal hash codes. To fulfill this contract, you must override hashCode whenever you override equals.Because it fails to override hashCode, the Name class inherits its hashCode implementation from Object. This implementation returns an identity-based hash code. In other words, distinct objects are likely to have unequal hash values, even if they are equal. Name does not fulfill the hashCode contract, so the behavior of a hash set containing Name elements is unspecified.When the program puts the first Name instance into the hash set, the set puts an entry for this instance into a hash bucket. The set chooses the hash bucket based on the hash value of the instance, as computed by its hashCode method. When it checks whether the second Name instance is contained in the hash set, the program chooses which bucket to search based on the hash value of the second instance. Because the second instance is distinct from the first, it is likely to have a different hash value.Solution:If the two hash values map to different buckets, the contains method will return false. Suppose that the two Name instances map to the same bucket.All HashSet implementations that we know of have an optimization in which each entry stores the hash value of its element in addition to the element itself. When searching for an element, the implementation selects the appropriate hash bucket and traverses its entries, comparing the hash value stored in each entry with the hash value of the desired element. Only if the two hash values are equal does the implementation check the elements for equality. This optimization makes sense because it is usually much cheaper to compare hash codes than elements.Because of this optimization, it is not enough for the hash set to search in the right bucket; the two Name instances must have equal hash values in order for the hash set to recognize them as equal. The odds that the program prints true are therefore the odds that two consecutively created objects have the same identity hash code.Results may vary depending on which Java implementation is used, but you are highly unlikely to see the program print true on any JRE we know of. To fix the problem, simply add an appropriate hashCode method to the Name class. Once this method is added, the program will print true as expected:public int hashCode() {\nreturn 63 * first.hashCode() + last.hashCode();\n}\nThis article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29302, "s": 29277, "text": "Why not expected output?" }, { "code": null, "e": 29663, "s": 29302, "text": "The bug is that Name violates the hashCode contract. This might seem strange, as Name doesn’t even have a hashCode method, but that is precisely the problem. The Name class overrides the equals method, and the hashCode contract demands that equal objects have equal hash codes. To fulfill this contract, you must override hashCode whenever you override equals." }, { "code": null, "e": 30037, "s": 29663, "text": "Because it fails to override hashCode, the Name class inherits its hashCode implementation from Object. This implementation returns an identity-based hash code. In other words, distinct objects are likely to have unequal hash values, even if they are equal. Name does not fulfill the hashCode contract, so the behavior of a hash set containing Name elements is unspecified." }, { "code": null, "e": 30541, "s": 30037, "text": "When the program puts the first Name instance into the hash set, the set puts an entry for this instance into a hash bucket. The set chooses the hash bucket based on the hash value of the instance, as computed by its hashCode method. When it checks whether the second Name instance is contained in the hash set, the program chooses which bucket to search based on the hash value of the second instance. Because the second instance is distinct from the first, it is likely to have a different hash value." }, { "code": null, "e": 30551, "s": 30541, "text": "Solution:" }, { "code": null, "e": 31255, "s": 30551, "text": "If the two hash values map to different buckets, the contains method will return false. Suppose that the two Name instances map to the same bucket.All HashSet implementations that we know of have an optimization in which each entry stores the hash value of its element in addition to the element itself. When searching for an element, the implementation selects the appropriate hash bucket and traverses its entries, comparing the hash value stored in each entry with the hash value of the desired element. Only if the two hash values are equal does the implementation check the elements for equality. This optimization makes sense because it is usually much cheaper to compare hash codes than elements." }, { "code": null, "e": 31589, "s": 31255, "text": "Because of this optimization, it is not enough for the hash set to search in the right bucket; the two Name instances must have equal hash values in order for the hash set to recognize them as equal. The odds that the program prints true are therefore the odds that two consecutively created objects have the same identity hash code." }, { "code": null, "e": 32418, "s": 31589, "text": "Results may vary depending on which Java implementation is used, but you are highly unlikely to see the program print true on any JRE we know of. To fix the problem, simply add an appropriate hashCode method to the Name class. Once this method is added, the program will print true as expected:public int hashCode() {\nreturn 63 * first.hashCode() + last.hashCode();\n}\nThis article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 32493, "s": 32418, "text": "public int hashCode() {\nreturn 63 * first.hashCode() + last.hashCode();\n}\n" }, { "code": null, "e": 32618, "s": 32493, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 32631, "s": 32618, "text": "Java-HashMap" }, { "code": null, "e": 32644, "s": 32631, "text": "java-hashset" }, { "code": null, "e": 32649, "s": 32644, "text": "Java" }, { "code": null, "e": 32654, "s": 32649, "text": "Java" }, { "code": null, "e": 32752, "s": 32654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32761, "s": 32752, "text": "Comments" }, { "code": null, "e": 32774, "s": 32761, "text": "Old Comments" }, { "code": null, "e": 32806, "s": 32774, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 32836, "s": 32806, "text": "HashMap in Java with Examples" }, { "code": null, "e": 32867, "s": 32836, "text": "How to iterate any Map in Java" }, { "code": null, "e": 32885, "s": 32867, "text": "ArrayList in Java" }, { "code": null, "e": 32936, "s": 32885, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 32968, "s": 32936, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32988, "s": 32968, "text": "Stack Class in Java" }, { "code": null, "e": 33007, "s": 32988, "text": "LinkedList in Java" }, { "code": null, "e": 33026, "s": 33007, "text": "Overriding in Java" } ]
AngularJS | angular.toJson() Function - GeeksforGeeks
12 Apr, 2019 The angular.toJson() Function in AngularJS is used to serialize the javascript object into a JSON – formatted string. It takes the javascript object and returns JSON string. Syntax: angular.toJson(object) Example: <!DOCTYPE html><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> </script> <title> angular.toJson() </title></head> <body ng-app="app" style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2> angular.toJson() </h2> <div ng-controller="geek"> <button ng-click="showAlert()"> Click it!</button> </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function($scope) { $scope.showAlert = function() { var string = { 'Name': 'Quick sort', 'Type': 'sorting' }; alert(angular.toJson(string)); } }]); </script></body> </html> Output:Before Click:After Click: Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript Top 10 Projects For Beginners To Practice HTML and CSS Skills Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 28346, "s": 28318, "text": "\n12 Apr, 2019" }, { "code": null, "e": 28520, "s": 28346, "text": "The angular.toJson() Function in AngularJS is used to serialize the javascript object into a JSON – formatted string. It takes the javascript object and returns JSON string." }, { "code": null, "e": 28528, "s": 28520, "text": "Syntax:" }, { "code": null, "e": 28551, "s": 28528, "text": "angular.toJson(object)" }, { "code": null, "e": 28560, "s": 28551, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js\"> </script> <title> angular.toJson() </title></head> <body ng-app=\"app\" style=\"text-align:center\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2> angular.toJson() </h2> <div ng-controller=\"geek\"> <button ng-click=\"showAlert()\"> Click it!</button> </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function($scope) { $scope.showAlert = function() { var string = { 'Name': 'Quick sort', 'Type': 'sorting' }; alert(angular.toJson(string)); } }]); </script></body> </html>", "e": 29423, "s": 28560, "text": null }, { "code": null, "e": 29456, "s": 29423, "text": "Output:Before Click:After Click:" }, { "code": null, "e": 29473, "s": 29456, "text": "Web Technologies" }, { "code": null, "e": 29571, "s": 29473, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29611, "s": 29571, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29644, "s": 29611, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29689, "s": 29644, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29732, "s": 29689, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29782, "s": 29732, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29843, "s": 29782, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29905, "s": 29843, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29977, "s": 29905, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30035, "s": 29977, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Insertion sort in Java.
Following is the required program. Live Demo public class Tester { public static void insertionSort(int array[]) { int n = array.length; for (int j = 1; j < n; j++) { int key = array[j]; int i = j-1; while ( (i > -1) &amp;&amp; ( array [i] > key ) ){ array [i+1] = array [i]; i--; } array[i+1] = key; } } public static void main(String a[]){ int arr[] = {21,60,32,01,41,34,5}; System.out.println("Before Insertion Sort"); for(int i:arr){ System.out.print(i+" "); } System.out.println(); insertionSort(arr); //sorting array using insertion sort System.out.println("After Insertion Sort"); for(int i:arr){ System.out.print(i+" "); } } } Before Insertion Sort 21 60 32 1 41 34 5 After Insertion Sort 1 5 21 32 34 41 60
[ { "code": null, "e": 1097, "s": 1062, "text": "Following is the required program." }, { "code": null, "e": 1107, "s": 1097, "text": "Live Demo" }, { "code": null, "e": 1938, "s": 1107, "text": "public class Tester {\n public static void insertionSort(int array[]) { \n int n = array.length; \n for (int j = 1; j < n; j++) { \n int key = array[j]; \n int i = j-1; \n while ( (i > -1) &amp;&amp; ( array [i] > key ) ){ \n array [i+1] = array [i]; \n i--; \n } \n array[i+1] = key; \n } \n }\n public static void main(String a[]){ \n int arr[] = {21,60,32,01,41,34,5}; \n System.out.println(\"Before Insertion Sort\"); \n for(int i:arr){ \n System.out.print(i+\" \"); \n } \n System.out.println(); \n insertionSort(arr); //sorting array using insertion sort \n System.out.println(\"After Insertion Sort\"); \n for(int i:arr){ \n System.out.print(i+\" \"); \n } \n } \n}" }, { "code": null, "e": 2019, "s": 1938, "text": "Before Insertion Sort\n21 60 32 1 41 34 5\nAfter Insertion Sort\n1 5 21 32 34 41 60" } ]
How to compress a file in Java?
The DeflaterOutputStream class of Java is used to compress the given data and stream it out to the destination. The write() method of this class accepts the data (in integer and byte format), compresses it and, writes it to the destination of the current DeflaterOutputStream object. To compress a file using this method &Minus; Create a FileInputStream object, by passing the path of the file to be compressed in String format, as a parameter to its constructor. Create a FileOutputStream object, by passing the path of the output file, in String format, as a parameter to its constructor. Create a DeflaterOutputStream object, by passing the above created FileOutputStream object, as a parameter to its constructor. Then, read the contents of the input file and write using the write() method of the DeflaterOutputStream class. import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.DeflaterOutputStream; public class CompressingFiles { public static void main(String args[]) throws IOException { //Instantiating the FileInputStream String inputPath = "D:\\ExampleDirectory\\logo.jpg"; FileInputStream inputStream = new FileInputStream(inputPath); //Instantiating the FileOutputStream String outputPath = "D:\\ExampleDirectory\\compressedLogo.txt"; FileOutputStream outputStream = new FileOutputStream(outputPath); //Instantiating the DeflaterOutputStream DeflaterOutputStream compresser = new DeflaterOutputStream(outputStream); int contents; while ((contents=inputStream.read())!=-1){ compresser.write(contents); } compresser.close(); System.out.println("File compressed......."); } } File compressed.......
[ { "code": null, "e": 1174, "s": 1062, "text": "The DeflaterOutputStream class of Java is used to compress the given data and stream it out to the destination." }, { "code": null, "e": 1391, "s": 1174, "text": "The write() method of this class accepts the data (in integer and byte format), compresses it and, writes it to the destination of the current DeflaterOutputStream object. To compress a file using this method &Minus;" }, { "code": null, "e": 1526, "s": 1391, "text": "Create a FileInputStream object, by passing the path of the file to be compressed in String format, as a parameter to its constructor." }, { "code": null, "e": 1653, "s": 1526, "text": "Create a FileOutputStream object, by passing the path of the output file, in String format, as a parameter to its constructor." }, { "code": null, "e": 1780, "s": 1653, "text": "Create a DeflaterOutputStream object, by passing the above created FileOutputStream object, as a parameter to its constructor." }, { "code": null, "e": 1892, "s": 1780, "text": "Then, read the contents of the input file and write using the write() method of the DeflaterOutputStream class." }, { "code": null, "e": 2771, "s": 1892, "text": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.zip.DeflaterOutputStream;\npublic class CompressingFiles {\n public static void main(String args[]) throws IOException {\n //Instantiating the FileInputStream\n String inputPath = \"D:\\\\ExampleDirectory\\\\logo.jpg\";\n FileInputStream inputStream = new FileInputStream(inputPath);\n //Instantiating the FileOutputStream\n String outputPath = \"D:\\\\ExampleDirectory\\\\compressedLogo.txt\";\n FileOutputStream outputStream = new FileOutputStream(outputPath);\n //Instantiating the DeflaterOutputStream\n DeflaterOutputStream compresser = new DeflaterOutputStream(outputStream);\n int contents;\n while ((contents=inputStream.read())!=-1){\n compresser.write(contents);\n }\n compresser.close();\n System.out.println(\"File compressed.......\");\n }\n}" }, { "code": null, "e": 2794, "s": 2771, "text": "File compressed......." } ]
How to Write Excel-like Formulas in Python | by Roman Orac | Towards Data Science
Many Python users are transitioning from spreadsheets because of a Python package that allows users to use Excel-like syntax. It is a spreadsheet environment for JupyterLab to help you with your Python analysis. Meet Mito — a Python package that initializes an interactive spreadsheet into your JupyterLab Environment. For each edit you make in the spreadsheet, Mito generates production-ready Python code. It’s also free to use. By reading this article you’ll learn: How to perform basic Excel-like operations in Python How to write Excel-like formulas in Python In case you’ve missed my previous articles about this topic, see Mito — A Spreadsheet that Generates Python. To use Excel syntax, first initialize the Mitosheet using the commands: import mitosheetmitosheet.sheet() This will render the interactive spreadsheet, where you can: pass in a dataset from your local files or you can pass in an existent DataFrame in your notebook as an argument to the Mitosheet call: mitosheet.sheet(df)) To install Mito, run these commands: python -m pip install mitoinstallerpython -m mitoinstaller install Here are the full install instructions. To add a column, click the “ADD COL” button in the toolbar at the top of the Mitosheet. With the new column, you can use spreadsheet functions and formulas. When you add a column, it generates the equivalent Python in the code cell below the Mitosheet. To rename a column just double click the column's title and type in whichever new title you want. Within the cells of the new column, you can assign a formula. In the new column, you can use normal Excel-like functions and Mito will generate the equivalent Python code. As you begin to type your function, a suggestion list of possible functions to choose from will populate a menu below. The function used in the image above generates the equivalent Python (which is auto-documented). Airport_Pets_csv['New_Column'] = IF(Airport_Pets_csv['Division'] == "Central", 1, 0) Mito has many different types of Excel functions ready to use in the sheet. You can use: Date Manipulation Statistical Analysis Data Cleaning and more. See the formula reference page for all supported Excel-like formulas. Mito allows the users to select any cell in the DataFrame and change a specific value — just as they would in a spreadsheet. This can be an important feature for quick data editing and data validation. This edit generates the equivalent code: # Set column City at index 0 in Airport_Pets_csv to AmherstAirport_Pets_csv.at[0, 'City'] = "Amherst" Mito also gives users a familiar spreadsheet environment to complete other common Python tasks. Users can create pivot tables in an interactive setting, and have the equivalent code these tables generated automatically: Users can generate graphs and the equivalent code as well: Mito also supports common analysis features such as: filtering sorting summary statistics merging dataset macros exporting to CSV Mito is a powerful tool for those wishing to transition from spreadsheet environments like Excel or Google Spreadsheets to Python. A neet Mito feature is that it shows how it calculates certain operations. So you can learn while clicking through your analysis. As an experienced pandas user, I use Mito for the initial Exploratory Data Analysis. With Mito I avoid writing the same pandas commands over and over. If you enjoy reading these stories, why not become a Medium paying member? It is $5 per month, and you will get unlimited access to 10000s of stories and writers. If you sign up using my link, I will earn a small commission.
[ { "code": null, "e": 383, "s": 171, "text": "Many Python users are transitioning from spreadsheets because of a Python package that allows users to use Excel-like syntax. It is a spreadsheet environment for JupyterLab to help you with your Python analysis." }, { "code": null, "e": 601, "s": 383, "text": "Meet Mito — a Python package that initializes an interactive spreadsheet into your JupyterLab Environment. For each edit you make in the spreadsheet, Mito generates production-ready Python code. It’s also free to use." }, { "code": null, "e": 639, "s": 601, "text": "By reading this article you’ll learn:" }, { "code": null, "e": 692, "s": 639, "text": "How to perform basic Excel-like operations in Python" }, { "code": null, "e": 735, "s": 692, "text": "How to write Excel-like formulas in Python" }, { "code": null, "e": 844, "s": 735, "text": "In case you’ve missed my previous articles about this topic, see Mito — A Spreadsheet that Generates Python." }, { "code": null, "e": 916, "s": 844, "text": "To use Excel syntax, first initialize the Mitosheet using the commands:" }, { "code": null, "e": 950, "s": 916, "text": "import mitosheetmitosheet.sheet()" }, { "code": null, "e": 1011, "s": 950, "text": "This will render the interactive spreadsheet, where you can:" }, { "code": null, "e": 1051, "s": 1011, "text": "pass in a dataset from your local files" }, { "code": null, "e": 1147, "s": 1051, "text": "or you can pass in an existent DataFrame in your notebook as an argument to the Mitosheet call:" }, { "code": null, "e": 1168, "s": 1147, "text": "mitosheet.sheet(df))" }, { "code": null, "e": 1205, "s": 1168, "text": "To install Mito, run these commands:" }, { "code": null, "e": 1272, "s": 1205, "text": "python -m pip install mitoinstallerpython -m mitoinstaller install" }, { "code": null, "e": 1312, "s": 1272, "text": "Here are the full install instructions." }, { "code": null, "e": 1469, "s": 1312, "text": "To add a column, click the “ADD COL” button in the toolbar at the top of the Mitosheet. With the new column, you can use spreadsheet functions and formulas." }, { "code": null, "e": 1565, "s": 1469, "text": "When you add a column, it generates the equivalent Python in the code cell below the Mitosheet." }, { "code": null, "e": 1663, "s": 1565, "text": "To rename a column just double click the column's title and type in whichever new title you want." }, { "code": null, "e": 1725, "s": 1663, "text": "Within the cells of the new column, you can assign a formula." }, { "code": null, "e": 1835, "s": 1725, "text": "In the new column, you can use normal Excel-like functions and Mito will generate the equivalent Python code." }, { "code": null, "e": 1954, "s": 1835, "text": "As you begin to type your function, a suggestion list of possible functions to choose from will populate a menu below." }, { "code": null, "e": 2051, "s": 1954, "text": "The function used in the image above generates the equivalent Python (which is auto-documented)." }, { "code": null, "e": 2136, "s": 2051, "text": "Airport_Pets_csv['New_Column'] = IF(Airport_Pets_csv['Division'] == \"Central\", 1, 0)" }, { "code": null, "e": 2225, "s": 2136, "text": "Mito has many different types of Excel functions ready to use in the sheet. You can use:" }, { "code": null, "e": 2243, "s": 2225, "text": "Date Manipulation" }, { "code": null, "e": 2264, "s": 2243, "text": "Statistical Analysis" }, { "code": null, "e": 2278, "s": 2264, "text": "Data Cleaning" }, { "code": null, "e": 2288, "s": 2278, "text": "and more." }, { "code": null, "e": 2358, "s": 2288, "text": "See the formula reference page for all supported Excel-like formulas." }, { "code": null, "e": 2560, "s": 2358, "text": "Mito allows the users to select any cell in the DataFrame and change a specific value — just as they would in a spreadsheet. This can be an important feature for quick data editing and data validation." }, { "code": null, "e": 2601, "s": 2560, "text": "This edit generates the equivalent code:" }, { "code": null, "e": 2703, "s": 2601, "text": "# Set column City at index 0 in Airport_Pets_csv to AmherstAirport_Pets_csv.at[0, 'City'] = \"Amherst\"" }, { "code": null, "e": 2799, "s": 2703, "text": "Mito also gives users a familiar spreadsheet environment to complete other common Python tasks." }, { "code": null, "e": 2923, "s": 2799, "text": "Users can create pivot tables in an interactive setting, and have the equivalent code these tables generated automatically:" }, { "code": null, "e": 2982, "s": 2923, "text": "Users can generate graphs and the equivalent code as well:" }, { "code": null, "e": 3035, "s": 2982, "text": "Mito also supports common analysis features such as:" }, { "code": null, "e": 3045, "s": 3035, "text": "filtering" }, { "code": null, "e": 3053, "s": 3045, "text": "sorting" }, { "code": null, "e": 3072, "s": 3053, "text": "summary statistics" }, { "code": null, "e": 3088, "s": 3072, "text": "merging dataset" }, { "code": null, "e": 3095, "s": 3088, "text": "macros" }, { "code": null, "e": 3112, "s": 3095, "text": "exporting to CSV" }, { "code": null, "e": 3243, "s": 3112, "text": "Mito is a powerful tool for those wishing to transition from spreadsheet environments like Excel or Google Spreadsheets to Python." }, { "code": null, "e": 3373, "s": 3243, "text": "A neet Mito feature is that it shows how it calculates certain operations. So you can learn while clicking through your analysis." }, { "code": null, "e": 3524, "s": 3373, "text": "As an experienced pandas user, I use Mito for the initial Exploratory Data Analysis. With Mito I avoid writing the same pandas commands over and over." } ]
Predicting Housing Prices using a Scikit-Learn’s Random Forest Model | Towards Data Science
Having a housing price prediction model can be a very important tool for both the seller and the buyer as it can aid them in making well informed decision. For sellers, it may help them to determine the average price at which they should put their house for sale while for buyers, it may help them find out the right average price to purchase the house. To build a random forest regression model, which is able to predict the median value of houses. We will also briefly walk through some Exploratory Data Analysis, Feature Engineering and Hyperparameter tuning to improve the performance of our Random Forest model. Our Machine Learning Pipeline can be broadly summarized into the following task: Data AcquisitionData Pre-Processing and Exploratory Data AnalysisCreating a Base ModelFeature EngineeringHyperparameter TuningFinal Model Training and Evaluation Data Acquisition Data Pre-Processing and Exploratory Data Analysis Creating a Base Model Feature Engineering Hyperparameter Tuning Final Model Training and Evaluation We will be using the Boston Housing dataset: https://www.kaggle.com/c/boston-housing/data. #Importing the necessary libraries we will be using%load_ext autoreload%autoreload 2%matplotlib inlinefrom fastai.imports import *from fastai.structured import *from pandas_summary import DataFrameSummaryfrom sklearn.ensemble import RandomForestRegressorfrom IPython.display import displayfrom sklearn import metricsfrom sklearn.model_selection import RandomizedSearchCV#Loading the DatasetPATH = 'data/Boston Housing Dataset/'df_raw_train = pd.read_csv(f'{PATH}train.csv',low_memory = False)df_raw_test = pd.read_csv(f'{PATH}test.csv',low_memory = False) 2.1 Checking and handling if there are any missing data and outliers. df_raw_train.info Understanding the raw data: From the raw training dataset above: (a) There are 14 variables (13 independent variables — Features and 1 dependent variable — Target Variable). (b) The data types are either integers or floats.(c) No categorical data is present.(d) There are no missing values in our dataset. 2.2 As part of EDA, we will first try to determine the distribution of the dependent variable (MDEV). #Plot the distribution of MEDVplt.figure(figsize=(10, 6))sns.distplot(df_raw_train['MEDV'],bins=30) The values of MEDV follows a normal distribution with a mean of around 22. There are some outliers to the right. 2.3 Next, try to determine if there are any correlations between: (i) the independent variables themselves (ii) the independent variables and dependent variable To do this, let’s do a correlation heatmap. # Plot the correlation heatmapplt.figure(figsize=(14, 8))corr_matrix = df_raw_train.corr().round(2)sns.heatmap(data=corr_matrix,cmap='coolwarm',annot=True) (i) Correlation between independent variables:We would need to look out for features of multi-collinearity (i.e. features that are correlated with each other)as this will affect our relationship with the independent variable. Observe that RAD and TAX are highly correlated with each other (Correlation score: 0.92) while there are a couple of features which are somewhat correlated with one another with a correlation score of around 0.70 (INDUS and TAX, NOX and INDUS, AGE and DIS, AGE and INDUS). (ii) Correlation between independent variable and dependent variable:In order for our regression model to perform well, we ideally need to select those features that are highly correlated with our dependent variable (MEDV). We observe that both RM and LSTAT are correlated with MEDV with a correlation score of 0.66 and 0.74 respective. This can also be illustrated via the scatter plot . #Scatter plot to observe the correlations between the features that are highly correlated with MEDVtarget_var = df_raw_train['MEDV']plot1 = plt.figure(1)plt.scatter(df_raw_train['RM'],target_var)plt.xlabel('RM')plt.ylabel('MEDV')plot2 = plt.figure(2)plt.scatter(df_raw_train['LSTAT'],target_var)plt.xlabel('LSTAT')plt.ylabel('MEDV') From the scatter plot above:i) MEDV increases linearly with the RM. This makes sense as we would expect the median price of a house would be more generally more expensive as the number of rooms increases.ii) MEDV decreases linearly with LSTAT. This also makes sense since we can expect the median price of a house would generally be less expensive at places of lower status. Hold up! Before we create our base Random Forest Model, it very important to pick a suitable evaluation metric. 3.1 Picking the right evaluation metricPicking the right evaluation metric will help us to evaluate whether our model’s performance is good. For regression problems, the go-to evaluation metric is either Root Mean Square Error(RMSE) or Root Mean Square Logistic Error (RMLSE). RMSE: It is a measure of the squared difference between the prediction from our model and the actual value. where y’: predicted value, y: actual value RMSLE: It is a measure of the squared difference between the log of the prediction from our model and the log of the actual value. where y’: predicted value, y: actual value The RMSLE might be a better evaluation metric as (1) it is robust enough to deal with outliers, which we saw is present in our dataset (2) RMSLE incurs a larger penalty for underestimation of the actual value. If we put ourselves in the sellers perspective, we do not want to underestimate the price as it would result in losses. However, for this project we shall not take anyone’s side and shall choose the RMSE as the evaluation metric as we would be using the Random Forest model which is immune to outliers. 3.2 Creating our base Random Forest Model The next step would be to create a base model first without any feature engineering and hyperparameter tuning. We would use this model’s performance as a benchmark for comparison later on after we have done feature engineering and hyperparameter tuning later. The machine learning model we have chosen is the Random Forest Regression Model and here is why: Random Forests models require minimal data preparation. It is able to easily hand categorical, numerical and binary features without scaling or normalization required.Random Forests models can help us in performing implicit feature selections as they provide good indicators of the important features.Random Forest models are immune to outliers, which is present in our data, and they completely ignore statistical issues because unlike other machine learning models which perform much better after being normalized. Random Forests models require minimal data preparation. It is able to easily hand categorical, numerical and binary features without scaling or normalization required. Random Forests models can help us in performing implicit feature selections as they provide good indicators of the important features. Random Forest models are immune to outliers, which is present in our data, and they completely ignore statistical issues because unlike other machine learning models which perform much better after being normalized. We would like to create some helpful functions : # A function to split our training data into a training set to train our model and a validations set, which will be used to validate our model.def split_vals(a,n): return a[:n],a[n:]# Functions that will help us calculate the RMSE and print the score.def rmse(x,y): return math.sqrt(((x-y)**2).mean())def print_score(m): res =[rmse(m.predict(X_train),y_train),rmse(m.predict(X_valid),y_valid),m.score(X_train,y_train),m.score(X_valid,y_valid)] if hasattr(m,'oob_score_'):res.append(m.oob_score_) print(res) Splitting our training data further — Training data to train our Random Forest Model on and Validation data to validate the performance of our Model. n_valid = 100n_train = len(df_raw_train)-n_validX_train,X_valid = split_vals(df_raw_train.drop('MEDV',axis=1),n_train)y_train,y_valid = split_vals(df_raw_train['MEDV'],n_train)X_test = df_raw_test Creating and Fitting our Random Forest Model without feature selection and hyperparameter tuning. From our base Random Forest model, we already get a very decent result with the training RMSE to be 1.394 while the validation RMSE is 3.021. However, notice that our model seems to be ovefitting since the validation RMSE is around 3 times higher than the training RMSE. Hence, the baseline score to beat is validation RMSE 3.021! Feature Engineering and Hyperparameter tuning are essential steps within a Machine Learning Pipeline. 4.1 Determining the important featuresThe features in our data are directly influencing our Random Forest model and the result it achieves (i.e. the better the features we prepare and choose, the better final result we will achieve!). Hence we are going to explore and fine tune our Random Forest model by determining which of the features it had deemed to be important in our base model earlier. def feat_importance(m,df_train): importance = m.feature_importances_ importance = pd.DataFrame(importance,index=df_train.columns,columns=["Importance"]) return importance.sort_values(by=['Importance'],ascending=False)importance = feat_importance(m,X_train)importance[:] importance.plot(kind='barh') We observe that the most importance features in predicting the MDEV are LSTAT and RM. Recall that these two parameters were previously found to be highly correlated with the MDEV. 4.2 Discarding non-important features The next step will be to try and discard features with importance coefficient less than 0.01 and use it to model our Random Forest again to see if there is an improvement in our prediction results. #Discarding features with feature coefficients less than 0.01to_keep = importance[importance['Importance'] > 0.01].indexdf_raw_train_keep = df_raw_train[to_keep].copy()df_raw_test_keep = df_raw_test[to_keep].copy()#Splitting data into training and validation setX_train,X_valid = split_vals(df_raw_train_keep,n_train)# Fitting our Random Forest Model after discarding the less important features. Our Random Forest Model performs slightly better after removing some of the redundant features (i.e. 6 features!). We have obtain the top 9 most important features in determining the dependent variable MEDV (LSTAT, RM, DIS,CRIM, TAX, NOX, PTRATIO,NOX and AGE). Next, let’s see if there have been any changes to the rank of the features which are found to be important to our Random Forest Model. def feat_importance(m,df_raw_train_keep): importance = m.feature_importances_ importance =pd.DataFrame(importance,index=df_train.columns,columns=["Importance"]) return importance.sort_values(by=['Importance'],ascending=False)importance We observe that the most important features after removing the redundant features previously are still LSTAT and RM. We would like to explore how dropping each of the remaining features one by one would affect our overall score. Notice removing RM, LSTAT, DIS and CRIM results in a worse validation RMSE while removing AGE and PTRATIO gives us a slightly better score. Hence, we will further remove AGE and PTRATIO from the dataset before doing running the final model. 4.3 Removing Multi collinearity between independent features In 2.3(i), there are some features which are correlated to each other. To improve the model’s performance, we would ideally like to remove any multi collinearity between the features. To see how the features are correlated, we can plot a dendrogram diagram. #Dendogram plotfrom scipy.cluster import hierarchy as hccorr = np.round(scipy.stats.spearmanr(df_raw_train_keep).correlation,4)corr_condensed = hc.distance.squareform(1-corr)z = hc.linkage(corr_condensed,method='average')fig = plt.figure(figsize=(16,10))dendogram = hc.dendrogram(z,labels=df_raw_train_keep.columns,orientation='left',leaf_font_size=16)plt.show() From the dendrogram plot, in terms of ranking we can see that none of the features are measuring the same thing. The closest one we have in terms of ranking is NOX and CRIM. If there were features which were very close to each other in terms of ranking, the next step would have been to remove these features, one at a time, and see if our model could be simplified further without impacting our validation RMSE score. However for this case, we don’t need to. We have come to the final step (hooray!) before we can build our final Random Forest Model. Hyperparameter tuning is an iterative process whereby we select the best configurations of the hyperparameters that give us the best model performance output. For Random Forest model, we will focus on tuning 3 hyperparameters: (1) n_estimators : Number of trees to create and generalize over our Random Forest. Likely, the more trees we create, the better as it would enable us to sample more of the dataset and help us to generalize better. However, there would come a point whereby increasing the number of trees will only result in very small changes to our validation RMSE at the cost of computational power. (2) min_samples_leaf : This indicates the number of samples that will be in our leaf node. Each time we double the min_sample_leaf, we are removing one layer from the tree and halving the number of leaf nodes. Hence, the result of increasing min_samples_leaf is that each of our leaf nodes will have more than one sample inside them so when we calculate the average on that leaf node, it would be more stable although we will get a little less depth and have smaller number of nodes.Hence, though each tree will not be less predictive and less correlated, our model should be able to generalize better and prevent overfitting. (3) max_features : This indicates how many of the features to consider at each split. To optimize and search for the best hyperparameters, we will be using the Randomized Grid Search method! n_estimators = [int(x) for x in np.arange(start = 10, stop = 2000, step = 10)]max_features = [0.5,'auto', 'sqrt','log2']min_samples_leaf = [1, 2, 4]bootstrap = [True, False]random_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap}# First create the base model to tunem = RandomForestRegressor()# Fit the random search modelm_random = RandomizedSearchCV(estimator = m, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1)m_random.fit(X_train, y_train)m_random.best_params_ From our Randomized Grid Search, we found that the most optimized hyperparameters for our Random Forest Model to be those above. The last step — building our final mode. To do so, we are going to drop the AGE and PTRATIO feature as discussed earlier. We have obtained a validation RMSE score of 2.847, which is better than our original base model validation RMSE score of 3.021! In addition, the final validation R2 score is 0.87 and this is better than the validation R2 score of the base model of 0.85. The R2 score tells us how much our model is able to explain the variation in the dataset. Having a score of 0.87 indicates that our model can explain 87% of the variation in the dataset. Hence, we see the simple final model even with less input features performs much better! While we have created a much better model already, let’s take a step back and explore our results further. Previously, we observed there is a linear relationship between the median price of houses increases (MDEV) and number of rooms (RM). Let’s try to do ggplot. from pdpbox import pdpfrom plotnine import *ggplot(df_raw_train, aes('RM', 'MEDV'))+stat_smooth(se=True, method='loess') Based on the ggplot above, we observe that the relationship between the RM and MEDV is not what we expected. For instance, one would generally expect the price of the house to increase with the number of rooms. However, we see in a drop in price between 4 rooms and 5 rooms, likewise a price drop between 8 rooms to 9 rooms. The issue here is we are looking at univariate relationships and there are a lot of interactions between the features that are being lost in univariate plots. For instance, why did the price drop for houses that are 5 rooms as compared to 4 rooms and the price of a 6 room house is almost similar to a 4 room house? Hence, to find the true relationship between RM and MEDV, we would need to do a partial independence plot (i.e. assuming that all other features being equal, how does the price of the house vary with the number of rooms) to see the true relationship. def plot_pdp(feat,clusters=None,feat_name=None): feat_name = feat_name or feat p = pdp.pdp_isolate(m,X_train,feat) return pdp.pdp_plot(p,feat_name,plot_lines=True,cluster=clusters is not None,n_cluster_centers = clusters)plot_pdp('RM') Notice from the Partial Dependence Plot (PDP) above, after removing all other externalities we observe that the relationship between the RM and MEDV is almost a straight line (i.e. roughly linear), which is what we would expect. The yellow line represents the average MEDV of all the transactions. Now let’s explore how LSTAT and RM influences the median housing prices. feats = ['LSTAT','RM']p = pdp.pdp_interact(m,X_train,feats)pdp.pdp_interact_plot(p,feats) Hence, looking at the PDP plots, we can safely conclude that the number of rooms (RM) influences the median housing prices (MEDV) linearly. The status of the population (LSTAT) influences MEDV inversely. We have built a Random Forest model which has validation RMSE score of 3.021 and validation R2 score of 0.87. We have also determined from our Random Forest model the key features that affects the median housing prices (MEDV) in Boston are (1) LSAT : Percentage of the lower population status (2) RM: The average number of rooms per dwelling (3) NOX: Concentration of Nitrogen Oxide (4) CRIM: The crime rate per capita by town. The final model we have built is far from perfect. For instance, observe that the training R2 score in our final model is much higher 0.98 than our validation R2 score of 0.87. This indicates the final model is able to explain 98% of the variations in the training data while only explain 87% of the variation in the validation data (i.e. the final model is still overfitting the training data and does not generalize as well to the validation data). One simple way to address overfitting could be to try to increase the size of our dataset to train our model on. Currently, we only have 406 entries in our dataset which is simply insufficient. Congratulations and thank you for making it to the end. I sincerely hope you have learnt something new! Happy learning!😬
[ { "code": null, "e": 525, "s": 171, "text": "Having a housing price prediction model can be a very important tool for both the seller and the buyer as it can aid them in making well informed decision. For sellers, it may help them to determine the average price at which they should put their house for sale while for buyers, it may help them find out the right average price to purchase the house." }, { "code": null, "e": 788, "s": 525, "text": "To build a random forest regression model, which is able to predict the median value of houses. We will also briefly walk through some Exploratory Data Analysis, Feature Engineering and Hyperparameter tuning to improve the performance of our Random Forest model." }, { "code": null, "e": 869, "s": 788, "text": "Our Machine Learning Pipeline can be broadly summarized into the following task:" }, { "code": null, "e": 1031, "s": 869, "text": "Data AcquisitionData Pre-Processing and Exploratory Data AnalysisCreating a Base ModelFeature EngineeringHyperparameter TuningFinal Model Training and Evaluation" }, { "code": null, "e": 1048, "s": 1031, "text": "Data Acquisition" }, { "code": null, "e": 1098, "s": 1048, "text": "Data Pre-Processing and Exploratory Data Analysis" }, { "code": null, "e": 1120, "s": 1098, "text": "Creating a Base Model" }, { "code": null, "e": 1140, "s": 1120, "text": "Feature Engineering" }, { "code": null, "e": 1162, "s": 1140, "text": "Hyperparameter Tuning" }, { "code": null, "e": 1198, "s": 1162, "text": "Final Model Training and Evaluation" }, { "code": null, "e": 1289, "s": 1198, "text": "We will be using the Boston Housing dataset: https://www.kaggle.com/c/boston-housing/data." }, { "code": null, "e": 1845, "s": 1289, "text": "#Importing the necessary libraries we will be using%load_ext autoreload%autoreload 2%matplotlib inlinefrom fastai.imports import *from fastai.structured import *from pandas_summary import DataFrameSummaryfrom sklearn.ensemble import RandomForestRegressorfrom IPython.display import displayfrom sklearn import metricsfrom sklearn.model_selection import RandomizedSearchCV#Loading the DatasetPATH = 'data/Boston Housing Dataset/'df_raw_train = pd.read_csv(f'{PATH}train.csv',low_memory = False)df_raw_test = pd.read_csv(f'{PATH}test.csv',low_memory = False)" }, { "code": null, "e": 1915, "s": 1845, "text": "2.1 Checking and handling if there are any missing data and outliers." }, { "code": null, "e": 1933, "s": 1915, "text": "df_raw_train.info" }, { "code": null, "e": 1961, "s": 1933, "text": "Understanding the raw data:" }, { "code": null, "e": 1998, "s": 1961, "text": "From the raw training dataset above:" }, { "code": null, "e": 2239, "s": 1998, "text": "(a) There are 14 variables (13 independent variables — Features and 1 dependent variable — Target Variable). (b) The data types are either integers or floats.(c) No categorical data is present.(d) There are no missing values in our dataset." }, { "code": null, "e": 2341, "s": 2239, "text": "2.2 As part of EDA, we will first try to determine the distribution of the dependent variable (MDEV)." }, { "code": null, "e": 2441, "s": 2341, "text": "#Plot the distribution of MEDVplt.figure(figsize=(10, 6))sns.distplot(df_raw_train['MEDV'],bins=30)" }, { "code": null, "e": 2554, "s": 2441, "text": "The values of MEDV follows a normal distribution with a mean of around 22. There are some outliers to the right." }, { "code": null, "e": 2716, "s": 2554, "text": "2.3 Next, try to determine if there are any correlations between: (i) the independent variables themselves (ii) the independent variables and dependent variable" }, { "code": null, "e": 2760, "s": 2716, "text": "To do this, let’s do a correlation heatmap." }, { "code": null, "e": 2916, "s": 2760, "text": "# Plot the correlation heatmapplt.figure(figsize=(14, 8))corr_matrix = df_raw_train.corr().round(2)sns.heatmap(data=corr_matrix,cmap='coolwarm',annot=True)" }, { "code": null, "e": 3142, "s": 2916, "text": "(i) Correlation between independent variables:We would need to look out for features of multi-collinearity (i.e. features that are correlated with each other)as this will affect our relationship with the independent variable." }, { "code": null, "e": 3415, "s": 3142, "text": "Observe that RAD and TAX are highly correlated with each other (Correlation score: 0.92) while there are a couple of features which are somewhat correlated with one another with a correlation score of around 0.70 (INDUS and TAX, NOX and INDUS, AGE and DIS, AGE and INDUS)." }, { "code": null, "e": 3639, "s": 3415, "text": "(ii) Correlation between independent variable and dependent variable:In order for our regression model to perform well, we ideally need to select those features that are highly correlated with our dependent variable (MEDV)." }, { "code": null, "e": 3804, "s": 3639, "text": "We observe that both RM and LSTAT are correlated with MEDV with a correlation score of 0.66 and 0.74 respective. This can also be illustrated via the scatter plot ." }, { "code": null, "e": 4137, "s": 3804, "text": "#Scatter plot to observe the correlations between the features that are highly correlated with MEDVtarget_var = df_raw_train['MEDV']plot1 = plt.figure(1)plt.scatter(df_raw_train['RM'],target_var)plt.xlabel('RM')plt.ylabel('MEDV')plot2 = plt.figure(2)plt.scatter(df_raw_train['LSTAT'],target_var)plt.xlabel('LSTAT')plt.ylabel('MEDV')" }, { "code": null, "e": 4512, "s": 4137, "text": "From the scatter plot above:i) MEDV increases linearly with the RM. This makes sense as we would expect the median price of a house would be more generally more expensive as the number of rooms increases.ii) MEDV decreases linearly with LSTAT. This also makes sense since we can expect the median price of a house would generally be less expensive at places of lower status." }, { "code": null, "e": 4624, "s": 4512, "text": "Hold up! Before we create our base Random Forest Model, it very important to pick a suitable evaluation metric." }, { "code": null, "e": 4901, "s": 4624, "text": "3.1 Picking the right evaluation metricPicking the right evaluation metric will help us to evaluate whether our model’s performance is good. For regression problems, the go-to evaluation metric is either Root Mean Square Error(RMSE) or Root Mean Square Logistic Error (RMLSE)." }, { "code": null, "e": 5009, "s": 4901, "text": "RMSE: It is a measure of the squared difference between the prediction from our model and the actual value." }, { "code": null, "e": 5052, "s": 5009, "text": "where y’: predicted value, y: actual value" }, { "code": null, "e": 5183, "s": 5052, "text": "RMSLE: It is a measure of the squared difference between the log of the prediction from our model and the log of the actual value." }, { "code": null, "e": 5226, "s": 5183, "text": "where y’: predicted value, y: actual value" }, { "code": null, "e": 5739, "s": 5226, "text": "The RMSLE might be a better evaluation metric as (1) it is robust enough to deal with outliers, which we saw is present in our dataset (2) RMSLE incurs a larger penalty for underestimation of the actual value. If we put ourselves in the sellers perspective, we do not want to underestimate the price as it would result in losses. However, for this project we shall not take anyone’s side and shall choose the RMSE as the evaluation metric as we would be using the Random Forest model which is immune to outliers." }, { "code": null, "e": 5781, "s": 5739, "text": "3.2 Creating our base Random Forest Model" }, { "code": null, "e": 6041, "s": 5781, "text": "The next step would be to create a base model first without any feature engineering and hyperparameter tuning. We would use this model’s performance as a benchmark for comparison later on after we have done feature engineering and hyperparameter tuning later." }, { "code": null, "e": 6138, "s": 6041, "text": "The machine learning model we have chosen is the Random Forest Regression Model and here is why:" }, { "code": null, "e": 6655, "s": 6138, "text": "Random Forests models require minimal data preparation. It is able to easily hand categorical, numerical and binary features without scaling or normalization required.Random Forests models can help us in performing implicit feature selections as they provide good indicators of the important features.Random Forest models are immune to outliers, which is present in our data, and they completely ignore statistical issues because unlike other machine learning models which perform much better after being normalized." }, { "code": null, "e": 6823, "s": 6655, "text": "Random Forests models require minimal data preparation. It is able to easily hand categorical, numerical and binary features without scaling or normalization required." }, { "code": null, "e": 6958, "s": 6823, "text": "Random Forests models can help us in performing implicit feature selections as they provide good indicators of the important features." }, { "code": null, "e": 7174, "s": 6958, "text": "Random Forest models are immune to outliers, which is present in our data, and they completely ignore statistical issues because unlike other machine learning models which perform much better after being normalized." }, { "code": null, "e": 7223, "s": 7174, "text": "We would like to create some helpful functions :" }, { "code": null, "e": 7746, "s": 7223, "text": "# A function to split our training data into a training set to train our model and a validations set, which will be used to validate our model.def split_vals(a,n): return a[:n],a[n:]# Functions that will help us calculate the RMSE and print the score.def rmse(x,y): return math.sqrt(((x-y)**2).mean())def print_score(m): res =[rmse(m.predict(X_train),y_train),rmse(m.predict(X_valid),y_valid),m.score(X_train,y_train),m.score(X_valid,y_valid)] if hasattr(m,'oob_score_'):res.append(m.oob_score_) print(res)" }, { "code": null, "e": 7896, "s": 7746, "text": "Splitting our training data further — Training data to train our Random Forest Model on and Validation data to validate the performance of our Model." }, { "code": null, "e": 8093, "s": 7896, "text": "n_valid = 100n_train = len(df_raw_train)-n_validX_train,X_valid = split_vals(df_raw_train.drop('MEDV',axis=1),n_train)y_train,y_valid = split_vals(df_raw_train['MEDV'],n_train)X_test = df_raw_test" }, { "code": null, "e": 8191, "s": 8093, "text": "Creating and Fitting our Random Forest Model without feature selection and hyperparameter tuning." }, { "code": null, "e": 8462, "s": 8191, "text": "From our base Random Forest model, we already get a very decent result with the training RMSE to be 1.394 while the validation RMSE is 3.021. However, notice that our model seems to be ovefitting since the validation RMSE is around 3 times higher than the training RMSE." }, { "code": null, "e": 8522, "s": 8462, "text": "Hence, the baseline score to beat is validation RMSE 3.021!" }, { "code": null, "e": 8624, "s": 8522, "text": "Feature Engineering and Hyperparameter tuning are essential steps within a Machine Learning Pipeline." }, { "code": null, "e": 9021, "s": 8624, "text": "4.1 Determining the important featuresThe features in our data are directly influencing our Random Forest model and the result it achieves (i.e. the better the features we prepare and choose, the better final result we will achieve!). Hence we are going to explore and fine tune our Random Forest model by determining which of the features it had deemed to be important in our base model earlier." }, { "code": null, "e": 9300, "s": 9021, "text": "def feat_importance(m,df_train): importance = m.feature_importances_ importance = pd.DataFrame(importance,index=df_train.columns,columns=[\"Importance\"]) return importance.sort_values(by=['Importance'],ascending=False)importance = feat_importance(m,X_train)importance[:]" }, { "code": null, "e": 9329, "s": 9300, "text": "importance.plot(kind='barh')" }, { "code": null, "e": 9509, "s": 9329, "text": "We observe that the most importance features in predicting the MDEV are LSTAT and RM. Recall that these two parameters were previously found to be highly correlated with the MDEV." }, { "code": null, "e": 9745, "s": 9509, "text": "4.2 Discarding non-important features The next step will be to try and discard features with importance coefficient less than 0.01 and use it to model our Random Forest again to see if there is an improvement in our prediction results." }, { "code": null, "e": 10142, "s": 9745, "text": "#Discarding features with feature coefficients less than 0.01to_keep = importance[importance['Importance'] > 0.01].indexdf_raw_train_keep = df_raw_train[to_keep].copy()df_raw_test_keep = df_raw_test[to_keep].copy()#Splitting data into training and validation setX_train,X_valid = split_vals(df_raw_train_keep,n_train)# Fitting our Random Forest Model after discarding the less important features." }, { "code": null, "e": 10403, "s": 10142, "text": "Our Random Forest Model performs slightly better after removing some of the redundant features (i.e. 6 features!). We have obtain the top 9 most important features in determining the dependent variable MEDV (LSTAT, RM, DIS,CRIM, TAX, NOX, PTRATIO,NOX and AGE)." }, { "code": null, "e": 10538, "s": 10403, "text": "Next, let’s see if there have been any changes to the rank of the features which are found to be important to our Random Forest Model." }, { "code": null, "e": 10783, "s": 10538, "text": "def feat_importance(m,df_raw_train_keep): importance = m.feature_importances_ importance =pd.DataFrame(importance,index=df_train.columns,columns=[\"Importance\"]) return importance.sort_values(by=['Importance'],ascending=False)importance" }, { "code": null, "e": 11012, "s": 10783, "text": "We observe that the most important features after removing the redundant features previously are still LSTAT and RM. We would like to explore how dropping each of the remaining features one by one would affect our overall score." }, { "code": null, "e": 11253, "s": 11012, "text": "Notice removing RM, LSTAT, DIS and CRIM results in a worse validation RMSE while removing AGE and PTRATIO gives us a slightly better score. Hence, we will further remove AGE and PTRATIO from the dataset before doing running the final model." }, { "code": null, "e": 11314, "s": 11253, "text": "4.3 Removing Multi collinearity between independent features" }, { "code": null, "e": 11498, "s": 11314, "text": "In 2.3(i), there are some features which are correlated to each other. To improve the model’s performance, we would ideally like to remove any multi collinearity between the features." }, { "code": null, "e": 11572, "s": 11498, "text": "To see how the features are correlated, we can plot a dendrogram diagram." }, { "code": null, "e": 11935, "s": 11572, "text": "#Dendogram plotfrom scipy.cluster import hierarchy as hccorr = np.round(scipy.stats.spearmanr(df_raw_train_keep).correlation,4)corr_condensed = hc.distance.squareform(1-corr)z = hc.linkage(corr_condensed,method='average')fig = plt.figure(figsize=(16,10))dendogram = hc.dendrogram(z,labels=df_raw_train_keep.columns,orientation='left',leaf_font_size=16)plt.show()" }, { "code": null, "e": 12109, "s": 11935, "text": "From the dendrogram plot, in terms of ranking we can see that none of the features are measuring the same thing. The closest one we have in terms of ranking is NOX and CRIM." }, { "code": null, "e": 12395, "s": 12109, "text": "If there were features which were very close to each other in terms of ranking, the next step would have been to remove these features, one at a time, and see if our model could be simplified further without impacting our validation RMSE score. However for this case, we don’t need to." }, { "code": null, "e": 12487, "s": 12395, "text": "We have come to the final step (hooray!) before we can build our final Random Forest Model." }, { "code": null, "e": 12714, "s": 12487, "text": "Hyperparameter tuning is an iterative process whereby we select the best configurations of the hyperparameters that give us the best model performance output. For Random Forest model, we will focus on tuning 3 hyperparameters:" }, { "code": null, "e": 13100, "s": 12714, "text": "(1) n_estimators : Number of trees to create and generalize over our Random Forest. Likely, the more trees we create, the better as it would enable us to sample more of the dataset and help us to generalize better. However, there would come a point whereby increasing the number of trees will only result in very small changes to our validation RMSE at the cost of computational power." }, { "code": null, "e": 13727, "s": 13100, "text": "(2) min_samples_leaf : This indicates the number of samples that will be in our leaf node. Each time we double the min_sample_leaf, we are removing one layer from the tree and halving the number of leaf nodes. Hence, the result of increasing min_samples_leaf is that each of our leaf nodes will have more than one sample inside them so when we calculate the average on that leaf node, it would be more stable although we will get a little less depth and have smaller number of nodes.Hence, though each tree will not be less predictive and less correlated, our model should be able to generalize better and prevent overfitting." }, { "code": null, "e": 13813, "s": 13727, "text": "(3) max_features : This indicates how many of the features to consider at each split." }, { "code": null, "e": 13918, "s": 13813, "text": "To optimize and search for the best hyperparameters, we will be using the Randomized Grid Search method!" }, { "code": null, "e": 14556, "s": 13918, "text": "n_estimators = [int(x) for x in np.arange(start = 10, stop = 2000, step = 10)]max_features = [0.5,'auto', 'sqrt','log2']min_samples_leaf = [1, 2, 4]bootstrap = [True, False]random_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap}# First create the base model to tunem = RandomForestRegressor()# Fit the random search modelm_random = RandomizedSearchCV(estimator = m, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1)m_random.fit(X_train, y_train)m_random.best_params_" }, { "code": null, "e": 14685, "s": 14556, "text": "From our Randomized Grid Search, we found that the most optimized hyperparameters for our Random Forest Model to be those above." }, { "code": null, "e": 14807, "s": 14685, "text": "The last step — building our final mode. To do so, we are going to drop the AGE and PTRATIO feature as discussed earlier." }, { "code": null, "e": 14935, "s": 14807, "text": "We have obtained a validation RMSE score of 2.847, which is better than our original base model validation RMSE score of 3.021!" }, { "code": null, "e": 15248, "s": 14935, "text": "In addition, the final validation R2 score is 0.87 and this is better than the validation R2 score of the base model of 0.85. The R2 score tells us how much our model is able to explain the variation in the dataset. Having a score of 0.87 indicates that our model can explain 87% of the variation in the dataset." }, { "code": null, "e": 15337, "s": 15248, "text": "Hence, we see the simple final model even with less input features performs much better!" }, { "code": null, "e": 15444, "s": 15337, "text": "While we have created a much better model already, let’s take a step back and explore our results further." }, { "code": null, "e": 15577, "s": 15444, "text": "Previously, we observed there is a linear relationship between the median price of houses increases (MDEV) and number of rooms (RM)." }, { "code": null, "e": 15601, "s": 15577, "text": "Let’s try to do ggplot." }, { "code": null, "e": 15722, "s": 15601, "text": "from pdpbox import pdpfrom plotnine import *ggplot(df_raw_train, aes('RM', 'MEDV'))+stat_smooth(se=True, method='loess')" }, { "code": null, "e": 16047, "s": 15722, "text": "Based on the ggplot above, we observe that the relationship between the RM and MEDV is not what we expected. For instance, one would generally expect the price of the house to increase with the number of rooms. However, we see in a drop in price between 4 rooms and 5 rooms, likewise a price drop between 8 rooms to 9 rooms." }, { "code": null, "e": 16363, "s": 16047, "text": "The issue here is we are looking at univariate relationships and there are a lot of interactions between the features that are being lost in univariate plots. For instance, why did the price drop for houses that are 5 rooms as compared to 4 rooms and the price of a 6 room house is almost similar to a 4 room house?" }, { "code": null, "e": 16614, "s": 16363, "text": "Hence, to find the true relationship between RM and MEDV, we would need to do a partial independence plot (i.e. assuming that all other features being equal, how does the price of the house vary with the number of rooms) to see the true relationship." }, { "code": null, "e": 16859, "s": 16614, "text": "def plot_pdp(feat,clusters=None,feat_name=None): feat_name = feat_name or feat p = pdp.pdp_isolate(m,X_train,feat) return pdp.pdp_plot(p,feat_name,plot_lines=True,cluster=clusters is not None,n_cluster_centers = clusters)plot_pdp('RM')" }, { "code": null, "e": 17157, "s": 16859, "text": "Notice from the Partial Dependence Plot (PDP) above, after removing all other externalities we observe that the relationship between the RM and MEDV is almost a straight line (i.e. roughly linear), which is what we would expect. The yellow line represents the average MEDV of all the transactions." }, { "code": null, "e": 17230, "s": 17157, "text": "Now let’s explore how LSTAT and RM influences the median housing prices." }, { "code": null, "e": 17320, "s": 17230, "text": "feats = ['LSTAT','RM']p = pdp.pdp_interact(m,X_train,feats)pdp.pdp_interact_plot(p,feats)" }, { "code": null, "e": 17524, "s": 17320, "text": "Hence, looking at the PDP plots, we can safely conclude that the number of rooms (RM) influences the median housing prices (MEDV) linearly. The status of the population (LSTAT) influences MEDV inversely." }, { "code": null, "e": 17634, "s": 17524, "text": "We have built a Random Forest model which has validation RMSE score of 3.021 and validation R2 score of 0.87." }, { "code": null, "e": 17952, "s": 17634, "text": "We have also determined from our Random Forest model the key features that affects the median housing prices (MEDV) in Boston are (1) LSAT : Percentage of the lower population status (2) RM: The average number of rooms per dwelling (3) NOX: Concentration of Nitrogen Oxide (4) CRIM: The crime rate per capita by town." }, { "code": null, "e": 18403, "s": 17952, "text": "The final model we have built is far from perfect. For instance, observe that the training R2 score in our final model is much higher 0.98 than our validation R2 score of 0.87. This indicates the final model is able to explain 98% of the variations in the training data while only explain 87% of the variation in the validation data (i.e. the final model is still overfitting the training data and does not generalize as well to the validation data)." }, { "code": null, "e": 18597, "s": 18403, "text": "One simple way to address overfitting could be to try to increase the size of our dataset to train our model on. Currently, we only have 406 entries in our dataset which is simply insufficient." } ]
How to get the Android Emulator's IP address?
This example demonstrates how do I get the Android Emulator’s IP address. 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:textSize="16sp" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" android:layout_centerInParent="true"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnGetIPAddress" android:text="Get IP Address" android:layout_below="@id/textView" android:layout_marginTop="10dp" android:layout_centerInParent="true"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.net.wifi.WifiManager; import android.os.Bundle; import android.text.format.Formatter; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button button; TextView textview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textview = findViewById(R.id.textView); button = findViewById(R.id.btnGetIPAddress); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GetIPAddress(); } }); } private void GetIPAddress() { WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); assert wifiManager != null; String ip = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress()); textview.setText(String.format("IP Address: %s", ip)); } } 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.ACCESS_WIFI_STATE"/> <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 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 demonstrates how do I get the Android Emulator’s IP address." }, { "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": 2156, "s": 1330, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" 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:textSize=\"16sp\"\n android:textStyle=\"bold\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textView\"\n android:layout_centerInParent=\"true\"/>\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/btnGetIPAddress\"\n android:text=\"Get IP Address\"\n android:layout_below=\"@id/textView\"\n android:layout_marginTop=\"10dp\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 2213, "s": 2156, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3296, "s": 2213, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.net.wifi.WifiManager;\nimport android.os.Bundle;\nimport android.text.format.Formatter;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n Button button;\n TextView textview;\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.btnGetIPAddress);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n GetIPAddress();\n }\n });\n }\n private void GetIPAddress() {\n WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); assert wifiManager != null;\n String ip = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());\n textview.setText(String.format(\"IP Address: %s\", ip));\n }\n}" }, { "code": null, "e": 3351, "s": 3296, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4163, "s": 3351, "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.ACCESS_WIFI_STATE\"/>\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": 4511, "s": 4163, "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": 4551, "s": 4511, "text": "Click here to download the project code" } ]
Data Structure - Priority Queue
Priority Queue is more specialized data structure than Queue. Like ordinary queue, priority queue has same method but with a major difference. In Priority queue items are ordered by key value so that item with the lowest value of key is at front and item with the highest value of key is at rear or vice versa. So we're assigned priority to item based on its key value. Lower the value, higher the priority. Following are the principal methods of a Priority Queue. insert / enqueue − add an item to the rear of the queue. insert / enqueue − add an item to the rear of the queue. remove / dequeue − remove an item from the front of the queue. remove / dequeue − remove an item from the front of the queue. We're going to implement Queue using array in this article. There is few more operations supported by queue which are following. Peek − get the element at front of the queue. Peek − get the element at front of the queue. isFull − check if queue is full. isFull − check if queue is full. isEmpty − check if queue is empty. isEmpty − check if queue is empty. Whenever an element is inserted into queue, priority queue inserts the item according to its order. Here we're assuming that data with high value has low priority. void insert(int data){ int i = 0; if(!isFull()){ // if queue is empty, insert the data if(itemCount == 0){ intArray[itemCount++] = data; }else{ // start from the right end of the queue for(i = itemCount - 1; i >= 0; i-- ){ // if data is larger, shift existing item to right end if(data > intArray[i]){ intArray[i+1] = intArray[i]; }else{ break; } } // insert the data intArray[i+1] = data; itemCount++; } } } Whenever an element is to be removed from queue, queue get the element using item count. Once element is removed. Item count is reduced by one. int removeData(){ return intArray[--itemCount]; } PriorityQueueDemo.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #define MAX 6 int intArray[MAX]; int itemCount = 0; int peek(){ return intArray[itemCount - 1]; } bool isEmpty(){ return itemCount == 0; } bool isFull(){ return itemCount == MAX; } int size(){ return itemCount; } void insert(int data){ int i = 0; if(!isFull()){ // if queue is empty, insert the data if(itemCount == 0){ intArray[itemCount++] = data; }else{ // start from the right end of the queue for(i = itemCount - 1; i >= 0; i-- ){ // if data is larger, shift existing item to right end if(data > intArray[i]){ intArray[i+1] = intArray[i]; }else{ break; } } // insert the data intArray[i+1] = data; itemCount++; } } } int removeData(){ return intArray[--itemCount]; } int main() { /* insert 5 items */ insert(3); insert(5); insert(9); insert(1); insert(12); // ------------------ // index : 0 1 2 3 4 // ------------------ // queue : 12 9 5 3 1 insert(15); // --------------------- // index : 0 1 2 3 4 5 // --------------------- // queue : 15 12 9 5 3 1 if(isFull()){ printf("Queue is full!\n"); } // remove one item int num = removeData(); printf("Element removed: %d\n",num); // --------------------- // index : 0 1 2 3 4 // --------------------- // queue : 15 12 9 5 3 // insert more items insert(16); // ---------------------- // index : 0 1 2 3 4 5 // ---------------------- // queue : 16 15 12 9 5 3 // As queue is full, elements will not be inserted. insert(17); insert(18); // ---------------------- // index : 0 1 2 3 4 5 // ---------------------- // queue : 16 15 12 9 5 3 printf("Element at front: %d\n",peek()); printf("----------------------\n"); printf("index : 5 4 3 2 1 0\n"); printf("----------------------\n"); printf("Queue: "); while(!isEmpty()){ int n = removeData(); printf("%d ",n); } } If we compile and run the above program then it would produce following result − Queue is full! Element removed: 1 Element at front: 3 ---------------------- index : 5 4 3 2 1 0 ---------------------- Queue: 3 5 9 12 15 16 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 3045, "s": 2580, "text": "Priority Queue is more specialized data structure than Queue. Like ordinary queue, priority queue has same method but with a major difference. In Priority queue items are ordered by key value so that item with the lowest value of key is at front and item with the highest value of key is at rear or vice versa. So we're assigned priority to item based on its key value. Lower the value, higher the priority. Following are the principal methods of a Priority Queue." }, { "code": null, "e": 3102, "s": 3045, "text": "insert / enqueue − add an item to the rear of the queue." }, { "code": null, "e": 3159, "s": 3102, "text": "insert / enqueue − add an item to the rear of the queue." }, { "code": null, "e": 3222, "s": 3159, "text": "remove / dequeue − remove an item from the front of the queue." }, { "code": null, "e": 3285, "s": 3222, "text": "remove / dequeue − remove an item from the front of the queue." }, { "code": null, "e": 3414, "s": 3285, "text": "We're going to implement Queue using array in this article. There is few more operations supported by queue which are following." }, { "code": null, "e": 3460, "s": 3414, "text": "Peek − get the element at front of the queue." }, { "code": null, "e": 3506, "s": 3460, "text": "Peek − get the element at front of the queue." }, { "code": null, "e": 3539, "s": 3506, "text": "isFull − check if queue is full." }, { "code": null, "e": 3572, "s": 3539, "text": "isFull − check if queue is full." }, { "code": null, "e": 3607, "s": 3572, "text": "isEmpty − check if queue is empty." }, { "code": null, "e": 3642, "s": 3607, "text": "isEmpty − check if queue is empty." }, { "code": null, "e": 3806, "s": 3642, "text": "Whenever an element is inserted into queue, priority queue inserts the item according to its order. Here we're assuming that data with high value has low priority." }, { "code": null, "e": 4420, "s": 3806, "text": "void insert(int data){\n int i = 0;\n\n if(!isFull()){\n // if queue is empty, insert the data \n\t\t\n if(itemCount == 0){\n intArray[itemCount++] = data; \n }else{\n // start from the right end of the queue \n for(i = itemCount - 1; i >= 0; i-- ){\n // if data is larger, shift existing item to right end \n if(data > intArray[i]){\n intArray[i+1] = intArray[i];\n }else{\n break;\n } \n } \n // insert the data \n intArray[i+1] = data;\n itemCount++;\n }\n }\n}" }, { "code": null, "e": 4564, "s": 4420, "text": "Whenever an element is to be removed from queue, queue get the element using item count. Once element is removed. Item count is reduced by one." }, { "code": null, "e": 4618, "s": 4564, "text": "int removeData(){\n return intArray[--itemCount]; \n}" }, { "code": null, "e": 4638, "s": 4618, "text": "PriorityQueueDemo.c" }, { "code": null, "e": 6871, "s": 4638, "text": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#define MAX 6\n\nint intArray[MAX];\nint itemCount = 0;\n\nint peek(){\n return intArray[itemCount - 1];\n}\n\nbool isEmpty(){\n return itemCount == 0;\n}\n\nbool isFull(){\n return itemCount == MAX;\n}\n\nint size(){\n return itemCount;\n} \n\nvoid insert(int data){\n int i = 0;\n\n if(!isFull()){\n // if queue is empty, insert the data \n if(itemCount == 0){\n intArray[itemCount++] = data; \n }else{\n // start from the right end of the queue \n\t\t\t\n for(i = itemCount - 1; i >= 0; i-- ){\n // if data is larger, shift existing item to right end \n if(data > intArray[i]){\n intArray[i+1] = intArray[i];\n }else{\n break;\n } \n } \n\t\t\t\n // insert the data \n intArray[i+1] = data;\n itemCount++;\n }\n }\n}\n\nint removeData(){\n return intArray[--itemCount]; \n}\n\nint main() {\n /* insert 5 items */\n insert(3);\n insert(5);\n insert(9);\n insert(1);\n insert(12);\n\n // ------------------\n // index : 0 1 2 3 4 \n // ------------------\n // queue : 12 9 5 3 1 \n insert(15);\n\n // ---------------------\n // index : 0 1 2 3 4 5 \n // ---------------------\n // queue : 15 12 9 5 3 1\n\t\n if(isFull()){\n printf(\"Queue is full!\\n\"); \n }\n\n // remove one item \n int num = removeData();\n printf(\"Element removed: %d\\n\",num);\n\t\n // ---------------------\n // index : 0 1 2 3 4 \n // ---------------------\n // queue : 15 12 9 5 3 \n\n // insert more items\n insert(16);\n\n // ----------------------\n // index : 0 1 2 3 4 5\n // ----------------------\n // queue : 16 15 12 9 5 3\n\n // As queue is full, elements will not be inserted. \n insert(17);\n insert(18);\n\n // ----------------------\n // index : 0 1 2 3 4 5\n // ----------------------\n // queue : 16 15 12 9 5 3\n printf(\"Element at front: %d\\n\",peek());\n\n printf(\"----------------------\\n\");\n printf(\"index : 5 4 3 2 1 0\\n\");\n printf(\"----------------------\\n\");\n printf(\"Queue: \");\n\t\n while(!isEmpty()){\n int n = removeData(); \n printf(\"%d \",n);\n } \n}" }, { "code": null, "e": 6952, "s": 6871, "text": "If we compile and run the above program then it would produce following result −" }, { "code": null, "e": 7095, "s": 6952, "text": "Queue is full!\nElement removed: 1\nElement at front: 3\n----------------------\nindex : 5 4 3 2 1 0\n----------------------\nQueue: 3 5 9 12 15 16\n" }, { "code": null, "e": 7130, "s": 7095, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7142, "s": 7130, "text": " Ravi Kiran" }, { "code": null, "e": 7177, "s": 7142, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 7196, "s": 7177, "text": " Arnab Chakraborty" }, { "code": null, "e": 7231, "s": 7196, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 7246, "s": 7231, "text": " Parth Panjabi" }, { "code": null, "e": 7279, "s": 7246, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 7298, "s": 7279, "text": " Arnab Chakraborty" }, { "code": null, "e": 7332, "s": 7298, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 7360, "s": 7332, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7396, "s": 7360, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 7424, "s": 7396, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7431, "s": 7424, "text": " Print" }, { "code": null, "e": 7442, "s": 7431, "text": " Add Notes" } ]
How to set the alignment of the JLabel content along the Y axis in the bottom with Java
Set the alignment of the label’s content along the Y axis on the bottom, use the setVerticalAlignment() method and set the location. Let us first set a label component. We have set the label background color as well so that we can check the alignment of the label’s content properly − JLabel label = new JLabel("Project Name"); label.setPreferredSize(new Dimension(190, 100)); label.setOpaque(true); label.setBackground(Color.GREEN); label.setForeground(Color.WHITE); Now, we will align the label content along the Y axis on the bottom by seeting location as BOTTOM − label.setVerticalAlignment(JLabel.BOTTOM); The following is an example to set the alignment of the label content along the Y axis in the bottom − package my; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.WindowConstants; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Frame"); frame.setLayout(new FlowLayout()); JLabel label = new JLabel("Project Name"); label.setPreferredSize(new Dimension(190, 100)); label.setOpaque(true); label.setBackground(Color.GREEN); label.setForeground(Color.WHITE); Font font = new Font("Serif", Font.BOLD, 18); label.setFont(font); label.setVerticalAlignment(JLabel.BOTTOM); JTextArea text = new JTextArea(); text.setText("Amit Learning Application"); font = new Font("Serif", Font.BOLD, 13); text.setFont(font); frame.add(label); frame.add(text); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(500, 300); frame.setVisible(true); } }
[ { "code": null, "e": 1348, "s": 1062, "text": "Set the alignment of the label’s content along the Y axis on the bottom, use the setVerticalAlignment() method and set the location. Let us first set a label component. We have set the label background color as well so that we can check the alignment of the label’s content properly −" }, { "code": null, "e": 1531, "s": 1348, "text": "JLabel label = new JLabel(\"Project Name\");\nlabel.setPreferredSize(new Dimension(190, 100));\nlabel.setOpaque(true);\nlabel.setBackground(Color.GREEN);\nlabel.setForeground(Color.WHITE);" }, { "code": null, "e": 1631, "s": 1531, "text": "Now, we will align the label content along the Y axis on the bottom by seeting location as BOTTOM −" }, { "code": null, "e": 1674, "s": 1631, "text": "label.setVerticalAlignment(JLabel.BOTTOM);" }, { "code": null, "e": 1777, "s": 1674, "text": "The following is an example to set the alignment of the label content along the Y axis in the bottom −" }, { "code": null, "e": 2848, "s": 1777, "text": "package my;\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.FlowLayout;\nimport java.awt.Font;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JTextArea;\nimport javax.swing.WindowConstants;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Frame\");\n frame.setLayout(new FlowLayout());\n JLabel label = new JLabel(\"Project Name\");\n label.setPreferredSize(new Dimension(190, 100));\n label.setOpaque(true);\n label.setBackground(Color.GREEN);\n label.setForeground(Color.WHITE);\n Font font = new Font(\"Serif\", Font.BOLD, 18);\n label.setFont(font);\n label.setVerticalAlignment(JLabel.BOTTOM);\n JTextArea text = new JTextArea();\n text.setText(\"Amit Learning Application\");\n font = new Font(\"Serif\", Font.BOLD, 13);\n text.setFont(font);\n frame.add(label);\n frame.add(text);\n frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n frame.setSize(500, 300);\n frame.setVisible(true);\n }\n}" } ]
How to declare numbers in JavaScript?
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. To declare variables in JavaScript, you need to use the var keyword. Whether it is a number or string, use the var keyword for declaration. Here’s how you can declare numbers in JavaScript − var points = 100; var rank = 5; You can try to run the following code to learn how to declare number in JavaScript − <html> <body> <script> <!-- var age = 20; if( age > 18 ){ document.write("<b>Qualifies for driving</b>"); } //--> </script> </body> </html>
[ { "code": null, "e": 1307, "s": 1062, "text": "JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. To declare variables in JavaScript, you need to use the var keyword. Whether it is a number or string, use the var keyword for declaration." }, { "code": null, "e": 1358, "s": 1307, "text": "Here’s how you can declare numbers in JavaScript −" }, { "code": null, "e": 1390, "s": 1358, "text": "var points = 100;\nvar rank = 5;" }, { "code": null, "e": 1475, "s": 1390, "text": "You can try to run the following code to learn how to declare number in JavaScript −" }, { "code": null, "e": 1704, "s": 1475, "text": "<html>\n <body>\n <script>\n <!--\n var age = 20;\n if( age > 18 ){\n document.write(\"<b>Qualifies for driving</b>\");\n }\n //-->\n </script>\n </body>\n</html>" } ]
Difference between title() and wm_title() methods in Tkinter class
Tkinter has a definite class hierarchy which contains many functions and built-in methods. As we create applications, we use these functions to build the structure of components.The wm class stands for "window manager" that is a mixin class that provides many builtin functions and methods. The method wm_title() is used to change the title of the tkinter window. However, alternatively, we can also use the win.title() method. Generally, wm class provides many methods that let us communicate with the window services. # Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") win.wm_title("This is the Title") # Add A label widget Label(win, text="Welcome to TutorialsPoint✨ \n" "You are browsing the best resource for Online Education.", font=('Aerial 18 italic')).place(x=50, y=150) win.mainloop() Run the above code to display a window that will contain some Label text widget.
[ { "code": null, "e": 1353, "s": 1062, "text": "Tkinter has a definite class hierarchy which contains many functions and built-in methods. As we create applications, we use these functions to build the structure of components.The wm class stands for \"window manager\" that is a mixin class that provides many builtin functions and methods." }, { "code": null, "e": 1582, "s": 1353, "text": "The method wm_title() is used to change the title of the tkinter window. However, alternatively, we can also use the win.title() method. Generally, wm class provides many methods that let us communicate with the window services." }, { "code": null, "e": 1976, "s": 1582, "text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\nwin.wm_title(\"This is the Title\")\n\n# Add A label widget\nLabel(win, text=\"Welcome to TutorialsPoint✨ \\n\" \"You are browsing the best resource for Online Education.\", font=('Aerial 18 italic')).place(x=50, y=150)\n\nwin.mainloop()" }, { "code": null, "e": 2057, "s": 1976, "text": "Run the above code to display a window that will contain some Label text widget." } ]
C++ Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
This is a C++ program to generate all possible subsets with exactly k elements in each subset. Begin function PossibleSubSet(char a[], int reqLen, int s, int currLen, bool check[], int l): If currLen > reqLen Return Else if currLen = reqLen Then print the new generated sequence. If s = l Then return no further element is left. For every index there are two options: either proceed with a start as ‘true’ and recursively call PossibleSubSet() with incremented value of ‘currLen’ and ‘s’. Or proceed with a start as ‘false’ and recursively call PossibleSubSet() with only incremented value of ‘s’. End #include<iostream> using namespace std; void PossibleSubSet(char a[], int reqLen, int s, int currLen, bool check[], int l) //print the all possible combination of given array set { if(currLen > reqLen) return; else if (currLen == reqLen) { cout<<"\t"; for (int i = 0; i < l; i++) { if (check[i] == true) { cout<<a[i]<<" "; } } cout<<"\n"; return; } if (s == l) { return; } check[s] = true; PossibleSubSet(a, reqLen, s + 1, currLen + 1, check, l); //recursively call PossibleSubSet() with incremented value of ‘currLen’ and ‘s’. check[s] = false; PossibleSubSet(a, reqLen, s + 1, currLen, check, l); //recursively call PossibleSubSet() with only incremented value of ‘s’. } int main() { int i,n,m; bool check[n]; cout<<"Enter the number of elements: "; cin>>n; char a[n]; cout<<"\n"; for(i = 0; i < n; i++) { cout<<"Enter "<<i+1<<" element: "; cin>>a[i]; check[i] = false; } cout<<"\nEnter the length of the subsets required: "; cin>>m; cout<<"\nThe possible combination of length "<<m<<" for the given array set:\n"; PossibleSubSet(a, m, 0, 0, check, n); return 0; } Enter the number of elements: 7 Enter 1 element: 7 Enter 2 element: 6 Enter 3 element: 5 Enter 4 element: 4 Enter 5 element: 3 Enter 6 element: 2 Enter 7 element: 1 Enter the length of the subsets required: 6 The possible combination of length 6 for the given array set: 7 6 5 4 3 2 7 6 5 4 3 1 7 6 5 4 2 1 7 6 5 3 2 1 7 6 4 3 2 1 7 5 4 3 2 1 6 5 4 3 2 1
[ { "code": null, "e": 1157, "s": 1062, "text": "This is a C++ program to generate all possible subsets with exactly k elements in each subset." }, { "code": null, "e": 1733, "s": 1157, "text": "Begin\n function PossibleSubSet(char a[], int reqLen, int s, int currLen, bool check[], int l):\n If currLen > reqLen\n Return\n Else if currLen = reqLen\n Then print the new generated sequence.\n If s = l\n Then return no further element is left.\n For every index there are two options:\n either proceed with a start as ‘true’ and recursively call PossibleSubSet()\n with incremented value of ‘currLen’ and ‘s’.\n Or proceed with a start as ‘false’ and recursively call PossibleSubSet()\n with only incremented value of ‘s’.\nEnd" }, { "code": null, "e": 2959, "s": 1733, "text": "#include<iostream>\nusing namespace std;\nvoid PossibleSubSet(char a[], int reqLen, int s, int currLen, bool check[], int l)\n//print the all possible combination of given array set\n{\n if(currLen > reqLen)\n return;\n else if (currLen == reqLen) {\n cout<<\"\\t\";\n for (int i = 0; i < l; i++) {\n if (check[i] == true) {\n cout<<a[i]<<\" \";\n }\n }\n cout<<\"\\n\";\n return;\n }\n if (s == l) {\n return;\n }\n check[s] = true;\n PossibleSubSet(a, reqLen, s + 1, currLen + 1, check, l);\n //recursively call PossibleSubSet() with incremented value of ‘currLen’ and ‘s’.\n check[s] = false;\n PossibleSubSet(a, reqLen, s + 1, currLen, check, l);\n //recursively call PossibleSubSet() with only incremented value of ‘s’.\n}\nint main() {\n int i,n,m;\n bool check[n];\n cout<<\"Enter the number of elements: \";\n cin>>n;\n char a[n];\n cout<<\"\\n\";\n for(i = 0; i < n; i++) {\n cout<<\"Enter \"<<i+1<<\" element: \";\n cin>>a[i];\n check[i] = false;\n }\n cout<<\"\\nEnter the length of the subsets required: \";\n cin>>m;\n cout<<\"\\nThe possible combination of length \"<<m<<\" for the given array set:\\n\";\n PossibleSubSet(a, m, 0, 0, check, n);\n return 0;\n}" }, { "code": null, "e": 3314, "s": 2959, "text": "Enter the number of elements: 7\nEnter 1 element: 7\nEnter 2 element: 6\nEnter 3 element: 5\nEnter 4 element: 4\nEnter 5 element: 3\nEnter 6 element: 2\nEnter 7 element: 1\nEnter the length of the subsets required: 6\nThe possible combination of length 6 for the given array set:\n7 6 5 4 3 2\n7 6 5 4 3 1\n7 6 5 4 2 1\n7 6 5 3 2 1\n7 6 4 3 2 1\n7 5 4 3 2 1\n6 5 4 3 2 1" } ]
Random Forest for predictive maintenance of turbofan engines | by Koen Peters | Towards Data Science
<disclaimer: I aim to showcase the effect of different methods and choices made during model development. These effects are often shown using the test set, something which is considered (very) bad practice but helps for educational purposes.> Welcome to another installment of the ‘Exploring NASA’s turbofan dataset’ series. In the last post we looked at survival analysis and wrapped up our analysis on dataset FD001. Although the final RMSE wasn’t as good compared to the earlier models we created, it’s a very interesting technique to keep in mind as it can deal with censored data. Today we’ll dive into the third dataset (FD003), which is characterized by the engines having two possible fault modes. I have chosen to switch the order in which to post on FD002 and FD003 as, in my opinion, this order gives a more gradual increase in complexity. At first, I had started fitting a Random Forest (RF) on FD002, but results weren’t all that good. FD002 looks like it really requires more complex preprocessing and modelling to deal with the various operating conditions. On FD003 however, I think the RF will perform pretty well, as it’s naturally capable of differentiating between the fault modes. Let’s dive in and find out! We can repeat a lot of the steps from our EDA on FD001. First, let’s read in the data. # returns# (24720, 26) Looks good, next we will inspect some descriptive statistics. Our dataset consists of 24.7k rows and 26 columns, the first engine fails after 145 time_cycles while the last engine fails after 525 time_cylces. Next, we’ll inspect the sensor descriptives. Judging by the standard deviation of (almost) zero, sensors 1, 5, 16, 18 and 19 hold no valuable information. Before we start plotting our data, let’s compute the Remaining Useful Life (RUL) of the train set. Now that that’s added, we’re going to inspect the distribution to get an even better understanding than we could from inspecting the descriptive table. The RUL is clearly right skewed and doesn’t have much of a tail on the left side at all. The skewed distribution can have a big impact on model performance. After EDA is complete, we’ll clip the computed RUL to an upper limit of 125 for model training, as it gives a better representation of our knowledge of RUL for the train set [1, 2]. Next, we’ll inspect the sensor values to see if we can visually distinguish between the different fault modes and to identify sensors to abandon for model development. Sensors 1, 5, 16, 18 and 19 all look similar. We can reconfirm their exclusion as they don’t seem to hold any information. Sensors 2, 3, 4, 8, 11, 13 and 17 show a similar upward trend and should be included during model development. Sensor 6 is a bit of an odd one but gets the benefit of the doubt. Sensors 7, 12, 15, 20 and 21 clearly show the two fault modes and should definitely be included in the model. Sensors 9 and 14 show a similar trend but don’t differentiate between fault modes very well. Testing their effect on model performance will have to point out if they should be included or not. Lastly, sensor 10, also an odd one which gets the benefit of the doubt as there seems to be somewhat of an upward trend. With our EDA complete it’s time to create our baseline model. Like we did for FD001, I like to start with one of the simplest models possible, a regression model with no additional preprocessing. # returns# train set RMSE:19.33013490506061, R2:0.7736110804777467# test set RMSE:22.31934448440365, R2:0.7092939799790338 The test RMSE for the baseline model is 22.319, which will be our score to beat. Next is our first try at the Random Forest Regressor. One of the key strengths of the Random Forest (RF) over single decision trees is their ability to generate varied trees. Let me explain. When creating a single decision tree, the algorithm tries to create a decision node based on a single feature (of all available features) which best splits your dataset. For the next node it will re-examine all available features to create the following best split. If you would fit a decision tree a second time under these conditions, it would make the exact same tree. A RF however, only considers a subset of all features when creating a split. This forces the algorithm into making different trees, as the feature for creating the best split may not be available. Potentially coming up with combinations of splits which perform better than the single best split of a regular decision tree. Although the description above is how I learned RF works, it’s important to check if the tool you use also implements it in the same way. Examining the documentation of sklearns RandomForestRegressor shows it considers all features by default, essentially creating the same tree over and over again. Therefore, we specify the max_features as the square root of the available features. In addition, we set the random_state so trees are always generated in the same way. Otherwise the random tree generation will affect model results, making it difficult to judge if a model performs better because we changed some features or due to randomness. # returns# train set RMSE:5.9199939580022525, R2:0.9787661901585051# test set RMSE:21.05308450085165, R2:0.7413439613827657 Although the RF already performs a little better than our baseline model. Judging by the difference in RMSE and variance between the train and test sets the model seems quite overfit. Let’s inspect some tree characteristics to verify my suspicion. # returns# 33# array([15616, 11694, 7793, ..., 1, 1, 4], dtype=int64) This tree’s longest path consists of 33 of nodes, more than double the number of features we put in. When looking at the n_nodes_samples, we can see the final leaves of the tree contain very few samples each. The tree has become so specific, it created splitting criteria until most samples can be distinguished, which is really bad for generalization (hence overfitting on the training set). We can try to fix this by setting the max_depth and min_samples_leaf of the RF. # returns# train set RMSE:15.706704198492831, R2:0.8505294865338602# test set RMSE:20.994958823842456, R2:0.7427702419664686 Playing around with those settings for a bit reduced overfitting while gaining a slight performance increase. Fitting this same model without s_6 and s_10 performed worse, so those sensors are kept in. We’ll use this model as a base for further improvements. We can visualize one of our trees in an attempt to identify points of improvement [4,5]. There seem to be some nodes which result in very inaccurate predictions (mse > 500). Remember sensors 9 and 14, which don’t differentiate between fault modes very well? They show up as splitting criterion in this part of the tree quite a bit, but results remain lackluster. Let’s try and fit a RF without those two sensors and check its performance. Rerunning the crudely tweaked RF returns: # train set RMSE:17.598192835079978, R2:0.8123616776758054# test set RMSE:22.186214762363356, R2:0.7127516253047333 Unfortunately, performance becomes quite a bit worse, so we’ll keep sensors 9 and 14 included. There aren’t a lot of possibilities for feature engineering for this particular dataset - algorithm combination. Random Forests naturally excel at learning complex data patterns and are invariant to scaling or feature transformations [6]. Since all features are numeric already, there isn’t much more we can do. I’ve tried smoothing the data with a simple moving average. In theory this would make it easier for the algorithm to apply its splits correctly and make it easier to distinguish between faults as noise is removed from the signal. But unfortunately, performance didn’t increase. The code for smoothing the sensor signals can be found in the notebook (link at the bottom of the post). Next, we’ll delve into hyperparameter tuning. What parameters can we tune? # returns{'bootstrap': True, 'ccp_alpha': 0.0, 'criterion': 'mse', 'max_depth': 8, 'max_features': 'sqrt', 'max_leaf_nodes': None, 'max_samples': None, 'min_impurity_decrease': 0.0, 'min_impurity_split': None, 'min_samples_leaf': 50, 'min_samples_split': 2, 'min_weight_fraction_leaf': 0.0, 'n_estimators': 100, 'n_jobs': None, 'oob_score': False, 'random_state': 42, 'verbose': 0, 'warm_start': False} For a full description of all parameters, please refer to the official documentation [3]. The biggest challenge in fitting Random Forests is overfitting. The parameters max_depth, min_samples_leaf, ccp_alpha and min_impurity_decrease help reduce overfitting and generate overall better performing models. Therefore, I’ve picked those for model tuning. Max_depth and min_samples_leaf should be quite self-explanatory, but ccp_alpha and min_impurity_decrease need a bit more explanation. Cost complexity pruning alpha is a parameter used for pruning trees. Pruning is the removal of nodes after fitting, so essentially ccp_alpha is an alternative to using min_samples_leaf and max_depth to prevent overfitting. The cost complexity of the nodes can be retrieved from a fitted tree. Lower ccp_alpha’s indicate higher cost complexity. By removing nodes with small ccp_alpha’s the tree is pruned, and overall complexity reduced [7]. To get an indication of what range of ccp_alpha’s to use for hyperparameter tuning it’s best to visualize the effective alpha versus the impurity of the leaves. Note, the below analysis is from a single tree of the RF. The cost complexity of the tree really increases when the effective alpha drops from ~70 to a bit more than 20, but for lower values of alpha the effect of cost complexity on leaf impurity is difficult to determine, let’s zoom in a little bit. When effective alpha drops from 2 to 0 (and cost complexity reaches its maximum) the leaf impurity seems to decrease by about 50 points, which amounts to ~7 training RMSE. Given the extreme overfitting of our first RF, this seems a suitable range for hyperparameter tuning. Min impurity decrease is a measure for indicating the reduction in error after a split. The impurity decrease is a weighted value calculated as follows: Impurity decreases are normally calculated for a single decision tree. So, let’s first extract the required data of a single tree. # returns shape (227, 5) When looking at the first few rows you should notice some child_id’s have the value -1. This indicates the parent node was a leaf node and so no further splits were made. With all the data in a dataframe we can calculate the min_impurity_decrease using the formula above. It’s best to visualize the result to get an idea of suitable values for min_impurity_decrease. The impurity decrease is very right skewed, this can be explained by the first few nodes of the tree contributing a lot to decreasing error. Checking the descriptives shows 25% of the values for impurity decrease lie below 14.59, which seems a suitable upper-bound for the min_impurity_decrease parameter. After finishing exploring the parameters to tune, we can now set the appropriate ranges to evaluate. # returns1571724 Note, if we wanted to test all possible combinations, we’d have to fit over 1.5 million models. A tedious task. Luckily, applying Randomsearch by randomly picking 60 unique combinations should get you within 95% of the optimal solution [8]. Increasing the number of iterations increases the probability of finding a better solution. In addition to using Randomsearch, I prefer to keep the number of trees low to speed up training times. This combination allows for a relatively fast search. I’ve executed the search a couple of times and chose the best performing settings. There’s one more thing to discuss before showing the code: We need to create validation sets to validate the chosen hyperparameters. Creating a validation set for this data requires taking into account one important factor. Engines which are included in the training set cannot be included in the validation set and vice versa. Normally you would create a random split in your data where 80 % belongs to the training set and 20 % to the validation set. However, if we split randomly without taking the unit numbers into account we might end up with part of the data of a single engine in both train and validation sets. The model could then learn to extrapolate between timesteps and make very accurate predictions on the validation set. On truly new data however, model performance would suffer. To prevent this form of ‘data leakage’ we must make sure all records of a single engine are assigned to either the training or validation set. To achieve this form of data splitting we’ll use GroupKFold. Since training times are relatively low, I’ve set the number of iterations to 300. Next, the RandomizedSearchCV is instantiated with a bare RF, the parameters to sample from for hyperparameter tuning and the GroupKFold, where groups are based on unit_nr. The random search takes slightly less than 15 minutes, we can convert the results to a dataframe for further inspection. Inspecting the results helps to obtain an understanding of which hyperparameters perform well and could potentially be used to refine your search space (we’ll leave it as if for now). Unfortunately, results aren’t reproducible, meaning restarting the kernel and running the notebook again doesn’t produce the same results. Something I will try to tackle in the next analysis. Having executed the search a couple of times, the best performing set of parameters I’ve found was: {'min_samples_leaf': 11, 'min_impurity_decrease': 0.0, 'max_depth': 15, 'ccp_alpha': 0.125}. With a mean_test_score of -16.577. Using those parameters, we can train our final model. # returns:# train set RMSE:13.95446880579081, R2:0.8820190156933622# test set RMSE:20.61288923394374, R2:0.7520472702746352 And there you have it, a tweaked Random Forest without feature engineering (only some feature selection) but still very respectable results. The test RMSE of 20.612 provides a 7.65% improvement over our baseline model. It may not seem like much, but in terms of RMSE this RF beats the timeseries model we’ve fit earlier on FD001 (which had an RMSE of 20.852), while FD003 is a more complex dataset! For the complete notebook you can check out my github page here. I would like to thank Maikel Grobbe for his inputs and reviewing my article. Next time, we’ll delve into the even more complex FD002 and neural networks using Tensorflow. Have any questions or remarks? Let me know in the comments below! References[1] The importance of problem framing for supervised predictive maintenance solutions[2] F. O. Heimes, “Recurrent neural networks for remaining useful life estimation,” 2008 International Conference on Prognostics and Health Management, Denver, CO, 2008, pp. 1–6, doi: 10.1109/PHM.2008.4711422.[3] https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html[4] https://towardsdatascience.com/how-to-visualize-a-decision-tree-from-a-random-forest-in-python-using-scikit-learn-38ad2d75f21c[5] https://stackoverflow.com/questions/14784405/how-to-set-the-output-size-in-graphviz-for-the-dot-format[6] https://en.wikipedia.org/wiki/Random_forest[7] https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html[8] Zheng, Alice. Evaluating Machine Learning Models. O’Reilly Media, Inc. 2015
[ { "code": null, "e": 414, "s": 171, "text": "<disclaimer: I aim to showcase the effect of different methods and choices made during model development. These effects are often shown using the test set, something which is considered (very) bad practice but helps for educational purposes.>" }, { "code": null, "e": 877, "s": 414, "text": "Welcome to another installment of the ‘Exploring NASA’s turbofan dataset’ series. In the last post we looked at survival analysis and wrapped up our analysis on dataset FD001. Although the final RMSE wasn’t as good compared to the earlier models we created, it’s a very interesting technique to keep in mind as it can deal with censored data. Today we’ll dive into the third dataset (FD003), which is characterized by the engines having two possible fault modes." }, { "code": null, "e": 1401, "s": 877, "text": "I have chosen to switch the order in which to post on FD002 and FD003 as, in my opinion, this order gives a more gradual increase in complexity. At first, I had started fitting a Random Forest (RF) on FD002, but results weren’t all that good. FD002 looks like it really requires more complex preprocessing and modelling to deal with the various operating conditions. On FD003 however, I think the RF will perform pretty well, as it’s naturally capable of differentiating between the fault modes. Let’s dive in and find out!" }, { "code": null, "e": 1488, "s": 1401, "text": "We can repeat a lot of the steps from our EDA on FD001. First, let’s read in the data." }, { "code": null, "e": 1511, "s": 1488, "text": "# returns# (24720, 26)" }, { "code": null, "e": 1573, "s": 1511, "text": "Looks good, next we will inspect some descriptive statistics." }, { "code": null, "e": 1765, "s": 1573, "text": "Our dataset consists of 24.7k rows and 26 columns, the first engine fails after 145 time_cycles while the last engine fails after 525 time_cylces. Next, we’ll inspect the sensor descriptives." }, { "code": null, "e": 1875, "s": 1765, "text": "Judging by the standard deviation of (almost) zero, sensors 1, 5, 16, 18 and 19 hold no valuable information." }, { "code": null, "e": 1974, "s": 1875, "text": "Before we start plotting our data, let’s compute the Remaining Useful Life (RUL) of the train set." }, { "code": null, "e": 2126, "s": 1974, "text": "Now that that’s added, we’re going to inspect the distribution to get an even better understanding than we could from inspecting the descriptive table." }, { "code": null, "e": 2465, "s": 2126, "text": "The RUL is clearly right skewed and doesn’t have much of a tail on the left side at all. The skewed distribution can have a big impact on model performance. After EDA is complete, we’ll clip the computed RUL to an upper limit of 125 for model training, as it gives a better representation of our knowledge of RUL for the train set [1, 2]." }, { "code": null, "e": 2633, "s": 2465, "text": "Next, we’ll inspect the sensor values to see if we can visually distinguish between the different fault modes and to identify sensors to abandon for model development." }, { "code": null, "e": 2756, "s": 2633, "text": "Sensors 1, 5, 16, 18 and 19 all look similar. We can reconfirm their exclusion as they don’t seem to hold any information." }, { "code": null, "e": 2867, "s": 2756, "text": "Sensors 2, 3, 4, 8, 11, 13 and 17 show a similar upward trend and should be included during model development." }, { "code": null, "e": 2934, "s": 2867, "text": "Sensor 6 is a bit of an odd one but gets the benefit of the doubt." }, { "code": null, "e": 3044, "s": 2934, "text": "Sensors 7, 12, 15, 20 and 21 clearly show the two fault modes and should definitely be included in the model." }, { "code": null, "e": 3237, "s": 3044, "text": "Sensors 9 and 14 show a similar trend but don’t differentiate between fault modes very well. Testing their effect on model performance will have to point out if they should be included or not." }, { "code": null, "e": 3420, "s": 3237, "text": "Lastly, sensor 10, also an odd one which gets the benefit of the doubt as there seems to be somewhat of an upward trend. With our EDA complete it’s time to create our baseline model." }, { "code": null, "e": 3554, "s": 3420, "text": "Like we did for FD001, I like to start with one of the simplest models possible, a regression model with no additional preprocessing." }, { "code": null, "e": 3677, "s": 3554, "text": "# returns# train set RMSE:19.33013490506061, R2:0.7736110804777467# test set RMSE:22.31934448440365, R2:0.7092939799790338" }, { "code": null, "e": 3812, "s": 3677, "text": "The test RMSE for the baseline model is 22.319, which will be our score to beat. Next is our first try at the Random Forest Regressor." }, { "code": null, "e": 4644, "s": 3812, "text": "One of the key strengths of the Random Forest (RF) over single decision trees is their ability to generate varied trees. Let me explain. When creating a single decision tree, the algorithm tries to create a decision node based on a single feature (of all available features) which best splits your dataset. For the next node it will re-examine all available features to create the following best split. If you would fit a decision tree a second time under these conditions, it would make the exact same tree. A RF however, only considers a subset of all features when creating a split. This forces the algorithm into making different trees, as the feature for creating the best split may not be available. Potentially coming up with combinations of splits which perform better than the single best split of a regular decision tree." }, { "code": null, "e": 4782, "s": 4644, "text": "Although the description above is how I learned RF works, it’s important to check if the tool you use also implements it in the same way." }, { "code": null, "e": 5288, "s": 4782, "text": "Examining the documentation of sklearns RandomForestRegressor shows it considers all features by default, essentially creating the same tree over and over again. Therefore, we specify the max_features as the square root of the available features. In addition, we set the random_state so trees are always generated in the same way. Otherwise the random tree generation will affect model results, making it difficult to judge if a model performs better because we changed some features or due to randomness." }, { "code": null, "e": 5412, "s": 5288, "text": "# returns# train set RMSE:5.9199939580022525, R2:0.9787661901585051# test set RMSE:21.05308450085165, R2:0.7413439613827657" }, { "code": null, "e": 5660, "s": 5412, "text": "Although the RF already performs a little better than our baseline model. Judging by the difference in RMSE and variance between the train and test sets the model seems quite overfit. Let’s inspect some tree characteristics to verify my suspicion." }, { "code": null, "e": 5743, "s": 5660, "text": "# returns# 33# array([15616, 11694, 7793, ..., 1, 1, 4], dtype=int64)" }, { "code": null, "e": 6216, "s": 5743, "text": "This tree’s longest path consists of 33 of nodes, more than double the number of features we put in. When looking at the n_nodes_samples, we can see the final leaves of the tree contain very few samples each. The tree has become so specific, it created splitting criteria until most samples can be distinguished, which is really bad for generalization (hence overfitting on the training set). We can try to fix this by setting the max_depth and min_samples_leaf of the RF." }, { "code": null, "e": 6341, "s": 6216, "text": "# returns# train set RMSE:15.706704198492831, R2:0.8505294865338602# test set RMSE:20.994958823842456, R2:0.7427702419664686" }, { "code": null, "e": 6600, "s": 6341, "text": "Playing around with those settings for a bit reduced overfitting while gaining a slight performance increase. Fitting this same model without s_6 and s_10 performed worse, so those sensors are kept in. We’ll use this model as a base for further improvements." }, { "code": null, "e": 6689, "s": 6600, "text": "We can visualize one of our trees in an attempt to identify points of improvement [4,5]." }, { "code": null, "e": 7039, "s": 6689, "text": "There seem to be some nodes which result in very inaccurate predictions (mse > 500). Remember sensors 9 and 14, which don’t differentiate between fault modes very well? They show up as splitting criterion in this part of the tree quite a bit, but results remain lackluster. Let’s try and fit a RF without those two sensors and check its performance." }, { "code": null, "e": 7081, "s": 7039, "text": "Rerunning the crudely tweaked RF returns:" }, { "code": null, "e": 7197, "s": 7081, "text": "# train set RMSE:17.598192835079978, R2:0.8123616776758054# test set RMSE:22.186214762363356, R2:0.7127516253047333" }, { "code": null, "e": 7292, "s": 7197, "text": "Unfortunately, performance becomes quite a bit worse, so we’ll keep sensors 9 and 14 included." }, { "code": null, "e": 7604, "s": 7292, "text": "There aren’t a lot of possibilities for feature engineering for this particular dataset - algorithm combination. Random Forests naturally excel at learning complex data patterns and are invariant to scaling or feature transformations [6]. Since all features are numeric already, there isn’t much more we can do." }, { "code": null, "e": 8033, "s": 7604, "text": "I’ve tried smoothing the data with a simple moving average. In theory this would make it easier for the algorithm to apply its splits correctly and make it easier to distinguish between faults as noise is removed from the signal. But unfortunately, performance didn’t increase. The code for smoothing the sensor signals can be found in the notebook (link at the bottom of the post). Next, we’ll delve into hyperparameter tuning." }, { "code": null, "e": 8062, "s": 8033, "text": "What parameters can we tune?" }, { "code": null, "e": 8465, "s": 8062, "text": "# returns{'bootstrap': True, 'ccp_alpha': 0.0, 'criterion': 'mse', 'max_depth': 8, 'max_features': 'sqrt', 'max_leaf_nodes': None, 'max_samples': None, 'min_impurity_decrease': 0.0, 'min_impurity_split': None, 'min_samples_leaf': 50, 'min_samples_split': 2, 'min_weight_fraction_leaf': 0.0, 'n_estimators': 100, 'n_jobs': None, 'oob_score': False, 'random_state': 42, 'verbose': 0, 'warm_start': False}" }, { "code": null, "e": 8817, "s": 8465, "text": "For a full description of all parameters, please refer to the official documentation [3]. The biggest challenge in fitting Random Forests is overfitting. The parameters max_depth, min_samples_leaf, ccp_alpha and min_impurity_decrease help reduce overfitting and generate overall better performing models. Therefore, I’ve picked those for model tuning." }, { "code": null, "e": 8951, "s": 8817, "text": "Max_depth and min_samples_leaf should be quite self-explanatory, but ccp_alpha and min_impurity_decrease need a bit more explanation." }, { "code": null, "e": 9174, "s": 8951, "text": "Cost complexity pruning alpha is a parameter used for pruning trees. Pruning is the removal of nodes after fitting, so essentially ccp_alpha is an alternative to using min_samples_leaf and max_depth to prevent overfitting." }, { "code": null, "e": 9392, "s": 9174, "text": "The cost complexity of the nodes can be retrieved from a fitted tree. Lower ccp_alpha’s indicate higher cost complexity. By removing nodes with small ccp_alpha’s the tree is pruned, and overall complexity reduced [7]." }, { "code": null, "e": 9611, "s": 9392, "text": "To get an indication of what range of ccp_alpha’s to use for hyperparameter tuning it’s best to visualize the effective alpha versus the impurity of the leaves. Note, the below analysis is from a single tree of the RF." }, { "code": null, "e": 9855, "s": 9611, "text": "The cost complexity of the tree really increases when the effective alpha drops from ~70 to a bit more than 20, but for lower values of alpha the effect of cost complexity on leaf impurity is difficult to determine, let’s zoom in a little bit." }, { "code": null, "e": 10129, "s": 9855, "text": "When effective alpha drops from 2 to 0 (and cost complexity reaches its maximum) the leaf impurity seems to decrease by about 50 points, which amounts to ~7 training RMSE. Given the extreme overfitting of our first RF, this seems a suitable range for hyperparameter tuning." }, { "code": null, "e": 10282, "s": 10129, "text": "Min impurity decrease is a measure for indicating the reduction in error after a split. The impurity decrease is a weighted value calculated as follows:" }, { "code": null, "e": 10413, "s": 10282, "text": "Impurity decreases are normally calculated for a single decision tree. So, let’s first extract the required data of a single tree." }, { "code": null, "e": 10438, "s": 10413, "text": "# returns shape (227, 5)" }, { "code": null, "e": 10609, "s": 10438, "text": "When looking at the first few rows you should notice some child_id’s have the value -1. This indicates the parent node was a leaf node and so no further splits were made." }, { "code": null, "e": 10710, "s": 10609, "text": "With all the data in a dataframe we can calculate the min_impurity_decrease using the formula above." }, { "code": null, "e": 10805, "s": 10710, "text": "It’s best to visualize the result to get an idea of suitable values for min_impurity_decrease." }, { "code": null, "e": 11111, "s": 10805, "text": "The impurity decrease is very right skewed, this can be explained by the first few nodes of the tree contributing a lot to decreasing error. Checking the descriptives shows 25% of the values for impurity decrease lie below 14.59, which seems a suitable upper-bound for the min_impurity_decrease parameter." }, { "code": null, "e": 11212, "s": 11111, "text": "After finishing exploring the parameters to tune, we can now set the appropriate ranges to evaluate." }, { "code": null, "e": 11229, "s": 11212, "text": "# returns1571724" }, { "code": null, "e": 11470, "s": 11229, "text": "Note, if we wanted to test all possible combinations, we’d have to fit over 1.5 million models. A tedious task. Luckily, applying Randomsearch by randomly picking 60 unique combinations should get you within 95% of the optimal solution [8]." }, { "code": null, "e": 11720, "s": 11470, "text": "Increasing the number of iterations increases the probability of finding a better solution. In addition to using Randomsearch, I prefer to keep the number of trees low to speed up training times. This combination allows for a relatively fast search." }, { "code": null, "e": 11936, "s": 11720, "text": "I’ve executed the search a couple of times and chose the best performing settings. There’s one more thing to discuss before showing the code: We need to create validation sets to validate the chosen hyperparameters." }, { "code": null, "e": 12131, "s": 11936, "text": "Creating a validation set for this data requires taking into account one important factor. Engines which are included in the training set cannot be included in the validation set and vice versa." }, { "code": null, "e": 12600, "s": 12131, "text": "Normally you would create a random split in your data where 80 % belongs to the training set and 20 % to the validation set. However, if we split randomly without taking the unit numbers into account we might end up with part of the data of a single engine in both train and validation sets. The model could then learn to extrapolate between timesteps and make very accurate predictions on the validation set. On truly new data however, model performance would suffer." }, { "code": null, "e": 12804, "s": 12600, "text": "To prevent this form of ‘data leakage’ we must make sure all records of a single engine are assigned to either the training or validation set. To achieve this form of data splitting we’ll use GroupKFold." }, { "code": null, "e": 13180, "s": 12804, "text": "Since training times are relatively low, I’ve set the number of iterations to 300. Next, the RandomizedSearchCV is instantiated with a bare RF, the parameters to sample from for hyperparameter tuning and the GroupKFold, where groups are based on unit_nr. The random search takes slightly less than 15 minutes, we can convert the results to a dataframe for further inspection." }, { "code": null, "e": 13364, "s": 13180, "text": "Inspecting the results helps to obtain an understanding of which hyperparameters perform well and could potentially be used to refine your search space (we’ll leave it as if for now)." }, { "code": null, "e": 13656, "s": 13364, "text": "Unfortunately, results aren’t reproducible, meaning restarting the kernel and running the notebook again doesn’t produce the same results. Something I will try to tackle in the next analysis. Having executed the search a couple of times, the best performing set of parameters I’ve found was:" }, { "code": null, "e": 13749, "s": 13656, "text": "{'min_samples_leaf': 11, 'min_impurity_decrease': 0.0, 'max_depth': 15, 'ccp_alpha': 0.125}." }, { "code": null, "e": 13784, "s": 13749, "text": "With a mean_test_score of -16.577." }, { "code": null, "e": 13838, "s": 13784, "text": "Using those parameters, we can train our final model." }, { "code": null, "e": 13962, "s": 13838, "text": "# returns:# train set RMSE:13.95446880579081, R2:0.8820190156933622# test set RMSE:20.61288923394374, R2:0.7520472702746352" }, { "code": null, "e": 14361, "s": 13962, "text": "And there you have it, a tweaked Random Forest without feature engineering (only some feature selection) but still very respectable results. The test RMSE of 20.612 provides a 7.65% improvement over our baseline model. It may not seem like much, but in terms of RMSE this RF beats the timeseries model we’ve fit earlier on FD001 (which had an RMSE of 20.852), while FD003 is a more complex dataset!" }, { "code": null, "e": 14663, "s": 14361, "text": "For the complete notebook you can check out my github page here. I would like to thank Maikel Grobbe for his inputs and reviewing my article. Next time, we’ll delve into the even more complex FD002 and neural networks using Tensorflow. Have any questions or remarks? Let me know in the comments below!" } ]
Surprising Sorting Tips for Data Scientists | by Jeff Hale | Towards Data Science
Sorting data is a basic task for data scientists and data engineers. Python users have a number of libraries to choose from with built-in, optimized sorting options. Some even work in parallel on GPUs. Surprisingly some sort methods don’t use the stated algorithm types and others don’t perform as expected. Choosing which library and type of sorting algorithm to use can be tricky. Implementations change quickly. As of the original writing of this article, the pandas documentation isn’t even up to date with the code (although my PR updating the sort options was just accepted). 😄 In this article I’ll give you the lay of the land, provide tips to help you remember the methods, and share the results of a speed test. Let’s get sorting! UPDATE July 17, 2019: Speed test evaluation results now include GPU implementations of PyTorch and TensorFlow. TensorFlow also includes CPU results under both tensorflow==2.0.0-beta1 and tensorflow-gpu==2.0.0-beta1. Surprising findings: PyTorch GPU is lightening fast and TensorFlow GPU is slower than TensorFlow CPU. I suspect a performance bug is present in the GPU version. Further updated Sept. 2021 for increased clarity. There are many different basic sorting algorithms. Some perform faster and use less memory than others. Some are better suited to big data and some work better if the data are arranged in certain ways. See the chart below for time and space complexity of many common algorithms. Being an expert at basic implementations isn’t necessary for most data science problems. In fact, premature optimization is occasionally cited as the root of all evil. However, knowing which library and which keyword arguments to use can be quite helpful when you need to repeatedly sort a lot of data. Here’s my cheat sheet. The sorting algorithms have changed over the years in many libraries. The following software versions were used in the analysis for this article: python 3.6.8numpy 1.16.4pandas 0.24.2tensorflow==2.0.0-beta1 #tensorflow-gpu==2.0.0-beta1 slows sortingpytorch 1.1 Let’s start with the basics. Python contains two built-in sorting methods. my_list.sort() sorts a list in-place. It mutates the list. sort() returns None. sorted(my_list) makes a sorted copy of any iterable. sorted() returns the sorted iterable. sort() does not mutate the original iterable. sort() should be faster because it is in place. Surprisingly, that’s not what I found in the test below. In-place sorting is more dangerous because it mutates the original data. For vanilla Python all of the implementations we’ll look at in this article, the default sorting order is ascending — from smallest to largest. Most sorting methods accept a keyword parameter to switch the sort order to descending. Unfortunately for your brain, this parameter name is different for each library. 😦 To change either sort order to descending in vanilla Python, pass reverse=True. key can be passed as a keyword argument to create your own sort criteria. For example, sort(key=len) will sort by the length of each list item. The only sorting algorithm used in vanilla Python is Timsort. Timsort chooses a sorting method depending upon the characteristics of the data to be sorted. For example, if a short list is to be sorted, then an insertion sort is used. See Brandon Skerritt’s great article for more details on Timsort here. Timsort, and thus Vanilla Python sorts, are stable. This means that if multiple values are the same, then those items remain in the original order after sorting. To remember sort() vs. sorted(), I just remember that sorted is a longer word than sort and that sorted should take longer to run because it has to make a copy. Although the results below didn’t support the conventional wisdom, the mnemonic still works. 😃 Now let’s look at using NumPy. NumPy is the bedrock Python library for scientific computing. Like vanilla Python, it has two sort implementations, one that mutates the array and one that copies it. my_array.sort() mutates the array in place and returns the sorted array. np.sort(my_array) returns a copy of the sorted array, so it doesn’t mutate the original array. Here are the optional arguments. axis : int, optional — Axis along which to sort. Default is -1, which means sort along the last axis. kind : {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional — Sorting algorithm. Default is ‘quicksort’. More on this below. order : str or list of str, optional — When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. The sorting algorithms used are now a bit different than you might expect based on their names. Passing kind=quicksort means sorting actually starts with an introsort algorithm. The docs explain: When [it] does not make enough progress it switches to a heapsort algorithm This implementation makes quicksort O(n*log(n)) in the worst case. stable automatically chooses the best stable sorting algorithm for the data type being sorted. It, along with mergesort is currently mapped to timsort or radix sort depending on the data type. API forward compatibility currently limits the ability to select the implementation and it is hardwired for the different data types. Timsort is added for better performance on already or nearly sorted data. On random data timsort is almost identical to mergesort. It is now used for stable sort while quicksort is still the default sort if none is chosen...‘mergesort’ and ‘stable’ are mapped to radix sort for integer data types. - From the NumPy docs —( after some of my edits). One take-away is that NumPy provides a wider range of control for sorting algorithm options than vanilla Python. A second take-away is that the kind keyword value doesn’t necessarily correspond to the actual sort type used. A final take-away is that the mergesort and stable values are stable sorts, but quicksort and heapsort are not. NumPy sorts are the only implementations on our list without a keyword argument to reverse the sort order. Luckily, it’s quick to reverse an array with a slice like this: my_arr[::-1]. The NumPy algorithm options are also available in the more user-friendly pandas — and I find the functions easier to keep straight. Sort a pandas DataFrame with df.sort_values(by=my_column). There are a number of keyword arguments available. by: str or list of str, required — Name or list of names to sort by. If axis is 0 or index then by may contain index levels and/or column labels. If axis is 1 or columns then by may contain column levels and/or index labels axis: {0 or index, 1 or columns}, default 0 — Axis to be sorted. ascending: bool or list of bool, default True — Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by argument. inplace: bool, default False — if True, perform operation in-place. kind: {quicksort, mergesort, heapsort, or stable}, default quicksort — Choice of sorting algorithm. See also ndarray.np.sort for more information. For DataFrames, this option is only applied when sorting on a single column or label. na_position: {‘first’, ‘last’}, default ‘last’ — first puts NaNs at the beginning, last puts NaNs at the end. Sort a pandas Series by following the same syntax. With a Series you don’t provide a by keyword, because you don’t have multiple columns. Because pandas uses NumPy under the hood, you have the same nicely optimized sorting options at your fingertips. However, pandas requires some extra time for its conveniences. The default when sorting by a single column is to use NumPy’s quicksort. You’ll recall quicksort is now actually an introsort that becomes a heapsort if the sorting progress is slow. Pandas ensures that sorting by multiple columns uses NumPy’s mergesort. Mergesort in NumPy actually uses Timsort or Radix sort algorithms. These are stable sorting algorithms and stable sorting is necessary when sorting by multiple columns. The key things to try to remember for pandas: The function name: sort_values(). You need by=column_name or a list of column names. ascending is the keyword for reversing. Use mergesort if you want a stable sort. When doing exploratory data analysis with pandas, I often find myself summing and sorting values in a pandas DataFrame with Series.value_counts(). Here’s a code snippet to sum and sort the most frequent values for each column. for c in df.columns: print(f"---- {c} ---") print(df[c].value_counts().head()) Sorting in pandas is a nice option for exploratory data analysis on smaller datasets. Dask implements much of the pandas API when your data won’t fit in memory. Dask doesn’t have a parallel sorting implementation as of mid 2019, although it’s being discussed. When you have a lot of data and want parallelized search on a GPU, you may want to use TensorFlow or PyTorch. TensorFlow is the most popular deep learning framework. See my article on deep learning framework popularity and usage here. The following infois for the GPU version of TensorFlow 2.0. tf.sort(my_tensor) returns a sorted copy of a tensor. Optional arguments: axis: {int, optional} The axis along which to sort. The default is -1, which sorts the last axis. direction: {ascending or descending} — direction in which to sort the values. name: {str, optional} — name for the operation. tf.sort uses the top_k() method behind the scenes. top_k uses CUB library for CUDA GPUs to make parallelism easier to implement. As the docs explain “CUB provides state-of-the-art, reusable software components for every layer of the CUDA programming model.” TensorFlow uses radix sort on GPU via CUB, as discussed here. TensorFlow GPU info can be found here. To enable GPU capabilities with TensorFlow 2.0 you need to pip3 install tensorflow-gpu==2.0.0-beta1. As we’ll see from the evaluation below, you might want to stick with tensorflow==2.0.0-beta1 if all you are doing in sorting (which isn’t very likely). Use the following code snippet to see whether each line of code is running on the CPU or GPU: tf.debugging.set_log_device_placement(True) To specify you want to use a GPU use the following with block: with tf.device('/GPU:0'): %time tf.sort(my_tf_tensor) use with tf.device('/CPU:0'): to use the CPU. tf.sort() is a pretty intuitive method to remember and use if you work in TensorFlow. Just remember direction=descending to switch the sort order. Now let’s look at sorting in the other popular deep learning package, PyTorch. torch.sort(my_tensor) returns a sorted copy of a tensor. Optional arguments: dim: {int, optional} — the dimension to sort along descending: {bool, optional} — controls the sorting order (ascending or descending). out: {tuple, optional} — the output tuple of (Tensor, LongTensor) that can be optionally given to be used as output buffers. Specify you want to use the GPU by appending .cuda() to your tensor. gpu_tensor=my_pytorch_tensor.cuda()%time torch.sort(gpu_tensor) PyTorch uses a segmented parallel sort via Thrust if a dataset any larger than 1 million rows by 100,000 columns is being sorted. Thrust is a parallel algorithms library that enables performance portability between GPUs and multicore CPUs. It provides a sort primitive that selects the most efficient implementation automatically. The CUB library used by TensorFlow wraps thrust. So if you drill down far enough you see that PyTorch and TensorFlow are using similar implementations for GPU sorting under the hood — whatever thrust chooses for the situation. Unfortunately, the Google Colab server ran out of memory when trying to to create 1.1M x 100K random data points via NumPy. 😦 So I moved to Google Cloud Platform (GCP) with 416 MB of RAM and still ran out of memory. 😦 😦 So I had to stay under 1 million rows. Segmented sort and locality sort are high-performance variants of mergesort that operate on non-uniform random data. Segmented sort allows us to sort many variable-length arrays in parallel. — https://moderngpu.github.io/segsort.html Like TensorFlow, the sorting method in PyTorch isn’t too rough to remember: torch.sort(). The only tricky thing is the keyword argument for the direction of the sorted values: TensorFlow uses direction while PyTorch uses descending. And don’t forget to use .cuda() to get a speed boost with large data sets. 😉 While sorting with GPUs could be a good option for really large datasets, it might also make sense to sort data directly in SQL. I have a brief bonus section on using SQL at the end of this article. 👍 For each of the Python libraries above, I conducted an analysis of the wall time to sort the same 1,000,000 data points in a single column, array, or list. I used a Google Colab Jupyter Notebook with a K80 GPU and Intel(R) Xeon(R) CPU @ 2.30GHz. PyTorch with GPU is super fast. For both NumPy and pandas, inplace is generally faster than copying the data. The default pandas quicksort is rather fast. Most pandas functions are comparatively slower than their NumPy counterparts. TensorFlow CPU is quite fast. The GPU install slows down TensorFlow even when the CPU is used. The GPU sort is quite slow. This looks like a possible bug. 🐞 Vanilla Python inplace sorting is surprisingly slow. It was nearly 100x slower than the PyTorch GPU-enabled sort. I tested it multiple times (with different data) to double check that this was not an anomaly. Again, this is just one small test. It’s definitely not definitive. 😉 You generally shouldn’t need custom sorting implementations. The off-the shelf options are strong. They are generally not using just a single sorting method. Instead they evaluate the data first and then use a sorting algorithm that performs well. Some implementations even change algorithms if the sort is not progressing quickly. In this article, you’ve seen how to sort in many Python data science libraries. I hope you’ve found it helpful. If you have, please share it on your favorite social media so others can find it, too. 👏 You just need to remember which option to choose and how to call it. Use my cheat sheet above to save time. 👍 My general recommendations are the following: Use the default pandas sort_values() for exploration on relatively small datasets. For large datasets or when speed is at a premium, try NumPy’s in-place mergesort. For even more of a speed boost, use PyTorch on a GPU. Sorting on GPUs isn’t something I’ve seen much written about. It’s an area that appears ripe for more research and tutorials. Here’s a 2017 article to give you a taste of recent research. More info on GPU sorting algorithms can be found here. Sorting in SQL is often very fast, particularly when the sort is in-memory. SQL is a specification, but doesn’t dictate things like which sort algorithm an implementation must use. Postgres uses a disk merge sort, heap sort, or quick sort, depending upon the circumstances. If you have enough memory, sorts can become much faster by making them in-memory. Increase the available memory for sorts via the work_mem setting. Other SQL implementations use different sorting algorithms. For example, Google BigQuery uses introsort with some tricks, according to this Stack Overflow answer. Sorts in SQL are performed with the ORDER BY command. This syntax is distinct from the Python implementations that all use some form of the word sort. At least ORDER BY is unique! 😃 To make the sort descending, use the keyword DESC. A query to return customers in alphabetical order from last to first would look like this: SELECT Names FROM CustomersORDER BY Names DESC; I write about Python, Docker, data science, and more. If any of that’s of interest to you, read more here and follow me on Medium. 😄 Happy sorting! 😀
[ { "code": null, "e": 355, "s": 47, "text": "Sorting data is a basic task for data scientists and data engineers. Python users have a number of libraries to choose from with built-in, optimized sorting options. Some even work in parallel on GPUs. Surprisingly some sort methods don’t use the stated algorithm types and others don’t perform as expected." }, { "code": null, "e": 631, "s": 355, "text": "Choosing which library and type of sorting algorithm to use can be tricky. Implementations change quickly. As of the original writing of this article, the pandas documentation isn’t even up to date with the code (although my PR updating the sort options was just accepted). 😄" }, { "code": null, "e": 768, "s": 631, "text": "In this article I’ll give you the lay of the land, provide tips to help you remember the methods, and share the results of a speed test." }, { "code": null, "e": 787, "s": 768, "text": "Let’s get sorting!" }, { "code": null, "e": 1214, "s": 787, "text": "UPDATE July 17, 2019: Speed test evaluation results now include GPU implementations of PyTorch and TensorFlow. TensorFlow also includes CPU results under both tensorflow==2.0.0-beta1 and tensorflow-gpu==2.0.0-beta1. Surprising findings: PyTorch GPU is lightening fast and TensorFlow GPU is slower than TensorFlow CPU. I suspect a performance bug is present in the GPU version. Further updated Sept. 2021 for increased clarity." }, { "code": null, "e": 1493, "s": 1214, "text": "There are many different basic sorting algorithms. Some perform faster and use less memory than others. Some are better suited to big data and some work better if the data are arranged in certain ways. See the chart below for time and space complexity of many common algorithms." }, { "code": null, "e": 1819, "s": 1493, "text": "Being an expert at basic implementations isn’t necessary for most data science problems. In fact, premature optimization is occasionally cited as the root of all evil. However, knowing which library and which keyword arguments to use can be quite helpful when you need to repeatedly sort a lot of data. Here’s my cheat sheet." }, { "code": null, "e": 1965, "s": 1819, "text": "The sorting algorithms have changed over the years in many libraries. The following software versions were used in the analysis for this article:" }, { "code": null, "e": 2081, "s": 1965, "text": "python 3.6.8numpy 1.16.4pandas 0.24.2tensorflow==2.0.0-beta1 #tensorflow-gpu==2.0.0-beta1 slows sortingpytorch 1.1" }, { "code": null, "e": 2110, "s": 2081, "text": "Let’s start with the basics." }, { "code": null, "e": 2156, "s": 2110, "text": "Python contains two built-in sorting methods." }, { "code": null, "e": 2236, "s": 2156, "text": "my_list.sort() sorts a list in-place. It mutates the list. sort() returns None." }, { "code": null, "e": 2373, "s": 2236, "text": "sorted(my_list) makes a sorted copy of any iterable. sorted() returns the sorted iterable. sort() does not mutate the original iterable." }, { "code": null, "e": 2551, "s": 2373, "text": "sort() should be faster because it is in place. Surprisingly, that’s not what I found in the test below. In-place sorting is more dangerous because it mutates the original data." }, { "code": null, "e": 2866, "s": 2551, "text": "For vanilla Python all of the implementations we’ll look at in this article, the default sorting order is ascending — from smallest to largest. Most sorting methods accept a keyword parameter to switch the sort order to descending. Unfortunately for your brain, this parameter name is different for each library. 😦" }, { "code": null, "e": 2946, "s": 2866, "text": "To change either sort order to descending in vanilla Python, pass reverse=True." }, { "code": null, "e": 3090, "s": 2946, "text": "key can be passed as a keyword argument to create your own sort criteria. For example, sort(key=len) will sort by the length of each list item." }, { "code": null, "e": 3395, "s": 3090, "text": "The only sorting algorithm used in vanilla Python is Timsort. Timsort chooses a sorting method depending upon the characteristics of the data to be sorted. For example, if a short list is to be sorted, then an insertion sort is used. See Brandon Skerritt’s great article for more details on Timsort here." }, { "code": null, "e": 3557, "s": 3395, "text": "Timsort, and thus Vanilla Python sorts, are stable. This means that if multiple values are the same, then those items remain in the original order after sorting." }, { "code": null, "e": 3813, "s": 3557, "text": "To remember sort() vs. sorted(), I just remember that sorted is a longer word than sort and that sorted should take longer to run because it has to make a copy. Although the results below didn’t support the conventional wisdom, the mnemonic still works. 😃" }, { "code": null, "e": 3844, "s": 3813, "text": "Now let’s look at using NumPy." }, { "code": null, "e": 4011, "s": 3844, "text": "NumPy is the bedrock Python library for scientific computing. Like vanilla Python, it has two sort implementations, one that mutates the array and one that copies it." }, { "code": null, "e": 4084, "s": 4011, "text": "my_array.sort() mutates the array in place and returns the sorted array." }, { "code": null, "e": 4179, "s": 4084, "text": "np.sort(my_array) returns a copy of the sorted array, so it doesn’t mutate the original array." }, { "code": null, "e": 4212, "s": 4179, "text": "Here are the optional arguments." }, { "code": null, "e": 4314, "s": 4212, "text": "axis : int, optional — Axis along which to sort. Default is -1, which means sort along the last axis." }, { "code": null, "e": 4445, "s": 4314, "text": "kind : {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional — Sorting algorithm. Default is ‘quicksort’. More on this below." }, { "code": null, "e": 4782, "s": 4445, "text": "order : str or list of str, optional — When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties." }, { "code": null, "e": 4978, "s": 4782, "text": "The sorting algorithms used are now a bit different than you might expect based on their names. Passing kind=quicksort means sorting actually starts with an introsort algorithm. The docs explain:" }, { "code": null, "e": 5121, "s": 4978, "text": "When [it] does not make enough progress it switches to a heapsort algorithm This implementation makes quicksort O(n*log(n)) in the worst case." }, { "code": null, "e": 5448, "s": 5121, "text": "stable automatically chooses the best stable sorting algorithm for the data type being sorted. It, along with mergesort is currently mapped to timsort or radix sort depending on the data type. API forward compatibility currently limits the ability to select the implementation and it is hardwired for the different data types." }, { "code": null, "e": 5746, "s": 5448, "text": "Timsort is added for better performance on already or nearly sorted data. On random data timsort is almost identical to mergesort. It is now used for stable sort while quicksort is still the default sort if none is chosen...‘mergesort’ and ‘stable’ are mapped to radix sort for integer data types." }, { "code": null, "e": 5796, "s": 5746, "text": "- From the NumPy docs —( after some of my edits)." }, { "code": null, "e": 6132, "s": 5796, "text": "One take-away is that NumPy provides a wider range of control for sorting algorithm options than vanilla Python. A second take-away is that the kind keyword value doesn’t necessarily correspond to the actual sort type used. A final take-away is that the mergesort and stable values are stable sorts, but quicksort and heapsort are not." }, { "code": null, "e": 6317, "s": 6132, "text": "NumPy sorts are the only implementations on our list without a keyword argument to reverse the sort order. Luckily, it’s quick to reverse an array with a slice like this: my_arr[::-1]." }, { "code": null, "e": 6449, "s": 6317, "text": "The NumPy algorithm options are also available in the more user-friendly pandas — and I find the functions easier to keep straight." }, { "code": null, "e": 6559, "s": 6449, "text": "Sort a pandas DataFrame with df.sort_values(by=my_column). There are a number of keyword arguments available." }, { "code": null, "e": 6783, "s": 6559, "text": "by: str or list of str, required — Name or list of names to sort by. If axis is 0 or index then by may contain index levels and/or column labels. If axis is 1 or columns then by may contain column levels and/or index labels" }, { "code": null, "e": 6848, "s": 6783, "text": "axis: {0 or index, 1 or columns}, default 0 — Axis to be sorted." }, { "code": null, "e": 7036, "s": 6848, "text": "ascending: bool or list of bool, default True — Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by argument." }, { "code": null, "e": 7104, "s": 7036, "text": "inplace: bool, default False — if True, perform operation in-place." }, { "code": null, "e": 7337, "s": 7104, "text": "kind: {quicksort, mergesort, heapsort, or stable}, default quicksort — Choice of sorting algorithm. See also ndarray.np.sort for more information. For DataFrames, this option is only applied when sorting on a single column or label." }, { "code": null, "e": 7447, "s": 7337, "text": "na_position: {‘first’, ‘last’}, default ‘last’ — first puts NaNs at the beginning, last puts NaNs at the end." }, { "code": null, "e": 7585, "s": 7447, "text": "Sort a pandas Series by following the same syntax. With a Series you don’t provide a by keyword, because you don’t have multiple columns." }, { "code": null, "e": 7761, "s": 7585, "text": "Because pandas uses NumPy under the hood, you have the same nicely optimized sorting options at your fingertips. However, pandas requires some extra time for its conveniences." }, { "code": null, "e": 8185, "s": 7761, "text": "The default when sorting by a single column is to use NumPy’s quicksort. You’ll recall quicksort is now actually an introsort that becomes a heapsort if the sorting progress is slow. Pandas ensures that sorting by multiple columns uses NumPy’s mergesort. Mergesort in NumPy actually uses Timsort or Radix sort algorithms. These are stable sorting algorithms and stable sorting is necessary when sorting by multiple columns." }, { "code": null, "e": 8231, "s": 8185, "text": "The key things to try to remember for pandas:" }, { "code": null, "e": 8265, "s": 8231, "text": "The function name: sort_values()." }, { "code": null, "e": 8316, "s": 8265, "text": "You need by=column_name or a list of column names." }, { "code": null, "e": 8356, "s": 8316, "text": "ascending is the keyword for reversing." }, { "code": null, "e": 8397, "s": 8356, "text": "Use mergesort if you want a stable sort." }, { "code": null, "e": 8624, "s": 8397, "text": "When doing exploratory data analysis with pandas, I often find myself summing and sorting values in a pandas DataFrame with Series.value_counts(). Here’s a code snippet to sum and sort the most frequent values for each column." }, { "code": null, "e": 8709, "s": 8624, "text": "for c in df.columns: print(f\"---- {c} ---\") print(df[c].value_counts().head())" }, { "code": null, "e": 9079, "s": 8709, "text": "Sorting in pandas is a nice option for exploratory data analysis on smaller datasets. Dask implements much of the pandas API when your data won’t fit in memory. Dask doesn’t have a parallel sorting implementation as of mid 2019, although it’s being discussed. When you have a lot of data and want parallelized search on a GPU, you may want to use TensorFlow or PyTorch." }, { "code": null, "e": 9264, "s": 9079, "text": "TensorFlow is the most popular deep learning framework. See my article on deep learning framework popularity and usage here. The following infois for the GPU version of TensorFlow 2.0." }, { "code": null, "e": 9338, "s": 9264, "text": "tf.sort(my_tensor) returns a sorted copy of a tensor. Optional arguments:" }, { "code": null, "e": 9436, "s": 9338, "text": "axis: {int, optional} The axis along which to sort. The default is -1, which sorts the last axis." }, { "code": null, "e": 9514, "s": 9436, "text": "direction: {ascending or descending} — direction in which to sort the values." }, { "code": null, "e": 9562, "s": 9514, "text": "name: {str, optional} — name for the operation." }, { "code": null, "e": 9882, "s": 9562, "text": "tf.sort uses the top_k() method behind the scenes. top_k uses CUB library for CUDA GPUs to make parallelism easier to implement. As the docs explain “CUB provides state-of-the-art, reusable software components for every layer of the CUDA programming model.” TensorFlow uses radix sort on GPU via CUB, as discussed here." }, { "code": null, "e": 10174, "s": 9882, "text": "TensorFlow GPU info can be found here. To enable GPU capabilities with TensorFlow 2.0 you need to pip3 install tensorflow-gpu==2.0.0-beta1. As we’ll see from the evaluation below, you might want to stick with tensorflow==2.0.0-beta1 if all you are doing in sorting (which isn’t very likely)." }, { "code": null, "e": 10268, "s": 10174, "text": "Use the following code snippet to see whether each line of code is running on the CPU or GPU:" }, { "code": null, "e": 10312, "s": 10268, "text": "tf.debugging.set_log_device_placement(True)" }, { "code": null, "e": 10375, "s": 10312, "text": "To specify you want to use a GPU use the following with block:" }, { "code": null, "e": 10430, "s": 10375, "text": "with tf.device('/GPU:0'): %time tf.sort(my_tf_tensor)" }, { "code": null, "e": 10476, "s": 10430, "text": "use with tf.device('/CPU:0'): to use the CPU." }, { "code": null, "e": 10623, "s": 10476, "text": "tf.sort() is a pretty intuitive method to remember and use if you work in TensorFlow. Just remember direction=descending to switch the sort order." }, { "code": null, "e": 10702, "s": 10623, "text": "Now let’s look at sorting in the other popular deep learning package, PyTorch." }, { "code": null, "e": 10779, "s": 10702, "text": "torch.sort(my_tensor) returns a sorted copy of a tensor. Optional arguments:" }, { "code": null, "e": 10830, "s": 10779, "text": "dim: {int, optional} — the dimension to sort along" }, { "code": null, "e": 10915, "s": 10830, "text": "descending: {bool, optional} — controls the sorting order (ascending or descending)." }, { "code": null, "e": 11040, "s": 10915, "text": "out: {tuple, optional} — the output tuple of (Tensor, LongTensor) that can be optionally given to be used as output buffers." }, { "code": null, "e": 11109, "s": 11040, "text": "Specify you want to use the GPU by appending .cuda() to your tensor." }, { "code": null, "e": 11173, "s": 11109, "text": "gpu_tensor=my_pytorch_tensor.cuda()%time torch.sort(gpu_tensor)" }, { "code": null, "e": 11303, "s": 11173, "text": "PyTorch uses a segmented parallel sort via Thrust if a dataset any larger than 1 million rows by 100,000 columns is being sorted." }, { "code": null, "e": 11731, "s": 11303, "text": "Thrust is a parallel algorithms library that enables performance portability between GPUs and multicore CPUs. It provides a sort primitive that selects the most efficient implementation automatically. The CUB library used by TensorFlow wraps thrust. So if you drill down far enough you see that PyTorch and TensorFlow are using similar implementations for GPU sorting under the hood — whatever thrust chooses for the situation." }, { "code": null, "e": 11990, "s": 11731, "text": "Unfortunately, the Google Colab server ran out of memory when trying to to create 1.1M x 100K random data points via NumPy. 😦 So I moved to Google Cloud Platform (GCP) with 416 MB of RAM and still ran out of memory. 😦 😦 So I had to stay under 1 million rows." }, { "code": null, "e": 12224, "s": 11990, "text": "Segmented sort and locality sort are high-performance variants of mergesort that operate on non-uniform random data. Segmented sort allows us to sort many variable-length arrays in parallel. — https://moderngpu.github.io/segsort.html" }, { "code": null, "e": 12534, "s": 12224, "text": "Like TensorFlow, the sorting method in PyTorch isn’t too rough to remember: torch.sort(). The only tricky thing is the keyword argument for the direction of the sorted values: TensorFlow uses direction while PyTorch uses descending. And don’t forget to use .cuda() to get a speed boost with large data sets. 😉" }, { "code": null, "e": 12735, "s": 12534, "text": "While sorting with GPUs could be a good option for really large datasets, it might also make sense to sort data directly in SQL. I have a brief bonus section on using SQL at the end of this article. 👍" }, { "code": null, "e": 12981, "s": 12735, "text": "For each of the Python libraries above, I conducted an analysis of the wall time to sort the same 1,000,000 data points in a single column, array, or list. I used a Google Colab Jupyter Notebook with a K80 GPU and Intel(R) Xeon(R) CPU @ 2.30GHz." }, { "code": null, "e": 13013, "s": 12981, "text": "PyTorch with GPU is super fast." }, { "code": null, "e": 13091, "s": 13013, "text": "For both NumPy and pandas, inplace is generally faster than copying the data." }, { "code": null, "e": 13136, "s": 13091, "text": "The default pandas quicksort is rather fast." }, { "code": null, "e": 13214, "s": 13136, "text": "Most pandas functions are comparatively slower than their NumPy counterparts." }, { "code": null, "e": 13371, "s": 13214, "text": "TensorFlow CPU is quite fast. The GPU install slows down TensorFlow even when the CPU is used. The GPU sort is quite slow. This looks like a possible bug. 🐞" }, { "code": null, "e": 13580, "s": 13371, "text": "Vanilla Python inplace sorting is surprisingly slow. It was nearly 100x slower than the PyTorch GPU-enabled sort. I tested it multiple times (with different data) to double check that this was not an anomaly." }, { "code": null, "e": 13650, "s": 13580, "text": "Again, this is just one small test. It’s definitely not definitive. 😉" }, { "code": null, "e": 13982, "s": 13650, "text": "You generally shouldn’t need custom sorting implementations. The off-the shelf options are strong. They are generally not using just a single sorting method. Instead they evaluate the data first and then use a sorting algorithm that performs well. Some implementations even change algorithms if the sort is not progressing quickly." }, { "code": null, "e": 14183, "s": 13982, "text": "In this article, you’ve seen how to sort in many Python data science libraries. I hope you’ve found it helpful. If you have, please share it on your favorite social media so others can find it, too. 👏" }, { "code": null, "e": 14339, "s": 14183, "text": "You just need to remember which option to choose and how to call it. Use my cheat sheet above to save time. 👍 My general recommendations are the following:" }, { "code": null, "e": 14422, "s": 14339, "text": "Use the default pandas sort_values() for exploration on relatively small datasets." }, { "code": null, "e": 14558, "s": 14422, "text": "For large datasets or when speed is at a premium, try NumPy’s in-place mergesort. For even more of a speed boost, use PyTorch on a GPU." }, { "code": null, "e": 14801, "s": 14558, "text": "Sorting on GPUs isn’t something I’ve seen much written about. It’s an area that appears ripe for more research and tutorials. Here’s a 2017 article to give you a taste of recent research. More info on GPU sorting algorithms can be found here." }, { "code": null, "e": 14877, "s": 14801, "text": "Sorting in SQL is often very fast, particularly when the sort is in-memory." }, { "code": null, "e": 15223, "s": 14877, "text": "SQL is a specification, but doesn’t dictate things like which sort algorithm an implementation must use. Postgres uses a disk merge sort, heap sort, or quick sort, depending upon the circumstances. If you have enough memory, sorts can become much faster by making them in-memory. Increase the available memory for sorts via the work_mem setting." }, { "code": null, "e": 15386, "s": 15223, "text": "Other SQL implementations use different sorting algorithms. For example, Google BigQuery uses introsort with some tricks, according to this Stack Overflow answer." }, { "code": null, "e": 15568, "s": 15386, "text": "Sorts in SQL are performed with the ORDER BY command. This syntax is distinct from the Python implementations that all use some form of the word sort. At least ORDER BY is unique! 😃" }, { "code": null, "e": 15710, "s": 15568, "text": "To make the sort descending, use the keyword DESC. A query to return customers in alphabetical order from last to first would look like this:" }, { "code": null, "e": 15758, "s": 15710, "text": "SELECT Names FROM CustomersORDER BY Names DESC;" }, { "code": null, "e": 15891, "s": 15758, "text": "I write about Python, Docker, data science, and more. If any of that’s of interest to you, read more here and follow me on Medium. 😄" } ]
Google Colab - Magics
Magics is a set of system commands that provide a mini extensive command language. Magics are of two types − Line magics Line magics Cell magics Cell magics The line magics as the name indicates that it consists of a single line of command, while the cell magic covers the entire body of the code cell. In case of line magics, the command is prepended with a single % character and in the case of cell magics, it is prepended with two % characters (%%). Let us look into some examples of both to illustrate these. Type the following code in your code cell − %ldir You will see the contents of your local directory, something like this - drwxr-xr-x 3 root 4096 Jun 20 10:05 drive/ drwxr-xr-x 1 root 4096 May 31 16:17 sample_data/ Try the following command − %history This presents the complete history of commands that you have previously executed. Type in the following code in your code cell − %%html <marquee style='width: 50%; color: Green;'>Welcome to Tutorialspoint!</marquee> Now, if you run the code and you will see the scrolling welcome message on the screen as shown here − The following code will add SVG to your document. %%html <svg xmlns="https://www.w3.org/2000/svg" viewBox="0 0 600 400" width="400" height="400"> <rect x="10" y="00" width="300" height="100" rx="0" style="fill:orange; stroke:black; fill-opacity:1.0" /> <rect x="10" y="100" width="300" height="100" rx="0" style="fill:white; stroke:black; fill-opacity:1.0;" /> <rect x="10" y="200" width="300" height="100" rx="0" style="fill:green; stroke:black; fill-opacity:1.0;" /> </svg> If you run the code, you would see the following output − To get a complete list of supported magics, execute the following command − %lsmagic You will see the following output − Available line magics: %alias %alias_magic %autocall %automagic %autosave %bookmark %cat %cd %clear %colors %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %shell %store %sx %system %tb %tensorflow_version %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode Available cell magics: %%! %%HTML %%SVG %%bash %%bigquery %%capture %%debug %%file %%html %%javascript %%js %%latex %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%shell %%svg %%sx %%system %%time %%timeit %%writefile Automagic is ON, % prefix IS NOT needed for line magics. Next, you will learn another powerful feature in Colab to set the program variables at runtime. 20 Lectures 2.5 hours Asif Hussain 7 Lectures 1 hours Aditya Kulkarni 33 Lectures 2.5 hours Sasha Miller 22 Lectures 1.5 hours Zach Miller 16 Lectures 1.5 hours Sasha Miller 23 Lectures 2.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2124, "s": 2041, "text": "Magics is a set of system commands that provide a mini extensive command language." }, { "code": null, "e": 2150, "s": 2124, "text": "Magics are of two types −" }, { "code": null, "e": 2162, "s": 2150, "text": "Line magics" }, { "code": null, "e": 2174, "s": 2162, "text": "Line magics" }, { "code": null, "e": 2186, "s": 2174, "text": "Cell magics" }, { "code": null, "e": 2198, "s": 2186, "text": "Cell magics" }, { "code": null, "e": 2344, "s": 2198, "text": "The line magics as the name indicates that it consists of a single line of command, while the cell magic covers the entire body of the code cell." }, { "code": null, "e": 2495, "s": 2344, "text": "In case of line magics, the command is prepended with a single % character and in the case of cell magics, it is prepended with two % characters (%%)." }, { "code": null, "e": 2555, "s": 2495, "text": "Let us look into some examples of both to illustrate these." }, { "code": null, "e": 2599, "s": 2555, "text": "Type the following code in your code cell −" }, { "code": null, "e": 2606, "s": 2599, "text": "%ldir\n" }, { "code": null, "e": 2679, "s": 2606, "text": "You will see the contents of your local directory, something like this -" }, { "code": null, "e": 2772, "s": 2679, "text": "drwxr-xr-x 3 root 4096 Jun 20 10:05 drive/\ndrwxr-xr-x 1 root 4096 May 31 16:17 sample_data/\n" }, { "code": null, "e": 2800, "s": 2772, "text": "Try the following command −" }, { "code": null, "e": 2810, "s": 2800, "text": "%history\n" }, { "code": null, "e": 2892, "s": 2810, "text": "This presents the complete history of commands that you have previously executed." }, { "code": null, "e": 2939, "s": 2892, "text": "Type in the following code in your code cell −" }, { "code": null, "e": 3027, "s": 2939, "text": "%%html\n<marquee style='width: 50%; color: Green;'>Welcome to Tutorialspoint!</marquee>\n" }, { "code": null, "e": 3129, "s": 3027, "text": "Now, if you run the code and you will see the scrolling welcome message on the screen as shown here −" }, { "code": null, "e": 3179, "s": 3129, "text": "The following code will add SVG to your document." }, { "code": null, "e": 3615, "s": 3179, "text": "%%html\n<svg xmlns=\"https://www.w3.org/2000/svg\" viewBox=\"0 0 600 400\" width=\"400\" height=\"400\">\n <rect x=\"10\" y=\"00\" width=\"300\" height=\"100\" rx=\"0\" style=\"fill:orange; stroke:black; fill-opacity:1.0\" />\n <rect x=\"10\" y=\"100\" width=\"300\" height=\"100\" rx=\"0\" style=\"fill:white; stroke:black; fill-opacity:1.0;\" />\n <rect x=\"10\" y=\"200\" width=\"300\" height=\"100\" rx=\"0\" style=\"fill:green; stroke:black; fill-opacity:1.0;\" />\n</svg>\n" }, { "code": null, "e": 3673, "s": 3615, "text": "If you run the code, you would see the following output −" }, { "code": null, "e": 3749, "s": 3673, "text": "To get a complete list of supported magics, execute the following command −" }, { "code": null, "e": 3759, "s": 3749, "text": "%lsmagic\n" }, { "code": null, "e": 3795, "s": 3759, "text": "You will see the following output −" }, { "code": null, "e": 4865, "s": 3795, "text": "Available line magics:\n%alias %alias_magic %autocall %automagic %autosave %bookmark %cat %cd %clear\n%colors %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit\n%env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext\n%loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro\n%magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef\n%pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %profile %prun\n%psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall\n%rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save\n%sc %set_env %shell %store %sx %system %tb %tensorflow_version %time %timeit\n%unalias %unload_ext %who %who_ls %whos %xdel %xmode\n\nAvailable cell magics:\n%%! %%HTML %%SVG %%bash %%bigquery %%capture %%debug %%file %%html %%javascript\n%%js %%latex %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script\n%%sh %%shell %%svg %%sx %%system %%time %%timeit %%writefile\n\nAutomagic is ON, % prefix IS NOT needed for line magics.\n" }, { "code": null, "e": 4961, "s": 4865, "text": "Next, you will learn another powerful feature in Colab to set the program variables at runtime." }, { "code": null, "e": 4996, "s": 4961, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5010, "s": 4996, "text": " Asif Hussain" }, { "code": null, "e": 5042, "s": 5010, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 5059, "s": 5042, "text": " Aditya Kulkarni" }, { "code": null, "e": 5094, "s": 5059, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5108, "s": 5094, "text": " Sasha Miller" }, { "code": null, "e": 5143, "s": 5108, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5156, "s": 5143, "text": " Zach Miller" }, { "code": null, "e": 5191, "s": 5156, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5205, "s": 5191, "text": " Sasha Miller" }, { "code": null, "e": 5240, "s": 5205, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5254, "s": 5240, "text": " Sasha Miller" }, { "code": null, "e": 5261, "s": 5254, "text": " Print" }, { "code": null, "e": 5272, "s": 5261, "text": " Add Notes" } ]
Add a method to a JavaScript object constructor?
Adding a method to an object constructor is unlike adding a method to a normal object. We cannot add a method as it is the case with a normal object. To make a method in an object constructor it has to be added inside the object constructor. In the following example, the method is added inside the constructor, therefore, we have got a legitimate value. Live Demo <html> <body> <script> function Business(name, property, age, designation) { this.Name = name; this.prop = property; this.age = age; this.designation = designation; this.name = function() { return this.Name }; } var person1 = new Business("Trump", "$28.05billion", "73", "President"); document.write(person1.name()); </script> </body> </html> Trump
[ { "code": null, "e": 1304, "s": 1062, "text": "Adding a method to an object constructor is unlike adding a method to a normal object. We cannot add a method as it is the case with a normal object. To make a method in an object constructor it has to be added inside the object constructor." }, { "code": null, "e": 1417, "s": 1304, "text": "In the following example, the method is added inside the constructor, therefore, we have got a legitimate value." }, { "code": null, "e": 1427, "s": 1417, "text": "Live Demo" }, { "code": null, "e": 1827, "s": 1427, "text": "<html>\n<body>\n<script>\n function Business(name, property, age, designation) {\n this.Name = name;\n this.prop = property;\n this.age = age;\n this.designation = designation;\n this.name = function() {\n return this.Name\n };\n }\n var person1 = new Business(\"Trump\", \"$28.05billion\", \"73\", \"President\");\n document.write(person1.name());\n</script>\n</body>\n</html>" }, { "code": null, "e": 1833, "s": 1827, "text": "Trump" } ]
How to determine database type (name) for a given JDBC connection?
One way to get the name of the underlying database you have connected with is by invoking the getDatabaseProductName() method of the DatabaseMetaData interface. This method returns the name of the underlying database in String format. Therefore, to retrieve the name of your current database using Java code − Retrieve the DatabaseMetaData object of the current Connection using the getMetaData() method. //Retrieving the meta data object DatabaseMetaData metaData = con.getMetaData(); Then, get the product name of the underlying database you have connected to using the getDatabaseProductName() method of the DatabaseMetaData interface as − //retrieving the name of the database String product_name = metaData.getDatabaseProductName(); Following JDBC program establishes connection with the database, retrieves and prints the name of the underlying database. import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.SQLException; public class DatabaseMetaData_getDatabaseProductName { 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......"); //Retrieving the meta data object DatabaseMetaData metaData = con.getMetaData(); //retrieving the name of the database String product_name = metaData.getDatabaseProductName(); System.out.println("Name of the underlying database: "+product_name); } } Connection established...... Name of the underlying database: MySQL
[ { "code": null, "e": 1297, "s": 1062, "text": "One way to get the name of the underlying database you have connected with is by invoking the getDatabaseProductName() method of the DatabaseMetaData interface. This method returns the name of the underlying database in String format." }, { "code": null, "e": 1372, "s": 1297, "text": "Therefore, to retrieve the name of your current database using Java code −" }, { "code": null, "e": 1467, "s": 1372, "text": "Retrieve the DatabaseMetaData object of the current Connection using the getMetaData() method." }, { "code": null, "e": 1548, "s": 1467, "text": "//Retrieving the meta data object\nDatabaseMetaData metaData = con.getMetaData();" }, { "code": null, "e": 1705, "s": 1548, "text": "Then, get the product name of the underlying database you have connected to using the getDatabaseProductName() method of the DatabaseMetaData interface as −" }, { "code": null, "e": 1800, "s": 1705, "text": "//retrieving the name of the database\nString product_name = metaData.getDatabaseProductName();" }, { "code": null, "e": 1923, "s": 1800, "text": "Following JDBC program establishes connection with the database, retrieves and prints the name of the underlying database." }, { "code": null, "e": 2776, "s": 1923, "text": "import java.sql.Connection;\nimport java.sql.DatabaseMetaData;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\npublic class DatabaseMetaData_getDatabaseProductName {\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 //Retrieving the meta data object\n DatabaseMetaData metaData = con.getMetaData();\n //retrieving the name of the database\n String product_name = metaData.getDatabaseProductName();\n System.out.println(\"Name of the underlying database: \"+product_name);\n }\n}" }, { "code": null, "e": 2844, "s": 2776, "text": "Connection established......\nName of the underlying database: MySQL" } ]
How to Add Live Camera Preview to UIView in Swift?
To add a live camera preview to our default UIView in swift we can either use AVFoundation framework of iOS SDK or native UIImagePickerController(). In this example we’ll be using ImagePicker as our aim is to present camera preview on the UIView and Imagepicker is suitable for that task. AVFoundation can be used when we need a lot of customization on our camera or different types of custom actions. To show a camera preview on the UIView we need to perform the following steps. Create a UIImagePickerController object. Create a UIImagePickerController object. Conform our class to UIImagePickerControllerDelegate and UINavigationControllerDelegate. Conform our class to UIImagePickerControllerDelegate and UINavigationControllerDelegate. Assign delegates to the object we created in step one. Assign delegates to the object we created in step one. Add the object we created as a child Add the object we created as a child Add the child's view as a subView to our UIView. Add the child's view as a subView to our UIView. To achieve the same we’ll use the code below override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib let imgPicker = UIImagePickerController() if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerController.CameraDevice.front) { imgPicker.delegate = self imgPicker.sourceType = .camera addChild(imgPicker) self.view.addSubview(imgPicker.view) imgPicker.view.frame = self.view.bounds imgPicker.allowsEditing = false imgPicker.showsCameraControls = false imgPicker.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] } } For this example we have not written any function and we directly created objects here, but it’s always a good choice to use lazy variables in situations where we might not need to use some variable. This code will not work on a simulator as it makes use of camera. When I run the above code on an iPhone 7+, below is the result that’s produced.
[ { "code": null, "e": 1464, "s": 1062, "text": "To add a live camera preview to our default UIView in swift we can either use AVFoundation framework of iOS SDK or native UIImagePickerController(). In this example we’ll be using ImagePicker as our aim is to present camera preview on the UIView and Imagepicker is suitable for that task. AVFoundation can be used when we need a lot of customization on our camera or different types of custom actions." }, { "code": null, "e": 1543, "s": 1464, "text": "To show a camera preview on the UIView we need to perform the following steps." }, { "code": null, "e": 1584, "s": 1543, "text": "Create a UIImagePickerController object." }, { "code": null, "e": 1625, "s": 1584, "text": "Create a UIImagePickerController object." }, { "code": null, "e": 1714, "s": 1625, "text": "Conform our class to UIImagePickerControllerDelegate and UINavigationControllerDelegate." }, { "code": null, "e": 1803, "s": 1714, "text": "Conform our class to UIImagePickerControllerDelegate and UINavigationControllerDelegate." }, { "code": null, "e": 1858, "s": 1803, "text": "Assign delegates to the object we created in step one." }, { "code": null, "e": 1913, "s": 1858, "text": "Assign delegates to the object we created in step one." }, { "code": null, "e": 1950, "s": 1913, "text": "Add the object we created as a child" }, { "code": null, "e": 1987, "s": 1950, "text": "Add the object we created as a child" }, { "code": null, "e": 2036, "s": 1987, "text": "Add the child's view as a subView to our UIView." }, { "code": null, "e": 2085, "s": 2036, "text": "Add the child's view as a subView to our UIView." }, { "code": null, "e": 2130, "s": 2085, "text": "To achieve the same we’ll use the code below" }, { "code": null, "e": 2752, "s": 2130, "text": "override func viewDidLoad() {\n super.viewDidLoad()\n // Do any additional setup after loading the view, typically from a nib\n let imgPicker = UIImagePickerController()\n if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerController.CameraDevice.front) {\n imgPicker.delegate = self\n imgPicker.sourceType = .camera\n\n addChild(imgPicker)\n self.view.addSubview(imgPicker.view)\n imgPicker.view.frame = self.view.bounds\n imgPicker.allowsEditing = false\n imgPicker.showsCameraControls = false\n imgPicker.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]\n }\n}" }, { "code": null, "e": 2952, "s": 2752, "text": "For this example we have not written any function and we directly created objects here, but it’s always a good choice to use lazy variables in situations where we might not need to use some variable." }, { "code": null, "e": 3098, "s": 2952, "text": "This code will not work on a simulator as it makes use of camera. When I run the above code on an iPhone 7+, below is the result that’s produced." } ]
Tryit Editor v3.7
Tryit: Using the animation-direction property
[]
How can I select the row with the highest ID in MySQL?
You can select the row with highest ID in MySQL with the help of ORDER BY with LIMIT OFFSET The syntax is as follows − select *from yourTableName order by yourColumnName desc limit 1 offset 0; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table HighestIdOrderBy −> ( −> EmployeeId int, −> EmployeeName varchar(200) −> ); Query OK, 0 rows affected (0.58 sec) Insert records in the table with the help of insert command. The query is as follows − mysql> insert into HighestIdOrderBy values(200,'David'); Query OK, 1 row affected (0.20 sec) mysql> insert into HighestIdOrderBy values(1000,'Bob'); Query OK, 1 row affected (0.18 sec) mysql> insert into HighestIdOrderBy values(600,'John'); Query OK, 1 row affected (0.16 sec) mysql> insert into HighestIdOrderBy values(300,'Johnson'); Query OK, 1 row affected (0.18 sec) mysql> insert into HighestIdOrderBy values(100,'Carol'); Query OK, 1 row affected (0.12 sec) Display all records from the table with select statement. The query is as follows − mysql> select *from HighestIdOrderBy; The following is the output − +------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 200 | David | | 1000 | Bob | | 600 | John | | 300 | Johnson | | 100 | Carol | +------------+--------------+ 5 rows in set (0.00 sec) Here is the query to select maximum id from MySQL table. The query is as follows − mysql> select *from HighestIdOrderBy order by EmployeeId desc limit 1 offset 0; The following is the output − +------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 1000 | Bob | +------------+--------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1154, "s": 1062, "text": "You can select the row with highest ID in MySQL with the help of ORDER BY with LIMIT OFFSET" }, { "code": null, "e": 1181, "s": 1154, "text": "The syntax is as follows −" }, { "code": null, "e": 1255, "s": 1181, "text": "select *from yourTableName order by yourColumnName desc limit 1 offset 0;" }, { "code": null, "e": 1354, "s": 1255, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1499, "s": 1354, "text": "mysql> create table HighestIdOrderBy\n −> (\n −> EmployeeId int,\n −> EmployeeName varchar(200)\n −> );\nQuery OK, 0 rows affected (0.58 sec)" }, { "code": null, "e": 1586, "s": 1499, "text": "Insert records in the table with the help of insert command. The query is as follows −" }, { "code": null, "e": 2055, "s": 1586, "text": "mysql> insert into HighestIdOrderBy values(200,'David');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into HighestIdOrderBy values(1000,'Bob');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into HighestIdOrderBy values(600,'John');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into HighestIdOrderBy values(300,'Johnson');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into HighestIdOrderBy values(100,'Carol');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 2139, "s": 2055, "text": "Display all records from the table with select statement. The query is as follows −" }, { "code": null, "e": 2177, "s": 2139, "text": "mysql> select *from HighestIdOrderBy;" }, { "code": null, "e": 2207, "s": 2177, "text": "The following is the output −" }, { "code": null, "e": 2501, "s": 2207, "text": "+------------+--------------+\n| EmployeeId | EmployeeName |\n+------------+--------------+\n| 200 | David |\n| 1000 | Bob |\n| 600 | John |\n| 300 | Johnson |\n| 100 | Carol |\n+------------+--------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2584, "s": 2501, "text": "Here is the query to select maximum id from MySQL table. The query is as follows −" }, { "code": null, "e": 2664, "s": 2584, "text": "mysql> select *from HighestIdOrderBy order by EmployeeId desc limit 1 offset 0;" }, { "code": null, "e": 2694, "s": 2664, "text": "The following is the output −" }, { "code": null, "e": 2868, "s": 2694, "text": "+------------+--------------+\n| EmployeeId | EmployeeName |\n+------------+--------------+\n| 1000 | Bob |\n+------------+--------------+\n1 row in set (0.00 sec)" } ]
PHP - Function ereg_replace()
string ereg_replace (string pattern, string replacement, string originalstring); The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found. The ereg_replace() function operates under the same premises as ereg(), except that the functionality is extended to finding and replacing pattern instead of simply locating it. Like ereg(), ereg_replace() is case sensitive. After the replacement has occurred, the modified string will be returned. After the replacement has occurred, the modified string will be returned. If no matches are found, the string will remain unchanged. If no matches are found, the string will remain unchanged. Following is the piece of code, copy and paste this code into a file and verify the result. <?php $copy_date = "Copyright 1999"; $copy_date = ereg_replace("([0-9]+)", "2000", $copy_date); print $copy_date; ?> This will produce the following result − 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2839, "s": 2757, "text": "string ereg_replace (string pattern, string replacement, string originalstring);\n" }, { "code": null, "e": 3134, "s": 2839, "text": "The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found. The ereg_replace() function operates under the same premises as ereg(), except that the functionality is extended to finding and replacing pattern instead of simply locating it." }, { "code": null, "e": 3181, "s": 3134, "text": "Like ereg(), ereg_replace() is case sensitive." }, { "code": null, "e": 3255, "s": 3181, "text": "After the replacement has occurred, the modified string will be returned." }, { "code": null, "e": 3329, "s": 3255, "text": "After the replacement has occurred, the modified string will be returned." }, { "code": null, "e": 3388, "s": 3329, "text": "If no matches are found, the string will remain unchanged." }, { "code": null, "e": 3447, "s": 3388, "text": "If no matches are found, the string will remain unchanged." }, { "code": null, "e": 3539, "s": 3447, "text": "Following is the piece of code, copy and paste this code into a file and verify the result." }, { "code": null, "e": 3669, "s": 3539, "text": "<?php\n $copy_date = \"Copyright 1999\";\n $copy_date = ereg_replace(\"([0-9]+)\", \"2000\", $copy_date);\n \n print $copy_date;\n?>" }, { "code": null, "e": 3710, "s": 3669, "text": "This will produce the following result −" }, { "code": null, "e": 3743, "s": 3710, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 3759, "s": 3743, "text": " Malhar Lathkar" }, { "code": null, "e": 3792, "s": 3759, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3803, "s": 3792, "text": " Syed Raza" }, { "code": null, "e": 3838, "s": 3803, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3855, "s": 3838, "text": " Frahaan Hussain" }, { "code": null, "e": 3888, "s": 3855, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 3903, "s": 3888, "text": " Nivedita Jain" }, { "code": null, "e": 3938, "s": 3903, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 3950, "s": 3938, "text": " Azaz Patel" }, { "code": null, "e": 3985, "s": 3950, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4013, "s": 3985, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4020, "s": 4013, "text": " Print" }, { "code": null, "e": 4031, "s": 4020, "text": " Add Notes" } ]
What is a recursive method call in C#?
Recursive method call in C# is called Recursion. Let us see an example to calculate power of a number using recursion. Here, if the power is not equal to 0, then the function call occurs which is eventually recursion − if (p!=0) { return (n * power(n, p - 1)); } Above, n is the number itself and the power reduces on every iteration as shown below − using System; using System.IO; public class Demo { public static void Main(string[] args) { int n = 5; int p = 2; long res; res = power(n, p); Console.WriteLine(res); } static long power (int n, int p) { if (p!=0) { return (n * power(n, p - 1)); } return 1; } }
[ { "code": null, "e": 1181, "s": 1062, "text": "Recursive method call in C# is called Recursion. Let us see an example to calculate power of a number using recursion." }, { "code": null, "e": 1281, "s": 1181, "text": "Here, if the power is not equal to 0, then the function call occurs which is eventually recursion −" }, { "code": null, "e": 1328, "s": 1281, "text": "if (p!=0) {\n return (n * power(n, p - 1));\n}" }, { "code": null, "e": 1416, "s": 1328, "text": "Above, n is the number itself and the power reduces on every iteration as shown below −" }, { "code": null, "e": 1749, "s": 1416, "text": "using System;\nusing System.IO;\n\npublic class Demo {\n public static void Main(string[] args) {\n int n = 5;\n int p = 2;\n long res;\n res = power(n, p);\n Console.WriteLine(res);\n }\n\n static long power (int n, int p) {\n if (p!=0) {\n return (n * power(n, p - 1));\n }\n return 1;\n }\n}" } ]
Meet Plotly Mapbox. Best Choice for Geographic Data Visualization | by Kefei Mo | Towards Data Science
I have come across several projects that include geographic data, and I have been searching for the best tool for geo-visualization. As a Python user, I have tried Pyplot’s basemap, GeoPandas, Folium, and Bohem, but none of them has given me a satisfying experience. Finally, my search ended after I found Plotly. To be more specific, Plotly’s Mapbox package. Today in this post, I will demonstrate a quick start for geographic data visualization using Plotly Mapbox and show it why you should consider using it as well. Visually appealing. You have to try hard to make it look ugly 😜. Choose the granularity of control. You have broad freedom to control the visualization effects. Interactive is fun. It can be handy for both EDA and dashboard presentations. Varies product lines in different languages (R, Python, Javascript), Stable released versions. Not very steep learning rate. Arguably, but judge by yourself. Eyes on bigdata. With datashader, Plotly can handle data visualization with millions of rows. Open-source. It is FREE!!! Come from my experience, if you are a Python user you are familiar with data visualization tools, like plt, sns you need interactive data visualization, or you want to try it you like free stuff then, Plotly Maxbox is most likely the right choice for you. I would like to mention one more thing about interactive data visualization before we jump into the code. Some people think interactive data visualization is nothing more about the cool effect, and it is solely for presentation. For other applications, like exploratory data analysis (EDA), a static plot should be sufficient. However, for geo-visualization, either a data scientist or an audience often needs to change the scale of the map (for example, by zoom in and out) to understand the information fully; a static plot is just not enough. Without further ado, let’s make geo-visualization. # import packagesimport pandas as pdimport plotly.express as pximport numpy as np# get dataurl = 'https://raw.githubusercontent.com/kefeimo/DataScienceBlog/master/2.geo_plot/df_mapbox_demo.csv'df_plot_tmp = pd.read_csv(url)df_plot_tmp.head()# two-line codefig = px.scatter_mapbox(df_plot_tmp, lat="latitude", lon="longitude", color="gender", zoom=3, mapbox_style='open-street-map')fig.show() TIPS: Click on the ‘EDIT CHART’ button to have a better interactive experience. In the above example, we used ‘open-street-map’ as the back-end tilemap. (Recall that we defined mapbox_style=’open-street-map’.) But actually, I found the Plotly default Mapbox base map is more appealing. To do that, we need to use a Mapbox access token. (A Mapbox access token would be something like this: pk.eyJ1Ijoibxxxxxxxxxxxxx. Here to apply the Public Access Token for free.) mapbox_access_token = 'Your token...'px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat="latitude", lon="longitude", color="gender", zoom=3,# mapbox_style='open-street-map', )fig.show() TIPS: if the token is wrong, you will get an empty plot. (it is there but you are not able to see it.) To solve this problem, double check your token validation or go back to use mapbox_style=’open-street-map’. (also, when using mapbox make sure the internet is connected.) wrong_token = 'xxx'px.set_mapbox_access_token(wrong_token)fig = px.scatter_mapbox(df_plot_tmp, lat="latitude", lon="longitude", color="gender", zoom=3,# mapbox_style='open-street-map', )fig.show() We can further specify the parameters as desired (see how similar it is to seaborn). Things I think worth to play with are: color (similar to hue in seaborn) size zoom, center, (control the first view when the plot is rendered) width, height While things didn’t give me a satisfying outcome is: text (the scatter just disappear somehow when using this. ‘hover_name’ can be an alternative though) Notes: There is no shape control Also, when you play with color, depends on whether it is continuous or categorical, you might wanna furth color_continuous_scale(similar to palette) or specify category_orders, color_discrete_sequence When you play with size, you can play with size_max as well You can choose to open the plot in the notebook (by default) or another window (renderer=’browser’) by setting the renderer. # px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat="latitude", lon="longitude", color="gender", size='hour', size_max=6, category_orders={'gender':list(df_plot_tmp.gender.unique())}, color_discrete_sequence=['#2b83ba', '#fdae61'],# hover_data=1,# hover_name='hour',# text='hour', zoom=3.3,# zoom=2.8, center=dict(lon=105, lat=38), width=900*1.5, height=500*1.5,)fig.show()fig.show(renderer="browser") To solidify our understanding, let’s use age_cate as the color specifier. In this example See how to specify the category order See how to specify the color palette(note in scatter_mapbox the color need to specify in hex, so we need to parse the color to hex by some sort) TIPS: While Plotly has its own palette, but for python, I found the easy way to select a palette is using seaborn sns.color_palette(), all the available pallet can be found in colorbrewer. from matplotlib.colors import to_heximport seaborn as sns# px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat="latitude", lon="longitude", color="age_cate", # size="hour", size_max=15, category_orders={'age_cate':['A22-', 'A23-26', 'A27-28', 'A29-31', 'A32-40', 'A40+']}, color_discrete_sequence=[to_hex(c) for c in sns.color_palette('BrBG_r', 6)], zoom=2.5, center=dict(lon=105, lat=38, ), width=900, height=600,)fig.show() Next, play with the continuous/numerical color. # play with the color: continous/numerical# px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat="latitude", lon="longitude", color="hour", # size="hour", color_continuous_scale=px.colors.cyclical.Twilight, zoom=2.5, center=dict(lon=105, lat=38, ), width=900, height=600,)fig.show() So far, you should have mastered the basic stuff of interactive geo data scatter plot using Plotly. Now let’s discuss some common issues and potential roundabouts. One issue is about overlapping. Sometimes, overlapping results from the dataset itself. You might have noticed the coordinates data (i.e., latitude, longitude) is at 0.01. When plotting on the tilemap, this easily causes overlapping. Note that there is no jitter option. We might have to add jitter to the data manually. (Somehow, I think jitter is not trivial for interactive scatter visualization since the jitter parameter has to change accordingly as the scale change (e.g., zoom in and zoom out). We might need an adaptive jitter method if were to apply jitter to an interactive plot.) In my opinion, to overcome overlapping, a ready-to-go solution is to adjust the scatter size (e.g., decrease the size of scatter to mitigate overlapping). But for px.scatter_mapbox, in 4.8.1 Plotly version, we cannot specify size using an int (no matter what says in the documentary). But there are ways to hack that, for instance, create a column in the data frame designated for scatter size. Try the following code: ‘Hack ’size parameter. # px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat="latitude", lon="longitude", color="gender", size='size_for_plot', size_max=2, category_orders={'gender':list(df_plot_tmp.gender.unique())}, color_discrete_sequence=['#2b83ba', '#fdae61'],# hover_data=1,# hover_name='hour',# text='hour', zoom=2.8, center=dict(lon=105, lat=38), width=900, height=600, title='modified scatter size')fig.show() Manually add jitter # px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat="lat_jitter", lon="lon_jitter", color="age_cate", # size="size_for_plot", size_max=3, category_orders={'age_cate':['A22-', 'A23-26', 'A27-28', 'A29-31', 'A32-40', 'A40+']}, color_discrete_sequence=[to_hex(c) for c in sns.color_palette('BrBG_r', 6)], zoom=10, center=dict(lon=116.4, lat=39.9, ), width=900, height=600, title='add jitter')fig.show() Try Plotly Mapbox, since it renders appealing visualization, it is fun, it is free, it is not hard to start. px stands for Plotly.express, it is easier to start from there. How to tackle the problem of overlapping. Try other Mapbox packages, for instance px.choropleth_mapbox Take a look at go (‘go’ stands for ‘plotly.graph_objs’) Try ‘go.Scattermapbox()’, which gives you more control Here is an example that combines Scattermapbox and dropdown list
[ { "code": null, "e": 439, "s": 172, "text": "I have come across several projects that include geographic data, and I have been searching for the best tool for geo-visualization. As a Python user, I have tried Pyplot’s basemap, GeoPandas, Folium, and Bohem, but none of them has given me a satisfying experience." }, { "code": null, "e": 693, "s": 439, "text": "Finally, my search ended after I found Plotly. To be more specific, Plotly’s Mapbox package. Today in this post, I will demonstrate a quick start for geographic data visualization using Plotly Mapbox and show it why you should consider using it as well." }, { "code": null, "e": 758, "s": 693, "text": "Visually appealing. You have to try hard to make it look ugly 😜." }, { "code": null, "e": 854, "s": 758, "text": "Choose the granularity of control. You have broad freedom to control the visualization effects." }, { "code": null, "e": 932, "s": 854, "text": "Interactive is fun. It can be handy for both EDA and dashboard presentations." }, { "code": null, "e": 1027, "s": 932, "text": "Varies product lines in different languages (R, Python, Javascript), Stable released versions." }, { "code": null, "e": 1090, "s": 1027, "text": "Not very steep learning rate. Arguably, but judge by yourself." }, { "code": null, "e": 1184, "s": 1090, "text": "Eyes on bigdata. With datashader, Plotly can handle data visualization with millions of rows." }, { "code": null, "e": 1211, "s": 1184, "text": "Open-source. It is FREE!!!" }, { "code": null, "e": 1239, "s": 1211, "text": "Come from my experience, if" }, { "code": null, "e": 1261, "s": 1239, "text": "you are a Python user" }, { "code": null, "e": 1323, "s": 1261, "text": "you are familiar with data visualization tools, like plt, sns" }, { "code": null, "e": 1386, "s": 1323, "text": "you need interactive data visualization, or you want to try it" }, { "code": null, "e": 1406, "s": 1386, "text": "you like free stuff" }, { "code": null, "e": 1467, "s": 1406, "text": "then, Plotly Maxbox is most likely the right choice for you." }, { "code": null, "e": 1794, "s": 1467, "text": "I would like to mention one more thing about interactive data visualization before we jump into the code. Some people think interactive data visualization is nothing more about the cool effect, and it is solely for presentation. For other applications, like exploratory data analysis (EDA), a static plot should be sufficient." }, { "code": null, "e": 2013, "s": 1794, "text": "However, for geo-visualization, either a data scientist or an audience often needs to change the scale of the map (for example, by zoom in and out) to understand the information fully; a static plot is just not enough." }, { "code": null, "e": 2064, "s": 2013, "text": "Without further ado, let’s make geo-visualization." }, { "code": null, "e": 2456, "s": 2064, "text": "# import packagesimport pandas as pdimport plotly.express as pximport numpy as np# get dataurl = 'https://raw.githubusercontent.com/kefeimo/DataScienceBlog/master/2.geo_plot/df_mapbox_demo.csv'df_plot_tmp = pd.read_csv(url)df_plot_tmp.head()# two-line codefig = px.scatter_mapbox(df_plot_tmp, lat=\"latitude\", lon=\"longitude\", color=\"gender\", zoom=3, mapbox_style='open-street-map')fig.show()" }, { "code": null, "e": 2536, "s": 2456, "text": "TIPS: Click on the ‘EDIT CHART’ button to have a better interactive experience." }, { "code": null, "e": 2921, "s": 2536, "text": "In the above example, we used ‘open-street-map’ as the back-end tilemap. (Recall that we defined mapbox_style=’open-street-map’.) But actually, I found the Plotly default Mapbox base map is more appealing. To do that, we need to use a Mapbox access token. (A Mapbox access token would be something like this: pk.eyJ1Ijoibxxxxxxxxxxxxx. Here to apply the Public Access Token for free.)" }, { "code": null, "e": 3190, "s": 2921, "text": "mapbox_access_token = 'Your token...'px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat=\"latitude\", lon=\"longitude\", color=\"gender\", zoom=3,# mapbox_style='open-street-map', )fig.show()" }, { "code": null, "e": 3464, "s": 3190, "text": "TIPS: if the token is wrong, you will get an empty plot. (it is there but you are not able to see it.) To solve this problem, double check your token validation or go back to use mapbox_style=’open-street-map’. (also, when using mapbox make sure the internet is connected.)" }, { "code": null, "e": 3706, "s": 3464, "text": "wrong_token = 'xxx'px.set_mapbox_access_token(wrong_token)fig = px.scatter_mapbox(df_plot_tmp, lat=\"latitude\", lon=\"longitude\", color=\"gender\", zoom=3,# mapbox_style='open-street-map', )fig.show()" }, { "code": null, "e": 3791, "s": 3706, "text": "We can further specify the parameters as desired (see how similar it is to seaborn)." }, { "code": null, "e": 3830, "s": 3791, "text": "Things I think worth to play with are:" }, { "code": null, "e": 3864, "s": 3830, "text": "color (similar to hue in seaborn)" }, { "code": null, "e": 3869, "s": 3864, "text": "size" }, { "code": null, "e": 3934, "s": 3869, "text": "zoom, center, (control the first view when the plot is rendered)" }, { "code": null, "e": 3948, "s": 3934, "text": "width, height" }, { "code": null, "e": 4001, "s": 3948, "text": "While things didn’t give me a satisfying outcome is:" }, { "code": null, "e": 4102, "s": 4001, "text": "text (the scatter just disappear somehow when using this. ‘hover_name’ can be an alternative though)" }, { "code": null, "e": 4109, "s": 4102, "text": "Notes:" }, { "code": null, "e": 4135, "s": 4109, "text": "There is no shape control" }, { "code": null, "e": 4336, "s": 4135, "text": "Also, when you play with color, depends on whether it is continuous or categorical, you might wanna furth color_continuous_scale(similar to palette) or specify category_orders, color_discrete_sequence" }, { "code": null, "e": 4396, "s": 4336, "text": "When you play with size, you can play with size_max as well" }, { "code": null, "e": 4521, "s": 4396, "text": "You can choose to open the plot in the notebook (by default) or another window (renderer=’browser’) by setting the renderer." }, { "code": null, "e": 5245, "s": 4521, "text": "# px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat=\"latitude\", lon=\"longitude\", color=\"gender\", size='hour', size_max=6, category_orders={'gender':list(df_plot_tmp.gender.unique())}, color_discrete_sequence=['#2b83ba', '#fdae61'],# hover_data=1,# hover_name='hour',# text='hour', zoom=3.3,# zoom=2.8, center=dict(lon=105, lat=38), width=900*1.5, height=500*1.5,)fig.show()fig.show(renderer=\"browser\")" }, { "code": null, "e": 5319, "s": 5245, "text": "To solidify our understanding, let’s use age_cate as the color specifier." }, { "code": null, "e": 5335, "s": 5319, "text": "In this example" }, { "code": null, "e": 5373, "s": 5335, "text": "See how to specify the category order" }, { "code": null, "e": 5518, "s": 5373, "text": "See how to specify the color palette(note in scatter_mapbox the color need to specify in hex, so we need to parse the color to hex by some sort)" }, { "code": null, "e": 5707, "s": 5518, "text": "TIPS: While Plotly has its own palette, but for python, I found the easy way to select a palette is using seaborn sns.color_palette(), all the available pallet can be found in colorbrewer." }, { "code": null, "e": 6334, "s": 5707, "text": "from matplotlib.colors import to_heximport seaborn as sns# px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat=\"latitude\", lon=\"longitude\", color=\"age_cate\", # size=\"hour\", size_max=15, category_orders={'age_cate':['A22-', 'A23-26', 'A27-28', 'A29-31', 'A32-40', 'A40+']}, color_discrete_sequence=[to_hex(c) for c in sns.color_palette('BrBG_r', 6)], zoom=2.5, center=dict(lon=105, lat=38, ), width=900, height=600,)fig.show()" }, { "code": null, "e": 6382, "s": 6334, "text": "Next, play with the continuous/numerical color." }, { "code": null, "e": 6863, "s": 6382, "text": "# play with the color: continous/numerical# px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat=\"latitude\", lon=\"longitude\", color=\"hour\", # size=\"hour\", color_continuous_scale=px.colors.cyclical.Twilight, zoom=2.5, center=dict(lon=105, lat=38, ), width=900, height=600,)fig.show()" }, { "code": null, "e": 7027, "s": 6863, "text": "So far, you should have mastered the basic stuff of interactive geo data scatter plot using Plotly. Now let’s discuss some common issues and potential roundabouts." }, { "code": null, "e": 7059, "s": 7027, "text": "One issue is about overlapping." }, { "code": null, "e": 7618, "s": 7059, "text": "Sometimes, overlapping results from the dataset itself. You might have noticed the coordinates data (i.e., latitude, longitude) is at 0.01. When plotting on the tilemap, this easily causes overlapping. Note that there is no jitter option. We might have to add jitter to the data manually. (Somehow, I think jitter is not trivial for interactive scatter visualization since the jitter parameter has to change accordingly as the scale change (e.g., zoom in and zoom out). We might need an adaptive jitter method if were to apply jitter to an interactive plot.)" }, { "code": null, "e": 8013, "s": 7618, "text": "In my opinion, to overcome overlapping, a ready-to-go solution is to adjust the scatter size (e.g., decrease the size of scatter to mitigate overlapping). But for px.scatter_mapbox, in 4.8.1 Plotly version, we cannot specify size using an int (no matter what says in the documentary). But there are ways to hack that, for instance, create a column in the data frame designated for scatter size." }, { "code": null, "e": 8037, "s": 8013, "text": "Try the following code:" }, { "code": null, "e": 8060, "s": 8037, "text": "‘Hack ’size parameter." }, { "code": null, "e": 8775, "s": 8060, "text": "# px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat=\"latitude\", lon=\"longitude\", color=\"gender\", size='size_for_plot', size_max=2, category_orders={'gender':list(df_plot_tmp.gender.unique())}, color_discrete_sequence=['#2b83ba', '#fdae61'],# hover_data=1,# hover_name='hour',# text='hour', zoom=2.8, center=dict(lon=105, lat=38), width=900, height=600, title='modified scatter size')fig.show()" }, { "code": null, "e": 8795, "s": 8775, "text": "Manually add jitter" }, { "code": null, "e": 9421, "s": 8795, "text": "# px.set_mapbox_access_token(mapbox_access_token)fig = px.scatter_mapbox(df_plot_tmp, lat=\"lat_jitter\", lon=\"lon_jitter\", color=\"age_cate\", # size=\"size_for_plot\", size_max=3, category_orders={'age_cate':['A22-', 'A23-26', 'A27-28', 'A29-31', 'A32-40', 'A40+']}, color_discrete_sequence=[to_hex(c) for c in sns.color_palette('BrBG_r', 6)], zoom=10, center=dict(lon=116.4, lat=39.9, ), width=900, height=600, title='add jitter')fig.show()" }, { "code": null, "e": 9530, "s": 9421, "text": "Try Plotly Mapbox, since it renders appealing visualization, it is fun, it is free, it is not hard to start." }, { "code": null, "e": 9594, "s": 9530, "text": "px stands for Plotly.express, it is easier to start from there." }, { "code": null, "e": 9636, "s": 9594, "text": "How to tackle the problem of overlapping." }, { "code": null, "e": 9697, "s": 9636, "text": "Try other Mapbox packages, for instance px.choropleth_mapbox" }, { "code": null, "e": 9753, "s": 9697, "text": "Take a look at go (‘go’ stands for ‘plotly.graph_objs’)" }, { "code": null, "e": 9808, "s": 9753, "text": "Try ‘go.Scattermapbox()’, which gives you more control" } ]
2 latent methods for dimension reduction and topic modeling | by Edward Ma | Towards Data Science
Before the state-of-the-art word embedding technique, Latent Semantic Analysis (LSA) and Latent Dirichlet Allocation (LDA) area good approaches to deal with NLP problems. Both LSA and LDA have same input which is Bag of words in matrix format. LSA focus on reducing matrix dimension while LDA solves topic modeling problems. I will not go through mathematical detail and as there is lot of great material for that. You may check it from reference. For the sake of keeping it easy to understand, I did not do pre-processing such as stopwords removal. It is critical part when you use LSA, LSI and LDA. After reading this article, you will know: Latent Semantic Analysis (LSA) Latent Dirichlet Allocation (LDA) Take Away LSA for natural language processing task was introduced by Jerome Bellegarda in 2005. The objective of LSA is reducing dimension for classification. The idea is that words will occurs in similar pieces of text if they have similar meaning. We usually use Latent Semantic Indexing (LSI) as an alternative name in NLP field. First of all, we have m documents and n words as input. An m * n matrix can be constructed while column and row are document and word respectively. You can use count occurrence or TF-IDF score. However, TF-IDF is better than count occurrence in most of the time as high frequency do not account for better classification. The idea of TF-IDF is that high frequency may not able to provide much information gain. In another word, rare words contribute more weights to the model. Word importance will be increased if the number of occurrence within same document (i.e. training record). On the other hand, it will be decreased if it occurs in corpus (i.e. other training records). For detail, you may check this blog . The challenge is that the matrix is very sparse (or high dimension) and noisy (or include lots of low frequency word). So truncated SVD is adopted to reduce dimension. The idea of SVD is finding the most valuable information and using lower dimension t to represent same thing. tfidf_vec = TfidfVectorizer(use_idf=True, norm='l2')svd = TruncatedSVD(n_components=dim)transformed_x_train = tfidf_vec.fit_transform(x_train)transformed_x_test = tfidf_vec.transform(x_test)print('TF-IDF output shape:', transformed_x_train.shape)x_train_svd = svd.fit_transform(transformed_x_train)x_test_svd = svd.transform(transformed_x_test)print('LSA output shape:', x_train_svd.shape)explained_variance = svd.explained_variance_ratio_.sum()print("Sum of explained variance ratio: %d%%" % (int(explained_variance * 100))) Output TF-IDF output shape: (11314, 130107)LSA output shape: (11314, 50)Sum of explained variance ratio: 8% We can see that the dimension reduces from 130k to 50 only. from sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import cross_val_score, KFoldlr_model = LogisticRegression(solver='newton-cg',n_jobs=-1)lr_model.fit(x_train_svd, y_train)cv = KFold(n_splits=5, shuffle=True) scores = cross_val_score(lr_model, x_test_svd, y_test, cv=cv, scoring='accuracy')print("Accuracy: %0.4f (+/- %0.4f)" % (scores.mean(), scores.std() * 2)) Output Accuracy: 0.6511 (+/- 0.0201) LDA is introduced by David Blei, Andrew Ng and Michael O. Jordan in 2003. It is unsupervised learning and topic model is the typical example. The assumption is that each document mix with various topics and every topic mix with various words. Intuitively, you can image that we have two layer of aggregations. First layer is the distribution of categories. For example, we have finance news, weather news and political news. Second layer is distribution of words within the category. For instance, we can find “sunny” and “cloud” in weather news while “money” and “stock” exists in finance news. However, “a”, “with” and “can” do not contribute on topic modeling problem. Those words exist among documents and will have roughly same probability between categories. Therefore, stopwords removal is a critical step to achieve a better result. For particular document d, we get the topic distribution which is θ. From this distribution(θ), topic t will be chosen and selecting corresponding word from φ. from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.decomposition import LatentDirichletAllocationdef build_lda(x_train, num_of_topic=10): vec = CountVectorizer() transformed_x_train = vec.fit_transform(x_train) feature_names = vec.get_feature_names()lda = LatentDirichletAllocation( n_components=num_of_topic, max_iter=5, learning_method='online', random_state=0) lda.fit(transformed_x_train)return lda, vec, feature_namesdef display_word_distribution(model, feature_names, n_word): for topic_idx, topic in enumerate(model.components_): print("Topic %d:" % (topic_idx)) words = [] for i in topic.argsort()[:-n_word - 1:-1]: words.append(feature_names[i]) print(words)lda_model, vec, feature_names = build_lda(x_train)display_word_distribution( model=lda_model, feature_names=feature_names, n_word=5) Output Topic 0:['the', 'for', 'and', 'to', 'edu']Topic 1:['c_', 'w7', 'hz', 'mv', 'ck']Topic 2:['space', 'nasa', 'cmu', 'science', 'edu']Topic 3:['the', 'to', 'of', 'for', 'and']Topic 4:['the', 'to', 'of', 'and', 'in']Topic 5:['the', 'of', 'and', 'in', 'were']Topic 6:['edu', 'team', 'he', 'game', '10']Topic 7:['ax', 'max', 'g9v', 'b8f', 'a86']Topic 8:['db', 'bike', 'ac', 'image', 'dod']Topic 9:['nec', 'mil', 'navy', 'sg', 'behanna'] To access all code, you can visit my github repo. Both of them use Bag-of-words as input matrix The challenge of SVD is that we are hard to determine the optimal number of dimension. In general, low dimension consume less resource but we may not able to distinguish opposite meaning words while high dimension overcome it but consuming more resource. I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science and Artificial Intelligence , especially in NLP and platform related. You can reach me from Medium, LinkedIn or Github. [1] SVD Tutorial: https://cs.fit.edu/~dmitra/SciComp/Resources/singular-value-decomposition-fast-track-tutorial.pdf [2] CUHK LSI Tutorial: http://www1.se.cuhk.edu.hk/~seem5680/lecture/LSI-Eg.pdf [3] Stanford LSI Tutorial: https://nlp.stanford.edu/IR-book/pdf/18lsi.pdf [4] LSA and LDA Explanation: https://cs.stanford.edu/~ppasupat/a9online/1140.html
[ { "code": null, "e": 497, "s": 172, "text": "Before the state-of-the-art word embedding technique, Latent Semantic Analysis (LSA) and Latent Dirichlet Allocation (LDA) area good approaches to deal with NLP problems. Both LSA and LDA have same input which is Bag of words in matrix format. LSA focus on reducing matrix dimension while LDA solves topic modeling problems." }, { "code": null, "e": 816, "s": 497, "text": "I will not go through mathematical detail and as there is lot of great material for that. You may check it from reference. For the sake of keeping it easy to understand, I did not do pre-processing such as stopwords removal. It is critical part when you use LSA, LSI and LDA. After reading this article, you will know:" }, { "code": null, "e": 847, "s": 816, "text": "Latent Semantic Analysis (LSA)" }, { "code": null, "e": 881, "s": 847, "text": "Latent Dirichlet Allocation (LDA)" }, { "code": null, "e": 891, "s": 881, "text": "Take Away" }, { "code": null, "e": 1214, "s": 891, "text": "LSA for natural language processing task was introduced by Jerome Bellegarda in 2005. The objective of LSA is reducing dimension for classification. The idea is that words will occurs in similar pieces of text if they have similar meaning. We usually use Latent Semantic Indexing (LSI) as an alternative name in NLP field." }, { "code": null, "e": 1536, "s": 1214, "text": "First of all, we have m documents and n words as input. An m * n matrix can be constructed while column and row are document and word respectively. You can use count occurrence or TF-IDF score. However, TF-IDF is better than count occurrence in most of the time as high frequency do not account for better classification." }, { "code": null, "e": 1930, "s": 1536, "text": "The idea of TF-IDF is that high frequency may not able to provide much information gain. In another word, rare words contribute more weights to the model. Word importance will be increased if the number of occurrence within same document (i.e. training record). On the other hand, it will be decreased if it occurs in corpus (i.e. other training records). For detail, you may check this blog ." }, { "code": null, "e": 2098, "s": 1930, "text": "The challenge is that the matrix is very sparse (or high dimension) and noisy (or include lots of low frequency word). So truncated SVD is adopted to reduce dimension." }, { "code": null, "e": 2208, "s": 2098, "text": "The idea of SVD is finding the most valuable information and using lower dimension t to represent same thing." }, { "code": null, "e": 2734, "s": 2208, "text": "tfidf_vec = TfidfVectorizer(use_idf=True, norm='l2')svd = TruncatedSVD(n_components=dim)transformed_x_train = tfidf_vec.fit_transform(x_train)transformed_x_test = tfidf_vec.transform(x_test)print('TF-IDF output shape:', transformed_x_train.shape)x_train_svd = svd.fit_transform(transformed_x_train)x_test_svd = svd.transform(transformed_x_test)print('LSA output shape:', x_train_svd.shape)explained_variance = svd.explained_variance_ratio_.sum()print(\"Sum of explained variance ratio: %d%%\" % (int(explained_variance * 100)))" }, { "code": null, "e": 2741, "s": 2734, "text": "Output" }, { "code": null, "e": 2842, "s": 2741, "text": "TF-IDF output shape: (11314, 130107)LSA output shape: (11314, 50)Sum of explained variance ratio: 8%" }, { "code": null, "e": 2902, "s": 2842, "text": "We can see that the dimension reduces from 130k to 50 only." }, { "code": null, "e": 3298, "s": 2902, "text": "from sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import cross_val_score, KFoldlr_model = LogisticRegression(solver='newton-cg',n_jobs=-1)lr_model.fit(x_train_svd, y_train)cv = KFold(n_splits=5, shuffle=True) scores = cross_val_score(lr_model, x_test_svd, y_test, cv=cv, scoring='accuracy')print(\"Accuracy: %0.4f (+/- %0.4f)\" % (scores.mean(), scores.std() * 2))" }, { "code": null, "e": 3305, "s": 3298, "text": "Output" }, { "code": null, "e": 3335, "s": 3305, "text": "Accuracy: 0.6511 (+/- 0.0201)" }, { "code": null, "e": 3578, "s": 3335, "text": "LDA is introduced by David Blei, Andrew Ng and Michael O. Jordan in 2003. It is unsupervised learning and topic model is the typical example. The assumption is that each document mix with various topics and every topic mix with various words." }, { "code": null, "e": 3931, "s": 3578, "text": "Intuitively, you can image that we have two layer of aggregations. First layer is the distribution of categories. For example, we have finance news, weather news and political news. Second layer is distribution of words within the category. For instance, we can find “sunny” and “cloud” in weather news while “money” and “stock” exists in finance news." }, { "code": null, "e": 4176, "s": 3931, "text": "However, “a”, “with” and “can” do not contribute on topic modeling problem. Those words exist among documents and will have roughly same probability between categories. Therefore, stopwords removal is a critical step to achieve a better result." }, { "code": null, "e": 4336, "s": 4176, "text": "For particular document d, we get the topic distribution which is θ. From this distribution(θ), topic t will be chosen and selecting corresponding word from φ." }, { "code": null, "e": 5233, "s": 4336, "text": "from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.decomposition import LatentDirichletAllocationdef build_lda(x_train, num_of_topic=10): vec = CountVectorizer() transformed_x_train = vec.fit_transform(x_train) feature_names = vec.get_feature_names()lda = LatentDirichletAllocation( n_components=num_of_topic, max_iter=5, learning_method='online', random_state=0) lda.fit(transformed_x_train)return lda, vec, feature_namesdef display_word_distribution(model, feature_names, n_word): for topic_idx, topic in enumerate(model.components_): print(\"Topic %d:\" % (topic_idx)) words = [] for i in topic.argsort()[:-n_word - 1:-1]: words.append(feature_names[i]) print(words)lda_model, vec, feature_names = build_lda(x_train)display_word_distribution( model=lda_model, feature_names=feature_names, n_word=5)" }, { "code": null, "e": 5240, "s": 5233, "text": "Output" }, { "code": null, "e": 5670, "s": 5240, "text": "Topic 0:['the', 'for', 'and', 'to', 'edu']Topic 1:['c_', 'w7', 'hz', 'mv', 'ck']Topic 2:['space', 'nasa', 'cmu', 'science', 'edu']Topic 3:['the', 'to', 'of', 'for', 'and']Topic 4:['the', 'to', 'of', 'and', 'in']Topic 5:['the', 'of', 'and', 'in', 'were']Topic 6:['edu', 'team', 'he', 'game', '10']Topic 7:['ax', 'max', 'g9v', 'b8f', 'a86']Topic 8:['db', 'bike', 'ac', 'image', 'dod']Topic 9:['nec', 'mil', 'navy', 'sg', 'behanna']" }, { "code": null, "e": 5720, "s": 5670, "text": "To access all code, you can visit my github repo." }, { "code": null, "e": 5766, "s": 5720, "text": "Both of them use Bag-of-words as input matrix" }, { "code": null, "e": 6021, "s": 5766, "text": "The challenge of SVD is that we are hard to determine the optimal number of dimension. In general, low dimension consume less resource but we may not able to distinguish opposite meaning words while high dimension overcome it but consuming more resource." }, { "code": null, "e": 6219, "s": 6021, "text": "I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science and Artificial Intelligence , especially in NLP and platform related. You can reach me from Medium, LinkedIn or Github." }, { "code": null, "e": 6335, "s": 6219, "text": "[1] SVD Tutorial: https://cs.fit.edu/~dmitra/SciComp/Resources/singular-value-decomposition-fast-track-tutorial.pdf" }, { "code": null, "e": 6414, "s": 6335, "text": "[2] CUHK LSI Tutorial: http://www1.se.cuhk.edu.hk/~seem5680/lecture/LSI-Eg.pdf" }, { "code": null, "e": 6488, "s": 6414, "text": "[3] Stanford LSI Tutorial: https://nlp.stanford.edu/IR-book/pdf/18lsi.pdf" } ]
C/C++ Program for Odd-Even Sort / Brick Sort - GeeksforGeeks
18 Apr, 2022 This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even indexed elements. CPP // A C++ Program to implement Odd-Even / Brick Sort#include <bits/stdc++.h>using namespace std; // A function to sort the algorithm using Odd Even sortvoid oddEvenSort(int arr[], int n){ bool isSorted = false; // Initially array is unsorted while (!isSorted) { isSorted = true; // Perform Bubble sort on odd indexed element for (int i = 1; i <= n - 2; i = i + 2) { if (arr[i] > arr[i + 1]) { swap(arr[i], arr[i + 1]); isSorted = false; } } // Perform Bubble sort on even indexed element for (int i = 0; i <= n - 2; i = i + 2) { if (arr[i] > arr[i + 1]) { swap(arr[i], arr[i + 1]); isSorted = false; } } } return;} // A utility function to print an array of size nvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << "\n";} // Driver program to test above functions.int main(){ int arr[] = { 34, 2, 10, -9 }; int n = sizeof(arr) / sizeof(arr[0]); oddEvenSort(arr, n); printArray(arr, n); return (0);} -9 2 10 34 Please refer complete article on Odd-Even Sort / Brick Sort for more details! C Programs C++ Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Difference between break and continue statement in C C++ Program for QuickSort C++ program for hashing with chaining Sorting a Map by value in C++ STL cin in C++ delete keyword in C++
[ { "code": null, "e": 24617, "s": 24589, "text": "\n18 Apr, 2022" }, { "code": null, "e": 24985, "s": 24617, "text": "This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even indexed elements. " }, { "code": null, "e": 24989, "s": 24985, "text": "CPP" }, { "code": "// A C++ Program to implement Odd-Even / Brick Sort#include <bits/stdc++.h>using namespace std; // A function to sort the algorithm using Odd Even sortvoid oddEvenSort(int arr[], int n){ bool isSorted = false; // Initially array is unsorted while (!isSorted) { isSorted = true; // Perform Bubble sort on odd indexed element for (int i = 1; i <= n - 2; i = i + 2) { if (arr[i] > arr[i + 1]) { swap(arr[i], arr[i + 1]); isSorted = false; } } // Perform Bubble sort on even indexed element for (int i = 0; i <= n - 2; i = i + 2) { if (arr[i] > arr[i + 1]) { swap(arr[i], arr[i + 1]); isSorted = false; } } } return;} // A utility function to print an array of size nvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << \"\\n\";} // Driver program to test above functions.int main(){ int arr[] = { 34, 2, 10, -9 }; int n = sizeof(arr) / sizeof(arr[0]); oddEvenSort(arr, n); printArray(arr, n); return (0);}", "e": 26129, "s": 24989, "text": null }, { "code": null, "e": 26140, "s": 26129, "text": "-9 2 10 34" }, { "code": null, "e": 26218, "s": 26140, "text": "Please refer complete article on Odd-Even Sort / Brick Sort for more details!" }, { "code": null, "e": 26229, "s": 26218, "text": "C Programs" }, { "code": null, "e": 26242, "s": 26229, "text": "C++ Programs" }, { "code": null, "e": 26250, "s": 26242, "text": "Sorting" }, { "code": null, "e": 26258, "s": 26250, "text": "Sorting" }, { "code": null, "e": 26356, "s": 26258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26365, "s": 26356, "text": "Comments" }, { "code": null, "e": 26378, "s": 26365, "text": "Old Comments" }, { "code": null, "e": 26419, "s": 26378, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 26450, "s": 26419, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 26491, "s": 26450, "text": "C program to find the length of a string" }, { "code": null, "e": 26525, "s": 26491, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 26578, "s": 26525, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 26604, "s": 26578, "text": "C++ Program for QuickSort" }, { "code": null, "e": 26642, "s": 26604, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 26676, "s": 26642, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 26687, "s": 26676, "text": "cin in C++" } ]
CUDA - Performance Considerations
In this chapter, we will understand the performance considerations of CUDA. A poorly written CUDA program can perform much worse than intended. Consider the following piece of code − for(int k=0; k<width; k++) { product_val += d_M[row*width+k] * d_N[k*width+col]; } For every iteration of the loop, the global memory is accessed twice. That is, for two floating-point calculations, we access the global memory twice. One for fetching an element of d_M and one for fetching an element of d_N. Is it efficient? We know that accessing the global memory is terribly expensive – the processor is simply wasting that time. If we can reduce the number of memory fetches per iteration, then the performance will certainly go up. The CGMA ratio of the above program is 1:1. CGMA stands for ‘Compute to Global Memory Access’ ratio, and the higher it is, the better the kernel performs. Programmers should aim to increase this ratio as much as it possible. In the above kernel, there are two floating-point operations. One is MUL and the other is ADD. Let the DRAM bandwidth be equal to 200G/s. Each single-precision floating-point value is 4B. Thus, in one second, no more than 50G single-precision floating-point values can be delivered. Since the CGMA ratio is 1:1, we can say that the maximum floating-point operations that the kernel will execute in 1 second is 50 GFLOPS (Giga Floating-point Operations per second). The peak performance of the Nvidia Titan X is 10157 GFLOPS for single-precision after boost. Compared to that 50GFLOPS is a minuscule number, and it is obvious that the above code will not harness the full potential of the card. Consider the kernel below − __global__ void addNumToEachElement(float* M) { int index = blockIdx.x * blockDim.x + threadIdx.x; M[index] = M[index] + M[0]; } The above kernel simply adds M[0] to each element of the array M. The number of global memory accesses for each thread is 3, while the total number of computations is 1 (ADD in the second instruction). The CGMA ratio is bad: 1⁄3. If we can eliminate the global memory access for M[0] for each thread, then the CGMA ratio will improve to 0.5. We will attain this by caching. If the kernel does not have to fetch the value of M[0] from the global memory for every thread, then the CGMA ratio will increase. What actually happens is that the value of M[0] is cached aggressively by CUDA in the constant memory. The bandwidth is very high, and hence, fetching it from the constant memory is not a high-latency operation. Caching is used generously wherever possible by CUDA to improve performance. Memory is often a bottleneck to achieving high performance in CUDA programs. No matter how fast the DRAM is, it cannot supply data at the rate at which the cores can consume it. It can be understood using the following analogy. Suppose that you are thirsty on a hot summer day, and someone offers you cold water, on the condition that you have to drink it using a straw. No matter how fast you try to suck the water in, only a specific quantity can enter your mouth per unit of time. In the case of GPUs, the cores are ‘thirsty’, and the straw is the actual memory bandwidth. It limits the performance here. Print Add Notes Bookmark this page
[ { "code": null, "e": 1968, "s": 1892, "text": "In this chapter, we will understand the performance considerations of CUDA." }, { "code": null, "e": 2075, "s": 1968, "text": "A poorly written CUDA program can perform much worse than intended. Consider the following piece of code −" }, { "code": null, "e": 2161, "s": 2075, "text": "for(int k=0; k<width; k++) {\n product_val += d_M[row*width+k] * d_N[k*width+col];\n}" }, { "code": null, "e": 2616, "s": 2161, "text": "For every iteration of the loop, the global memory is accessed twice. That is, for two floating-point calculations, we access the global memory twice. One for fetching an element of d_M and one for fetching an element of d_N. Is it efficient? We know that accessing the global memory is terribly expensive – the processor is simply wasting that time. If we can reduce the number of memory fetches per iteration, then the performance will certainly go up." }, { "code": null, "e": 2936, "s": 2616, "text": "The CGMA ratio of the above program is 1:1. CGMA stands for ‘Compute to Global Memory Access’ ratio, and the higher it is, the better the kernel performs. Programmers should aim to increase this ratio as much as it possible. In the above kernel, there are two floating-point operations. One is MUL and the other is ADD." }, { "code": null, "e": 3563, "s": 2936, "text": "Let the DRAM bandwidth be equal to 200G/s. Each single-precision floating-point value is 4B. Thus, in one second, no more than 50G single-precision floating-point values can be delivered. Since the CGMA ratio is 1:1, we can say that the maximum floating-point operations that the kernel will execute in 1 second is 50 GFLOPS (Giga Floating-point Operations per second). The peak performance of the Nvidia Titan X is 10157 GFLOPS for single-precision after boost. Compared to that 50GFLOPS is a minuscule number, and it is obvious that the above code will not harness the full potential of the card. Consider the kernel below −" }, { "code": null, "e": 3698, "s": 3563, "text": "__global__ void addNumToEachElement(float* M) {\n int index = blockIdx.x * blockDim.x + threadIdx.x;\n M[index] = M[index] + M[0];\n}" }, { "code": null, "e": 4072, "s": 3698, "text": "The above kernel simply adds M[0] to each element of the array M. The number of global memory accesses for each thread is 3, while the total number of computations is 1 (ADD in the second instruction). The CGMA ratio is bad: 1⁄3. If we can eliminate the global memory access for M[0] for each thread, then the CGMA ratio will improve to 0.5. We will attain this by caching." }, { "code": null, "e": 4492, "s": 4072, "text": "If the kernel does not have to fetch the value of M[0] from the global memory for every thread, then the CGMA ratio will increase. What actually happens is that the value of M[0] is cached aggressively by CUDA in the constant memory. The bandwidth is very high, and hence, fetching it from the constant memory is not a high-latency operation. Caching is used generously wherever possible by CUDA to improve performance." }, { "code": null, "e": 5100, "s": 4492, "text": "Memory is often a bottleneck to achieving high performance in CUDA programs. No matter how fast the DRAM is, it cannot supply data at the rate at which the cores can consume it. It can be understood using the following analogy. Suppose that you are thirsty on a hot summer day, and someone offers you cold water, on the condition that you have to drink it using a straw. No matter how fast you try to suck the water in, only a specific quantity can enter your mouth per unit of time. In the case of GPUs, the cores are ‘thirsty’, and the straw is the actual memory bandwidth. It limits the performance here." }, { "code": null, "e": 5107, "s": 5100, "text": " Print" }, { "code": null, "e": 5118, "s": 5107, "text": " Add Notes" } ]
New feature of C++17
The C++ Standards committee is always focusing on shipping new features every three years. The two main parts of the specification are the core functionality of the programming language and the Standard Template Library (STL). The new features are introduced to make the code cleaner, easier and compact. Following is the list of features that are introduced-: Fold expressions are used to write shorter codes for a variable number of arguments that can be passed to a function or can be returned from the function. It enables the use of any number of variables as arguments and in return statements of a function. Unary right fold - ( pack op1 ... ) Unary right fold - ( pack op1 ... ) Unary left fold - ( ... op1 pack ) Unary left fold - ( ... op1 pack ) Binary left fold - ( init op1 ... op1 pack ) Binary left fold - ( init op1 ... op1 pack ) Binary right fold - ( pack op1 ... op1 init ) Binary right fold - ( pack op1 ... op1 init ) Here pack is a parameter pack that can be expanded for any number of variables. op1 is an operator. ( -, + , <=, >=, <, > , ==, *, / .... ). In binary folds, both op1 are the same operators. init is an expression that cannot be expanded. #include <iostream> #include <string> using namespace std; template<typename ...Args> auto addition(Args ...args){ return (args + ... + 0); } template<typename ...Args> auto sum2(Args ...args){ return (args + ...); } int main(){ cout << "Sum is : "<<addition(1,1,1,1,1) << endl; cout << "Sum 2 is : "<<addition ( 1,2,3); } Sum is : 5 Sum 2 is : 6 These are used to declare multiple variables to be initialized with values in a pair, tuple etc. All these binding of variables with initializers done in a single statement. Case 1:- binding an arrayEach identifier in the identifier list becomes the name of lvalue for element of array. Number of elements must be equal to the number of identifiers.int arry[3] = { 3,4,5 };auto [a,b,c] = arry;//here array is created and a refers to 3, b refers to 4 and c refers to 5. Case 1:- binding an array Each identifier in the identifier list becomes the name of lvalue for element of array. Number of elements must be equal to the number of identifiers. int arry[3] = { 3,4,5 }; auto [a,b,c] = arry; //here array is created and a refers to 3, b refers to 4 and c refers to 5. Case 2:- binding a tuple like typefloat fnum{};char ch1{};int number{};std::tuple < float&, char&&, int > tplex( fnum, std::move(ch1) , number);const auto& [ p, q, r] = tplex;// p is name of structured binding referring to fnum// q is name of structured binding referring to ch1// r is name of structured binding referring to number Case 2:- binding a tuple like type float fnum{}; char ch1{}; int number{}; std::tuple < float&, char&&, int > tplex( fnum, std::move(ch1) , number); const auto& [ p, q, r] = tplex; // p is name of structured binding referring to fnum // q is name of structured binding referring to ch1 // r is name of structured binding referring to number Case 3:- binding to data membersstruct structVar {mutable int num1 : 2;volatile double num2;};structVar func();const auto [ a, b] = func();// a is an int lvalue for the 2-bit bit field// b is a const volatile double lvalue Case 3:- binding to data members struct structVar { mutable int num1 : 2; volatile double num2; }; structVar func(); const auto [ a, b] = func(); // a is an int lvalue for the 2-bit bit field // b is a const volatile double lvalue With C++17 the enums can now be initialized using braces. enum byte : unsigned char {}; byte b0 {0}; // OK byte b1 = byte{1}; // OK byte b2 = byte{256}; // ERROR - 0 to 255 only C++17 allows declaration of variables inside if and switch conditions. This makes it easy to use variables with same names that have different scopes. if (data type variable condition) { //statements } switch ( condition; variable ) { //statements } Useful feature for template codes. The if constexpr statement is evaluated at compile time. How it is Helpful can be shown using comparisons below:- int var = 10; if (var >= 10) { var=var+10; } else { var=var-10; } template <typename T> auto length ( T const& value ) { //checking if T is integer or not if (is_integral<T>::value) { return value; } else { return value.length(); } } Namespaces are used to group together similar codes like classes and functions that are correlated. C++17 allows more easy syntax of using nested namespaces. Earlier the syntax was quite messy when the number of nested namespaces was more. Handling braces is now no longer required. namespace Earth{ namespace Continent { namespace Country { class City { .......... }; } } } namespace Earth :: Continent :: Country { class City { .......... }; }
[ { "code": null, "e": 1423, "s": 1062, "text": "The C++ Standards committee is always focusing on shipping new features every three years. The two main parts of the specification are the core functionality of the programming language and the Standard Template Library (STL). The new features are introduced to make the code cleaner, easier and compact. Following is the list of features that are introduced-:" }, { "code": null, "e": 1677, "s": 1423, "text": "Fold expressions are used to write shorter codes for a variable number of arguments that can be passed to a function or can be returned from the function. It enables the use of any number of variables as arguments and in return statements of a function." }, { "code": null, "e": 1713, "s": 1677, "text": "Unary right fold - ( pack op1 ... )" }, { "code": null, "e": 1749, "s": 1713, "text": "Unary right fold - ( pack op1 ... )" }, { "code": null, "e": 1784, "s": 1749, "text": "Unary left fold - ( ... op1 pack )" }, { "code": null, "e": 1819, "s": 1784, "text": "Unary left fold - ( ... op1 pack )" }, { "code": null, "e": 1864, "s": 1819, "text": "Binary left fold - ( init op1 ... op1 pack )" }, { "code": null, "e": 1909, "s": 1864, "text": "Binary left fold - ( init op1 ... op1 pack )" }, { "code": null, "e": 1955, "s": 1909, "text": "Binary right fold - ( pack op1 ... op1 init )" }, { "code": null, "e": 2001, "s": 1955, "text": "Binary right fold - ( pack op1 ... op1 init )" }, { "code": null, "e": 2192, "s": 2001, "text": "Here pack is a parameter pack that can be expanded for any number of variables. op1 is an operator. ( -, + , <=, >=, <, > , ==, *, / .... ). In binary folds, both op1 are the same operators." }, { "code": null, "e": 2239, "s": 2192, "text": "init is an expression that cannot be expanded." }, { "code": null, "e": 2574, "s": 2239, "text": "#include <iostream>\n#include <string>\nusing namespace std;\ntemplate<typename ...Args> auto addition(Args ...args){\n return (args + ... + 0);\n}\ntemplate<typename ...Args> auto sum2(Args ...args){\n return (args + ...);\n}\nint main(){\n cout << \"Sum is : \"<<addition(1,1,1,1,1) << endl;\n cout << \"Sum 2 is : \"<<addition ( 1,2,3);\n}" }, { "code": null, "e": 2598, "s": 2574, "text": "Sum is : 5\nSum 2 is : 6" }, { "code": null, "e": 2772, "s": 2598, "text": "These are used to declare multiple variables to be initialized with values in a pair, tuple etc. All these binding of variables with initializers done in a single statement." }, { "code": null, "e": 3067, "s": 2772, "text": "Case 1:- binding an arrayEach identifier in the identifier list becomes the name of lvalue for element of array. Number of elements must be equal to the number of identifiers.int arry[3] = { 3,4,5 };auto [a,b,c] = arry;//here array is created and a refers to 3, b refers to 4 and c refers to 5." }, { "code": null, "e": 3093, "s": 3067, "text": "Case 1:- binding an array" }, { "code": null, "e": 3244, "s": 3093, "text": "Each identifier in the identifier list becomes the name of lvalue for element of array. Number of elements must be equal to the number of identifiers." }, { "code": null, "e": 3269, "s": 3244, "text": "int arry[3] = { 3,4,5 };" }, { "code": null, "e": 3290, "s": 3269, "text": "auto [a,b,c] = arry;" }, { "code": null, "e": 3366, "s": 3290, "text": "//here array is created and a refers to 3, b refers to 4 and c refers to 5." }, { "code": null, "e": 3699, "s": 3366, "text": "Case 2:- binding a tuple like typefloat fnum{};char ch1{};int number{};std::tuple < float&, char&&, int > tplex( fnum, std::move(ch1) , number);const auto& [ p, q, r] = tplex;// p is name of structured binding referring to fnum// q is name of structured binding referring to ch1// r is name of structured binding referring to number" }, { "code": null, "e": 3734, "s": 3699, "text": "Case 2:- binding a tuple like type" }, { "code": null, "e": 3748, "s": 3734, "text": "float fnum{};" }, { "code": null, "e": 3760, "s": 3748, "text": "char ch1{};" }, { "code": null, "e": 3774, "s": 3760, "text": "int number{};" }, { "code": null, "e": 3848, "s": 3774, "text": "std::tuple < float&, char&&, int > tplex( fnum, std::move(ch1) , number);" }, { "code": null, "e": 3880, "s": 3848, "text": "const auto& [ p, q, r] = tplex;" }, { "code": null, "e": 3933, "s": 3880, "text": "// p is name of structured binding referring to fnum" }, { "code": null, "e": 3985, "s": 3933, "text": "// q is name of structured binding referring to ch1" }, { "code": null, "e": 4040, "s": 3985, "text": "// r is name of structured binding referring to number" }, { "code": null, "e": 4263, "s": 4040, "text": "Case 3:- binding to data membersstruct structVar {mutable int num1 : 2;volatile double num2;};structVar func();const auto [ a, b] = func();// a is an int lvalue for the 2-bit bit field// b is a const volatile double lvalue" }, { "code": null, "e": 4296, "s": 4263, "text": "Case 3:- binding to data members" }, { "code": null, "e": 4315, "s": 4296, "text": "struct structVar {" }, { "code": null, "e": 4337, "s": 4315, "text": "mutable int num1 : 2;" }, { "code": null, "e": 4359, "s": 4337, "text": "volatile double num2;" }, { "code": null, "e": 4362, "s": 4359, "text": "};" }, { "code": null, "e": 4380, "s": 4362, "text": "structVar func();" }, { "code": null, "e": 4409, "s": 4380, "text": "const auto [ a, b] = func();" }, { "code": null, "e": 4455, "s": 4409, "text": "// a is an int lvalue for the 2-bit bit field" }, { "code": null, "e": 4494, "s": 4455, "text": "// b is a const volatile double lvalue" }, { "code": null, "e": 4552, "s": 4494, "text": "With C++17 the enums can now be initialized using braces." }, { "code": null, "e": 4672, "s": 4552, "text": "enum byte : unsigned char {};\nbyte b0 {0}; // OK\nbyte b1 = byte{1}; // OK\nbyte b2 = byte{256}; // ERROR - 0 to 255 only" }, { "code": null, "e": 4823, "s": 4672, "text": "C++17 allows declaration of variables inside if and switch conditions. This makes it easy to use variables with same names that have different scopes." }, { "code": null, "e": 4928, "s": 4823, "text": "if (data type variable condition)\n{\n //statements\n}\nswitch ( condition; variable )\n{\n //statements\n}" }, { "code": null, "e": 5020, "s": 4928, "text": "Useful feature for template codes. The if constexpr statement is evaluated at compile time." }, { "code": null, "e": 5030, "s": 5020, "text": "How it is" }, { "code": null, "e": 5077, "s": 5030, "text": "Helpful can be shown using comparisons below:-" }, { "code": null, "e": 5149, "s": 5077, "text": "int var = 10;\nif (var >= 10) {\n var=var+10;\n} else {\n var=var-10;\n}" }, { "code": null, "e": 5342, "s": 5149, "text": "template <typename T>\nauto length ( T const& value ) { \n //checking if T is integer or not\n if (is_integral<T>::value) {\n return value;\n } else {\n return value.length();\n }\n}" }, { "code": null, "e": 5625, "s": 5342, "text": "Namespaces are used to group together similar codes like classes and functions that are correlated. C++17 allows more easy syntax of using nested namespaces. Earlier the syntax was quite messy when the number of nested namespaces was more. Handling braces is now no longer required." }, { "code": null, "e": 5745, "s": 5625, "text": "namespace Earth{\n\n namespace Continent {\n namespace Country {\n class City {\n ..........\n}; } } }" }, { "code": null, "e": 5825, "s": 5745, "text": "namespace Earth :: Continent :: Country {\n class City {\n ..........\n}; }" } ]
What is constructor chaining in Java?
Constructors are similar to methods but, They do not have any return type. The name of the constructor is same as the name of the class. Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class. Each time a new object is created, at least one constructor will be invoked. A class can have more than one constructor. this() and super() are used to call constructors explicitly. Where, using this() you can call the current class’s constructor and using super() you can call the constructor of the super class. You can also call one constructor from another. Calling a constructor of one class from other is known as constructor chaining. From normal (default) constructor you can call the parameterized constructors of the same class using this() and, from the sub class you can call the constructor of the super class using super() Live Demo class Super{ Super(int data){ System.out.println("value is : "+ data); } } public class Sub extends Super{ Sub(int data) { super(data); } public static void main(String args[]){ Sub sub = new Sub(400); } } value is : 400
[ { "code": null, "e": 1103, "s": 1062, "text": "Constructors are similar to methods but," }, { "code": null, "e": 1137, "s": 1103, "text": "They do not have any return type." }, { "code": null, "e": 1199, "s": 1137, "text": "The name of the constructor is same as the name of the class." }, { "code": null, "e": 1350, "s": 1199, "text": "Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class." }, { "code": null, "e": 1427, "s": 1350, "text": "Each time a new object is created, at least one constructor will be invoked." }, { "code": null, "e": 1471, "s": 1427, "text": "A class can have more than one constructor." }, { "code": null, "e": 1664, "s": 1471, "text": "this() and super() are used to call constructors explicitly. Where, using this() you can call the current class’s constructor and using super() you can call the constructor of the super class." }, { "code": null, "e": 1712, "s": 1664, "text": "You can also call one constructor from another." }, { "code": null, "e": 1987, "s": 1712, "text": "Calling a constructor of one class from other is known as constructor chaining. From normal (default) constructor you can call the parameterized constructors of the same class using this() and, from the sub class you can call the constructor of the super class using super()" }, { "code": null, "e": 1998, "s": 1987, "text": " Live Demo" }, { "code": null, "e": 2241, "s": 1998, "text": "class Super{\n Super(int data){\n System.out.println(\"value is : \"+ data);\n }\n}\npublic class Sub extends Super{\n Sub(int data) {\n super(data);\n }\n public static void main(String args[]){\n Sub sub = new Sub(400);\n }\n}\n" }, { "code": null, "e": 2257, "s": 2241, "text": "value is : 400\n" } ]
Classical problems of Synchronization with Semaphore Solution - GeeksforGeeks
18 Nov, 2021 In this article, we will see number of classical problems of synchronization as examples of a large class of concurrency-control problems. In our solutions to the problems, we use semaphores for synchronization, since that is the traditional way to present such solutions. However, actual implementations of these solutions could use mutex locks in place of binary semaphores. These problems are used for testing nearly every newly proposed synchronization scheme. The following problems of synchronization are considered as classical problems: 1. Bounded-buffer (or Producer-Consumer) Problem, 2. Dining-Philosophers Problem, 3. Readers and Writers Problem, 4. Sleeping Barber Problem These are summarized, for detailed explanation, you can view the linked articles for each. Bounded-buffer (or Producer-Consumer) Problem: Bounded Buffer problem is also called producer consumer problem. This problem is generalized in terms of the Producer-Consumer problem. Solution to this problem is, creating two counting semaphores “full” and “empty” to keep track of the current number of full and empty buffers respectively. Producers produce a product and consumers consume the product, but both use of one of the containers each time. Dining-Philosophers Problem: The Dining Philosopher Problem states that K philosophers seated around a circular table with one chopstick between each pair of philosophers. There is one chopstick between each philosopher. A philosopher may eat if he can pickup the two chopsticks adjacent to him. One chopstick may be picked up by any one of its adjacent followers but not both. This problem involves the allocation of limited resources to a group of processes in a deadlock-free and starvation-free manner. Readers and Writers Problem: Suppose that a database is to be shared among several concurrent processes. Some of these processes may want only to read the database, whereas others may want to update (that is, to read and write) the database. We distinguish between these two types of processes by referring to the former as readers and to the latter as writers. Precisely in OS we call this situation as the readers-writers problem. Problem parameters: One set of data is shared among a number of processes. Once a writer is ready, it performs its write. Only one writer may write at a time. If a process is writing, no other process can read it. If at least one reader is reading, no other process can write. Readers may not write and only read. One set of data is shared among a number of processes. Once a writer is ready, it performs its write. Only one writer may write at a time. If a process is writing, no other process can read it. If at least one reader is reading, no other process can write. Readers may not write and only read. Sleeping Barber Problem: Barber shop with one barber, one barber chair and N chairs to wait in. When no customers the barber goes to sleep in barber chair and must be woken when a customer comes in. When barber is cutting hair new customers take empty seats to wait, or leave if no vacancy. surindertarika1234 simmytarika5 Operating Systems-Process Management Process Synchronization GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Regular Expressions, Regular Grammar and Regular Languages Difference between Clustered and Non-clustered index Introduction of Process Synchronization Differences between IPv4 and IPv6 Preemptive and Non-Preemptive Scheduling Banker's Algorithm in Operating System Program for FCFS CPU Scheduling | Set 1 Program for Round Robin scheduling | Set 1 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Introduction of Deadlock in Operating System
[ { "code": null, "e": 24298, "s": 24270, "text": "\n18 Nov, 2021" }, { "code": null, "e": 24676, "s": 24298, "text": "In this article, we will see number of classical problems of synchronization as examples of a large class of concurrency-control problems. In our solutions to the problems, we use semaphores for synchronization, since that is the traditional way to present such solutions. However, actual implementations of these solutions could use mutex locks in place of binary semaphores. " }, { "code": null, "e": 24845, "s": 24676, "text": "These problems are used for testing nearly every newly proposed synchronization scheme. The following problems of synchronization are considered as classical problems: " }, { "code": null, "e": 24986, "s": 24845, "text": "1. Bounded-buffer (or Producer-Consumer) Problem,\n2. Dining-Philosophers Problem,\n3. Readers and Writers Problem,\n4. Sleeping Barber Problem" }, { "code": null, "e": 25078, "s": 24986, "text": "These are summarized, for detailed explanation, you can view the linked articles for each. " }, { "code": null, "e": 25532, "s": 25078, "text": "Bounded-buffer (or Producer-Consumer) Problem: Bounded Buffer problem is also called producer consumer problem. This problem is generalized in terms of the Producer-Consumer problem. Solution to this problem is, creating two counting semaphores “full” and “empty” to keep track of the current number of full and empty buffers respectively. Producers produce a product and consumers consume the product, but both use of one of the containers each time. " }, { "code": null, "e": 26041, "s": 25532, "text": "Dining-Philosophers Problem: The Dining Philosopher Problem states that K philosophers seated around a circular table with one chopstick between each pair of philosophers. There is one chopstick between each philosopher. A philosopher may eat if he can pickup the two chopsticks adjacent to him. One chopstick may be picked up by any one of its adjacent followers but not both. This problem involves the allocation of limited resources to a group of processes in a deadlock-free and starvation-free manner. " }, { "code": null, "e": 26796, "s": 26043, "text": "Readers and Writers Problem: Suppose that a database is to be shared among several concurrent processes. Some of these processes may want only to read the database, whereas others may want to update (that is, to read and write) the database. We distinguish between these two types of processes by referring to the former as readers and to the latter as writers. Precisely in OS we call this situation as the readers-writers problem. Problem parameters: One set of data is shared among a number of processes. Once a writer is ready, it performs its write. Only one writer may write at a time. If a process is writing, no other process can read it. If at least one reader is reading, no other process can write. Readers may not write and only read. " }, { "code": null, "e": 26853, "s": 26796, "text": "One set of data is shared among a number of processes. " }, { "code": null, "e": 26939, "s": 26853, "text": "Once a writer is ready, it performs its write. Only one writer may write at a time. " }, { "code": null, "e": 26996, "s": 26939, "text": "If a process is writing, no other process can read it. " }, { "code": null, "e": 27061, "s": 26996, "text": "If at least one reader is reading, no other process can write. " }, { "code": null, "e": 27100, "s": 27061, "text": "Readers may not write and only read. " }, { "code": null, "e": 27393, "s": 27100, "text": "Sleeping Barber Problem: Barber shop with one barber, one barber chair and N chairs to wait in. When no customers the barber goes to sleep in barber chair and must be woken when a customer comes in. When barber is cutting hair new customers take empty seats to wait, or leave if no vacancy. " }, { "code": null, "e": 27414, "s": 27395, "text": "surindertarika1234" }, { "code": null, "e": 27427, "s": 27414, "text": "simmytarika5" }, { "code": null, "e": 27464, "s": 27427, "text": "Operating Systems-Process Management" }, { "code": null, "e": 27488, "s": 27464, "text": "Process Synchronization" }, { "code": null, "e": 27496, "s": 27488, "text": "GATE CS" }, { "code": null, "e": 27514, "s": 27496, "text": "Operating Systems" }, { "code": null, "e": 27532, "s": 27514, "text": "Operating Systems" }, { "code": null, "e": 27630, "s": 27532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27639, "s": 27630, "text": "Comments" }, { "code": null, "e": 27652, "s": 27639, "text": "Old Comments" }, { "code": null, "e": 27711, "s": 27652, "text": "Regular Expressions, Regular Grammar and Regular Languages" }, { "code": null, "e": 27764, "s": 27711, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 27804, "s": 27764, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 27838, "s": 27804, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 27879, "s": 27838, "text": "Preemptive and Non-Preemptive Scheduling" }, { "code": null, "e": 27918, "s": 27879, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 27958, "s": 27918, "text": "Program for FCFS CPU Scheduling | Set 1" }, { "code": null, "e": 28001, "s": 27958, "text": "Program for Round Robin scheduling | Set 1" }, { "code": null, "e": 28082, "s": 28001, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" } ]
Creating a better dashboard with Python, Dash, and Plotly | by Brad Bartram | Towards Data Science
My hobby is examining the depths of commodities and futures. As one could likely imagine, there is a lot of data and analysis that goes into it. Tables, reports, charts, graphs — you name it, it’s there. In trying to move forward and make heads or tails of it all, I find myself needing to visualize things that aren’t always existing. I need to see the data how I want to see it. If you’re in data analysis in any form or line of business, you likely already know what I’m talking about. However, there are a lot of people who are new to data analysis who are just dipping their toes in the water. There are also some more experienced people who just haven’t used these tools. This article is for anyone looking to do more or maybe just branch into a new tool. Maybe you’ve done the basics with Dash and Plotly and want to see something different. Hopefully this answers some questions or spurs on some new creative idea. I am going to approach this article with a ground-up approach. I will explain how this project came to be, its structure and capabilities, and where I can see it going in the future. Because of the size, I can’t do a complete line-by-line dissection of everything. However, I have taken great pains to write verbose, simple code with plenty of inline documentation. The repository files will be invaluable as a complement. My aim is to provide an overview of the template for getting a project like this running and showing just a little of what is possible. You don’t need to really understand the underlying data or even have an interest in it to gain insights. If you are into commodities and futures, then this will have a whole other dimension of value. As I said in the intro, my hobby is collecting and analyzing commodities data. One great source for this data is the weekly reports provided by the Commodities Futures Trading Commission (CFTC). The data I’m using for this entire project is housed here: https://www.cftc.gov/MarketReports/CommitmentsofTraders/index.htm For me, this whole project began as a dissection of some reports. When I first started, I wrote up a quick script that would grab the reports, process the files a bit, add some values, and output some charts. Then the number of reports began to grow. As I went on, I started looking at multiple commodities. I’d run my script and I’d have a few dozen tabs filling a browser window with all manner of charts. This was unsustainable. I needed to organize it all. So, the dashboard was conceptualized. Like all lazy programmers, I started with a template. The template happened to be a standard one I have used in the past and refined for much larger, database driven analytics system. I began ripping out what I didn’t need and started building. I don’t bring this up to waste time with needless descriptions and stories, but instead to give some logic behind some architectural decisions. Things that might seem odd at first glance. However, it all makes sense when put in the context of extending the simple into a more robust and complex system. Good solutions solve today’s problems. Better solutions look toward the future. Great systems incorporate both. As we get into it, you will need access to the code. This is the link to my repository for this project. All code examples and references are taken from here: github.com This dashboard incorporates several elements divided into distinct files for organizations. main.py — this file contains the dashboard code and serves as the front-end organization file.support_functions.py — this file is the workhorse of the system. Everything from report retrieval to actual chart creation lives here.business_logic.py — this file serves as the bridge to collecting the data and setting up the necessary dataframes.layout_configs.py — this file contains helper elements for styling charts the way I want to see them and defining the tools I want to use. main.py — this file contains the dashboard code and serves as the front-end organization file. support_functions.py — this file is the workhorse of the system. Everything from report retrieval to actual chart creation lives here. business_logic.py — this file serves as the bridge to collecting the data and setting up the necessary dataframes. layout_configs.py — this file contains helper elements for styling charts the way I want to see them and defining the tools I want to use. If I were to refactor this further, I could eliminate some of these files just by reorganizing. However, as systems grow, it provides a nice balance for incorporating other functions appropriately. For example, in my larger applications, my business_logic file handles database calls and a lot more data wrangling before things get passed on. Let’s begin by talking about some of the background functions we need to get the data. We can’t really do much without some data. deacot_file = "/tmp/deacot2021.txt"da_file = "/tmp/deacot_DA_2021.txt"# Data Retreival and Handling# Function to retrieve reportsdef get_COT(url, file_name): with urllib.request.urlopen(url) as response, open(file_name, "wb") as out_file: shutil.copyfileobj(response, out_file) with zipfile.ZipFile(file_name) as zf: zf.extractall()# Function to make sure things are fresh for datadef get_reports(): freshness_date = datetime.now() - timedelta(days=7) if os.path.exists(deacot_file): filetime = datetime.fromtimestamp(os.path.getctime(deacot_file)) if (filetime - timedelta(days=7)) <= freshness_date: print("Deacot file exists and is current - using cached data") else: get_COT( "https://www.cftc.gov/files/dea/history/deacot2021.zip", "deacot2021.zip",) os.rename(r"annual.txt", deacot_file) print("Deacot file is stale - getting fresh copy") else: print("Deacot file does not exist - getting fresh copy") get_COT( "https://www.cftc.gov/files/dea/history/deacot2021.zip", "deacot2021.zip") os.rename(r"annual.txt", deacot_file) if os.path.exists(da_file): filetime = datetime.fromtimestamp(os.path.getctime(da_file)) if (filetime - timedelta(days=7)) <= freshness_date: print("Disaggregation report file exists and is current - using cached data") else: get_COT( "https://www.cftc.gov/files/dea/history/fut_disagg_txt_2021.zip", "fut_disagg_txt_2021.zip",) os.rename(r"f_year.txt", da_file) print( "Disaggregation report file is stale - getting fresh copy") else: print( "Disaggregation report file does not exist - getting fresh copy") get_COT( "https://www.cftc.gov/files/dea/history/fut_disagg_txt_2021.zip", "fut_disagg_txt_2021.zip",) os.rename(r"f_year.txt", da_file) The two functions above (formatted horribly in Medium’s code box) do several things. First, the function get_reports() evaluates to see if the text report files exist. If they do, they are checked to see if they are “fresh” as in they are less than or equal to seven days old. If they are good, the existing files are used. If not, new ones are retrieved. Likewise, if the files do not exist, they are retrieved from the CFTC website. Retrieval of files uses the first function which is get_COT and takes the url and filename as arguments. These functions use python modules zip file, url lib, shutil, os, and datetime. Two variables are set to define path. If using this code, remember to set those variables appropriately for your situation. Once we have the files in place, we have data to work with. But, it’s still raw. The next two functions in the file “deacot_process” and “DA_process” goes through some dataframe modifications. Generally, these functions first, rename a number of columns to make things easier to work with. Next, they sort the dataframe by date to ensure things are in order in an expected way. After that, some new, calculated columns are created for easy reference later. Finally, the “exchange” column is split and two new columns for commodity and market are created. The last step is necessary to provide for some labels in charts and other locations later. Personally, I always find it a challenge to figure whether I should add calculated columns to the main dataframe or just wait until later and do it then. My personal rule is if I think there’s a chance I might need it in more than one place, I’ll do it to the main. The balance of this file is comprised of functions to generate specific charts that will be used on the dashboard. I won’t go into specific detail on them, but I encourage anyone to ask any questions if something is unclear. Since this was a chart-first process, the charts were defined prior to incorporation into the dashboard framework. It made sense to simply create them as callable functions rather than take other approaches. But, as with anything, there is more than one way to tackle the challenge. The key to remember is that the chart is returned by the function as a ready-to-go object. That means you can call it as the output of a function, as a figure variable, or inline as part of the layout object. Your choice really comes down to organization and use. The business_logic.py file is very simple in this application. At 41 lines total, including a lot of comments, it really just provides an entry into running certain functions when the application starts or reloads. """ This files does a lot of the dataframe work and larger data functions. Mostly this is data retrieval, organization, and making sure everything is ready to be called by the main app via call backs. This is called by main.py and in turn calls support functions when needed"""import pandas as pdimport numpy as npimport plotly.io as pioimport support_functions as sf pd.options.plotting.backend = "plotly"pio.templates.default = "plotly_dark" # Make sure we have data# This will check to see if a file exists and if not gets one# This also checks the data freshnesssf.get_reports() # Get the data frames to work with# DEACOT reportdf_deacot = pd.read_csv("/tmp/deacot2021.txt", na_values="x")df_deacot = sf.deacot_process(df_deacot) # Disambiguation reportdf_da = pd.read_csv("/tmp/deacot_DA_2021.txt", na_values="x", low_memory=False)df_da = sf.DA_process(df_da) ##################################################### Generate the commodities list - use the DA listing####################################################da_list = df_da["Exchange"].unique()da_list = np.sort(da_list) if __name__ == "__main__": print("business logic should not be run like this") The general layout is as follows: Set up the dataframe backend for plotting to be plotly.Configure the default template to be a dark theme.Get the reports using the functionRead the CSVs into a dataframe and process appropriatelyCreate a new array of just the unique values in the exchange column Set up the dataframe backend for plotting to be plotly. Configure the default template to be a dark theme. Get the reports using the function Read the CSVs into a dataframe and process appropriately Create a new array of just the unique values in the exchange column Item 5 is used to create the master list of commodities that we will use to drive the dashboard views and update the charts appropriately. The layout_config.py file holds some styling data that can be reused across charts. It mainly exists to simplify the layouts and declutter the chart building processes. For example: layout = go.Layout( template="plotly_dark", # plot_bgcolor="#FFFFFF", hovermode="x", hoverdistance=100, # Distance to show hover label of data point spikedistance=1000, # Distance to show spike xaxis=dict( title="time", linecolor="#BCCCDC", showspikes=True, spikesnap="cursor", spikethickness=1, spikedash="dot", spikecolor="#999999", spikemode="across", ), yaxis=dict( title="price", linecolor="#BCCCDC", tickformat=".2%", showspikes=True, spikesnap="cursor", spikethickness=1, spikedash="dot", spikecolor="#999999", spikemode="across", ),)tool_config = { "modeBarButtonsToAdd": [ "drawline", "drawopenpath", "drawclosedpath", "drawcircle", "drawrect", "eraseshape", "hoverclosest", "hovercompare", ], "modeBarButtonsToRemove": [ "zoom2d", "pan2d", "select2d", "lasso2d", "zoomIn2d", "zoomOut2d", "autoScale2d", ], "showTips": False, "displaylogo": False,} In both of these cases, placing these types of configurations allows for one central point of management for chart presentation and tool configuration. The moment you’ve all been waiting for, building the actual dashboard code. I know that when I first started using Dash, the main file seemed daunting. There was a lot going on. It also didn’t have distinct organizational flow to my mind. But, I made it work in a way that made sense to me. This is what I will lead you through. I tend to arrange my main file in the following fashion: Style modifiers.Content structures. Generally, these are containers holding row data. I find it easiest to construct my file in the manner that reflects the actual layout. I start with the top and move downward.Page Layout aggregations. Content structures are put together into page layouts and organized into one reference.Application parameters. This is where the actual application behavior resides along with global items like application title, stylesheets and themes, etc.Callbacks. These are the bits of dynamic code that allows widgets to function and really makes a dashboard functional.Server Run. This is where the final line resides for actually starting the server and running the dashboard. Style modifiers. Content structures. Generally, these are containers holding row data. I find it easiest to construct my file in the manner that reflects the actual layout. I start with the top and move downward. Page Layout aggregations. Content structures are put together into page layouts and organized into one reference. Application parameters. This is where the actual application behavior resides along with global items like application title, stylesheets and themes, etc. Callbacks. These are the bits of dynamic code that allows widgets to function and really makes a dashboard functional. Server Run. This is where the final line resides for actually starting the server and running the dashboard. Let’s walk through a few of these and give you a feel for the flow of how all the pieces fit together. I’m going to take these a bit out of order, but it’s not a big deal. First, let’s look at application parameters and server run together. These comprise the bones of the dashboard and inform some of the other aspects of the layout. ###################################################### Application parameters#####################################################app = dash.Dash( __name__, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.CYBORG],)app.title = "CFTC Data Analysis"app.layout = html.Div( [ dcc.Location( id="url", refresh=False), html.Div(id="page-content") ]) # Multi-page selector callback - left in for future use@app.callback( Output("page-content", "children"), Input("url", "pathname"))def display_page(pathname): # if pathname == "/market-sentiment": # return volumes # else: return main_page#################################################### Server Run###################################################if __name__ == "__main__": app.run_server( debug=True, host="0.0.0.0", port=8050, dev_tools_hot_reload=True ) For the most part, the application parameters should be self-explanatory. The key item to note is the “external_stylesheets”. This allows for exactly what is said — an external stylesheet. In this case, I’m using a bootstrap theme named CYBORG, which is a dark theme. Here, we also have the app.title parameter for the application to set a title. The app.layout parameter sets up a process by which the id named “page-content” is delivered via the output of the callback function “display_page”. This is not strictly necessary, but it allows for reading of a URL path and feeding distinct content based on that path. It is used with multi-page applications. I left it in as a reference. Finally, we have the Server Run section. Here is where we can set the listening ip address and port. Since I run my dashboards on a local server for use on all of my computers, I am configured to listen publicly on port 8050. I also have debug set to True. This reduces the chatter in my log files. With debug set true, the application will also do a hot reload when it detects a change in any of the files, which works well for development purposes. A lot of articles and videos and other material has been created around callbacks. It is a complex subject and one I will only scratch the surface on. However, it’s a subject that can at least give you an understanding of how they are arranged. In this dashboard, there is a primary dropdown selector that updates all the charts on the page. I’ll cover the dropdown later, but for now, it’s important to understand that there is an input provided by this dropdown that has an id of “future” With that in mind, let’s break down the first callback in the main.py file. # Sentiment charts@app.callback( dash.dependencies.Output("deacot_sent", "figure"), [dash.dependencies.Input("future", "value")],)def deacot_sentiment(future1): df1 = bl.df_deacot[bl.df_deacot["Exchange"] == future1] df1.set_index("Date", inplace=True) arr = df1["commodity"].unique() asset = arr[0] fig = sf.make_sentiment_chart(df1, asset) return fig In not a lot of code, there is a lot going on. Mostly, this is because of the organization we covered earlier. The callback begins with the decorator app.callback. Here we have a line for Output and a line for Input. Both take arguments for the id of the element they reference and the type of data being passed. In this case, the Input is collecting a value from the “future” id, which I mentioned in the beginning of this section. The output is sending figure data to “deacot_sent”. (Yeah, I know I should use hyphens for ids...) With the input and output routes sent we have to do something to turn that value into a figure. That’s where the function “deacot_sentiment” comes in. It takes the input parameter and simply names it future1. This function first filters the dataframe defined in business_logic named df_deacot and matches on the value passed in from future1. We are left with a consolidated dataframe (df1) that is comprised of data where the exchange column matches the selection from the drop down. The next line sets the date column as the index. We next take the unique values in the commodity column and throw them into an array. Because of the way the report is filtered, we should only have a single value. However, because sometimes things don’t go as planned, we pull the first array element into a variable named “asset”. Our dataframe (df1) and the variable “asset” are then fed into the chart function sf.make_sentiment_chart that is located in the support_functions file. The output of the function is set to the variable “fig”, which is the code of the chart. Finally, fig is returned as a figure via the output of the callback. It’s heading to the id “deacot_sent”. Some things to note are callbacks can have more than one input as well as output. Outputs can be chained to other callbacks. However, let’s follow this figure’s path... We just saw how an input will trigger a callback and return a figure to an id. If we jump back to the content, we can see this in action as we build out the element for display. As I mentioned earlier, I like to arrange my main file according to a top down layout set by rows. It helps me envision the grid and keep it in my head while building. In this case, we have a row defined for two sentiment charts: # Container for sentiment chartssentiment_direction = dbc.Row( [ dbc.Col( dcc.Graph( id="deacot_sent", style={"height": "70vh"}, config=lc.tool_config, ), md=6, ), dbc.Col( dcc.Graph( id="da_sent", style={"height": "70vh"}, config=lc.tool_config, ), md=6, ), ]) The above code sets up a row with two columns that each contain a different chart. The first column has the id of “deacot_sent”, which is the target id for the output of our callback. Since we are holding a chart, we use the graph container provided by the dash core components (dcc) library. Here we set the id along with a number of other parameters. I am specifically setting the height as a style override. I am also adding a “config” element, which is set to be the tool_config value from the layout_config.py file that I highlighted above. Because the element is being populated from the output of a callback, an explicit data source is not required. If we were generating our charts in a different fashion, we might use the “figure” parameter to hold the data. Finally, within the dbc.Col function, we see the “md=6”. This is a format value that uses the bootstrap framework. In it, each row is divided into 12 units. Setting “md=6” tells the framework that I want my column to fill 6 or half of the total. The second column is identical except for a different id value. This column will be the output for another chart on the same row that takes up the other half of the space. The final step on our journey of input to output is to actually link the row to a page layout that will be displayed via the application. This is quite simple: ##################################################### Layout Creation Section####################################################main_page = html.Div( [ html.Hr(), html.H5( "Futures Market Comparison and Analysis", style=TEXT_STYLE ), html.Hr(), future_select, html.Hr(), info_bar, html.Hr(), sentiment_direction, html.Hr(), da_postiions, html.Hr(), da_pos_snap, html.Hr(), da_diffs, html.Hr(), references, ], style=CONTENT_STYLE,) If you remember back to the section on application parameters, you will note the page-content id for the app.layout was the output of the callback that returned with main_page. It’s ok — read that sentence again, there’s a lot chained together. The main_page variable is just another container for an html.div. The Div is comprised of references to other elements previously constructed. We essentially just keep building blocks upon blocks to get to a final result. Here is where the page comes together though. In the code above, I begin with space, a title to display, more space, a row containing the selection drop down, space, an info bar, more space, and then our first row of charts. This is the row I showed above. This is everything we need to construct our dashboards. Actually, it’s a lot more than we need since this design is a bit large and dispersed across several files. However, you might be able to see by now why breaking out various elements for organization is effective to keep your sanity. There are a lot of blocks and elements. Organizing them into logical units can go a long way toward making a useful and maintainable application. Before I wrap up, I do want to pull together the drop down for you. The drop down drives the dashboard. It provides the point of original data and allows the entire set of reports to be evaluated based on the specific commodity. It is the first row under the title on the page and is critically important. # Create drop-down selectorfuture_select = dbc.Row( [ dbc.Col( [ html.Div( [ dcc.Dropdown( id="future", options=[ {"label": i, "value": i} for i in bl.da_list], value="SILVER - COMMODITY EXCHANGE INC.", ), ], className="dash-bootstrap", ), ], md=6, ) ]) As before, this is a pretty normal construction. We begin with the row and add a column. Within the column is a Div that contains the dropdown with id “future”. Remember that “future” is the input on the callbacks. Within the dropdown, we set the options, which is simply an expanded list of labels and values based on the bl.da_list array we defined in the business_logic file. This is a unique listing of all commodities pulled from the DA report dataframe. As a practical matter, there the DA report dataframe is less inclusive than the DEACOT report, so using DA for the master list is just the least common denominator. We finally set a default value, which is to have something to load on startup. In this case, I use silver since that’s a commodity I look at often. Also important, especially when using a dark theme, is to set the classname value. This allows the appropriate style to be applied so the drop down looks right on the dark background. This will save you a lot of aesthetic headaches. Along the style lines, while we only have one column, it is set to only extend across half the total row. This was a design choice more than anything. You might disagree. This was a lot to cover. Dash is not a simple platform since there is so much that you can accomplish with it. It is incredibly capable and once you get used to its nuances, things begin to make more sense and you can build quickly. As I mentioned when this started, grab the code from my repository and go through it. While this was just an overview to give a taste, the actual code is stepped through with documentation. More importantly, it’s a functional system that you can run and explore on your own. If you do pull the code, feel free to use it as you will. Build something cool or just dissect it and learn what you can. If you do tend to use something I’ve written, just give me a shout out. Otherwise, it’s my gift to the world. If there are problems with clarity or issues relating to the code, feel free to reach out to me directly or just leave a comment. I encourage feedback and suggestions for ways to make this better.
[ { "code": null, "e": 376, "s": 172, "text": "My hobby is examining the depths of commodities and futures. As one could likely imagine, there is a lot of data and analysis that goes into it. Tables, reports, charts, graphs — you name it, it’s there." }, { "code": null, "e": 553, "s": 376, "text": "In trying to move forward and make heads or tails of it all, I find myself needing to visualize things that aren’t always existing. I need to see the data how I want to see it." }, { "code": null, "e": 850, "s": 553, "text": "If you’re in data analysis in any form or line of business, you likely already know what I’m talking about. However, there are a lot of people who are new to data analysis who are just dipping their toes in the water. There are also some more experienced people who just haven’t used these tools." }, { "code": null, "e": 1021, "s": 850, "text": "This article is for anyone looking to do more or maybe just branch into a new tool. Maybe you’ve done the basics with Dash and Plotly and want to see something different." }, { "code": null, "e": 1095, "s": 1021, "text": "Hopefully this answers some questions or spurs on some new creative idea." }, { "code": null, "e": 1278, "s": 1095, "text": "I am going to approach this article with a ground-up approach. I will explain how this project came to be, its structure and capabilities, and where I can see it going in the future." }, { "code": null, "e": 1518, "s": 1278, "text": "Because of the size, I can’t do a complete line-by-line dissection of everything. However, I have taken great pains to write verbose, simple code with plenty of inline documentation. The repository files will be invaluable as a complement." }, { "code": null, "e": 1854, "s": 1518, "text": "My aim is to provide an overview of the template for getting a project like this running and showing just a little of what is possible. You don’t need to really understand the underlying data or even have an interest in it to gain insights. If you are into commodities and futures, then this will have a whole other dimension of value." }, { "code": null, "e": 2049, "s": 1854, "text": "As I said in the intro, my hobby is collecting and analyzing commodities data. One great source for this data is the weekly reports provided by the Commodities Futures Trading Commission (CFTC)." }, { "code": null, "e": 2174, "s": 2049, "text": "The data I’m using for this entire project is housed here: https://www.cftc.gov/MarketReports/CommitmentsofTraders/index.htm" }, { "code": null, "e": 2425, "s": 2174, "text": "For me, this whole project began as a dissection of some reports. When I first started, I wrote up a quick script that would grab the reports, process the files a bit, add some values, and output some charts. Then the number of reports began to grow." }, { "code": null, "e": 2606, "s": 2425, "text": "As I went on, I started looking at multiple commodities. I’d run my script and I’d have a few dozen tabs filling a browser window with all manner of charts. This was unsustainable." }, { "code": null, "e": 2673, "s": 2606, "text": "I needed to organize it all. So, the dashboard was conceptualized." }, { "code": null, "e": 2918, "s": 2673, "text": "Like all lazy programmers, I started with a template. The template happened to be a standard one I have used in the past and refined for much larger, database driven analytics system. I began ripping out what I didn’t need and started building." }, { "code": null, "e": 3221, "s": 2918, "text": "I don’t bring this up to waste time with needless descriptions and stories, but instead to give some logic behind some architectural decisions. Things that might seem odd at first glance. However, it all makes sense when put in the context of extending the simple into a more robust and complex system." }, { "code": null, "e": 3333, "s": 3221, "text": "Good solutions solve today’s problems. Better solutions look toward the future. Great systems incorporate both." }, { "code": null, "e": 3492, "s": 3333, "text": "As we get into it, you will need access to the code. This is the link to my repository for this project. All code examples and references are taken from here:" }, { "code": null, "e": 3503, "s": 3492, "text": "github.com" }, { "code": null, "e": 3595, "s": 3503, "text": "This dashboard incorporates several elements divided into distinct files for organizations." }, { "code": null, "e": 4076, "s": 3595, "text": "main.py — this file contains the dashboard code and serves as the front-end organization file.support_functions.py — this file is the workhorse of the system. Everything from report retrieval to actual chart creation lives here.business_logic.py — this file serves as the bridge to collecting the data and setting up the necessary dataframes.layout_configs.py — this file contains helper elements for styling charts the way I want to see them and defining the tools I want to use." }, { "code": null, "e": 4171, "s": 4076, "text": "main.py — this file contains the dashboard code and serves as the front-end organization file." }, { "code": null, "e": 4306, "s": 4171, "text": "support_functions.py — this file is the workhorse of the system. Everything from report retrieval to actual chart creation lives here." }, { "code": null, "e": 4421, "s": 4306, "text": "business_logic.py — this file serves as the bridge to collecting the data and setting up the necessary dataframes." }, { "code": null, "e": 4560, "s": 4421, "text": "layout_configs.py — this file contains helper elements for styling charts the way I want to see them and defining the tools I want to use." }, { "code": null, "e": 4903, "s": 4560, "text": "If I were to refactor this further, I could eliminate some of these files just by reorganizing. However, as systems grow, it provides a nice balance for incorporating other functions appropriately. For example, in my larger applications, my business_logic file handles database calls and a lot more data wrangling before things get passed on." }, { "code": null, "e": 5033, "s": 4903, "text": "Let’s begin by talking about some of the background functions we need to get the data. We can’t really do much without some data." }, { "code": null, "e": 6848, "s": 5033, "text": "deacot_file = \"/tmp/deacot2021.txt\"da_file = \"/tmp/deacot_DA_2021.txt\"# Data Retreival and Handling# Function to retrieve reportsdef get_COT(url, file_name): with urllib.request.urlopen(url) as response, open(file_name, \"wb\") as out_file: shutil.copyfileobj(response, out_file) with zipfile.ZipFile(file_name) as zf: zf.extractall()# Function to make sure things are fresh for datadef get_reports(): freshness_date = datetime.now() - timedelta(days=7) if os.path.exists(deacot_file): filetime = datetime.fromtimestamp(os.path.getctime(deacot_file)) if (filetime - timedelta(days=7)) <= freshness_date: print(\"Deacot file exists and is current - using cached data\") else: get_COT( \"https://www.cftc.gov/files/dea/history/deacot2021.zip\", \"deacot2021.zip\",) os.rename(r\"annual.txt\", deacot_file) print(\"Deacot file is stale - getting fresh copy\") else: print(\"Deacot file does not exist - getting fresh copy\") get_COT( \"https://www.cftc.gov/files/dea/history/deacot2021.zip\", \"deacot2021.zip\") os.rename(r\"annual.txt\", deacot_file) if os.path.exists(da_file): filetime = datetime.fromtimestamp(os.path.getctime(da_file)) if (filetime - timedelta(days=7)) <= freshness_date: print(\"Disaggregation report file exists and is current - using cached data\") else: get_COT( \"https://www.cftc.gov/files/dea/history/fut_disagg_txt_2021.zip\", \"fut_disagg_txt_2021.zip\",) os.rename(r\"f_year.txt\", da_file) print( \"Disaggregation report file is stale - getting fresh copy\") else: print( \"Disaggregation report file does not exist - getting fresh copy\") get_COT( \"https://www.cftc.gov/files/dea/history/fut_disagg_txt_2021.zip\", \"fut_disagg_txt_2021.zip\",) os.rename(r\"f_year.txt\", da_file)" }, { "code": null, "e": 7283, "s": 6848, "text": "The two functions above (formatted horribly in Medium’s code box) do several things. First, the function get_reports() evaluates to see if the text report files exist. If they do, they are checked to see if they are “fresh” as in they are less than or equal to seven days old. If they are good, the existing files are used. If not, new ones are retrieved. Likewise, if the files do not exist, they are retrieved from the CFTC website." }, { "code": null, "e": 7506, "s": 7283, "text": "Retrieval of files uses the first function which is get_COT and takes the url and filename as arguments. These functions use python modules zip file, url lib, shutil, os, and datetime. Two variables are set to define path." }, { "code": null, "e": 7592, "s": 7506, "text": "If using this code, remember to set those variables appropriately for your situation." }, { "code": null, "e": 7785, "s": 7592, "text": "Once we have the files in place, we have data to work with. But, it’s still raw. The next two functions in the file “deacot_process” and “DA_process” goes through some dataframe modifications." }, { "code": null, "e": 8238, "s": 7785, "text": "Generally, these functions first, rename a number of columns to make things easier to work with. Next, they sort the dataframe by date to ensure things are in order in an expected way. After that, some new, calculated columns are created for easy reference later. Finally, the “exchange” column is split and two new columns for commodity and market are created. The last step is necessary to provide for some labels in charts and other locations later." }, { "code": null, "e": 8504, "s": 8238, "text": "Personally, I always find it a challenge to figure whether I should add calculated columns to the main dataframe or just wait until later and do it then. My personal rule is if I think there’s a chance I might need it in more than one place, I’ll do it to the main." }, { "code": null, "e": 8729, "s": 8504, "text": "The balance of this file is comprised of functions to generate specific charts that will be used on the dashboard. I won’t go into specific detail on them, but I encourage anyone to ask any questions if something is unclear." }, { "code": null, "e": 9012, "s": 8729, "text": "Since this was a chart-first process, the charts were defined prior to incorporation into the dashboard framework. It made sense to simply create them as callable functions rather than take other approaches. But, as with anything, there is more than one way to tackle the challenge." }, { "code": null, "e": 9276, "s": 9012, "text": "The key to remember is that the chart is returned by the function as a ready-to-go object. That means you can call it as the output of a function, as a figure variable, or inline as part of the layout object. Your choice really comes down to organization and use." }, { "code": null, "e": 9491, "s": 9276, "text": "The business_logic.py file is very simple in this application. At 41 lines total, including a lot of comments, it really just provides an entry into running certain functions when the application starts or reloads." }, { "code": null, "e": 10666, "s": 9491, "text": "\"\"\" This files does a lot of the dataframe work and larger data functions. Mostly this is data retrieval, organization, and making sure everything is ready to be called by the main app via call backs. This is called by main.py and in turn calls support functions when needed\"\"\"import pandas as pdimport numpy as npimport plotly.io as pioimport support_functions as sf pd.options.plotting.backend = \"plotly\"pio.templates.default = \"plotly_dark\" # Make sure we have data# This will check to see if a file exists and if not gets one# This also checks the data freshnesssf.get_reports() # Get the data frames to work with# DEACOT reportdf_deacot = pd.read_csv(\"/tmp/deacot2021.txt\", na_values=\"x\")df_deacot = sf.deacot_process(df_deacot) # Disambiguation reportdf_da = pd.read_csv(\"/tmp/deacot_DA_2021.txt\", na_values=\"x\", low_memory=False)df_da = sf.DA_process(df_da) ##################################################### Generate the commodities list - use the DA listing####################################################da_list = df_da[\"Exchange\"].unique()da_list = np.sort(da_list) if __name__ == \"__main__\": print(\"business logic should not be run like this\")" }, { "code": null, "e": 10700, "s": 10666, "text": "The general layout is as follows:" }, { "code": null, "e": 10963, "s": 10700, "text": "Set up the dataframe backend for plotting to be plotly.Configure the default template to be a dark theme.Get the reports using the functionRead the CSVs into a dataframe and process appropriatelyCreate a new array of just the unique values in the exchange column" }, { "code": null, "e": 11019, "s": 10963, "text": "Set up the dataframe backend for plotting to be plotly." }, { "code": null, "e": 11070, "s": 11019, "text": "Configure the default template to be a dark theme." }, { "code": null, "e": 11105, "s": 11070, "text": "Get the reports using the function" }, { "code": null, "e": 11162, "s": 11105, "text": "Read the CSVs into a dataframe and process appropriately" }, { "code": null, "e": 11230, "s": 11162, "text": "Create a new array of just the unique values in the exchange column" }, { "code": null, "e": 11369, "s": 11230, "text": "Item 5 is used to create the master list of commodities that we will use to drive the dashboard views and update the charts appropriately." }, { "code": null, "e": 11538, "s": 11369, "text": "The layout_config.py file holds some styling data that can be reused across charts. It mainly exists to simplify the layouts and declutter the chart building processes." }, { "code": null, "e": 11551, "s": 11538, "text": "For example:" }, { "code": null, "e": 12838, "s": 11551, "text": "layout = go.Layout( template=\"plotly_dark\", # plot_bgcolor=\"#FFFFFF\", hovermode=\"x\", hoverdistance=100, # Distance to show hover label of data point spikedistance=1000, # Distance to show spike xaxis=dict( title=\"time\", linecolor=\"#BCCCDC\", showspikes=True, spikesnap=\"cursor\", spikethickness=1, spikedash=\"dot\", spikecolor=\"#999999\", spikemode=\"across\", ), yaxis=dict( title=\"price\", linecolor=\"#BCCCDC\", tickformat=\".2%\", showspikes=True, spikesnap=\"cursor\", spikethickness=1, spikedash=\"dot\", spikecolor=\"#999999\", spikemode=\"across\", ),)tool_config = { \"modeBarButtonsToAdd\": [ \"drawline\", \"drawopenpath\", \"drawclosedpath\", \"drawcircle\", \"drawrect\", \"eraseshape\", \"hoverclosest\", \"hovercompare\", ], \"modeBarButtonsToRemove\": [ \"zoom2d\", \"pan2d\", \"select2d\", \"lasso2d\", \"zoomIn2d\", \"zoomOut2d\", \"autoScale2d\", ], \"showTips\": False, \"displaylogo\": False,}" }, { "code": null, "e": 12990, "s": 12838, "text": "In both of these cases, placing these types of configurations allows for one central point of management for chart presentation and tool configuration." }, { "code": null, "e": 13066, "s": 12990, "text": "The moment you’ve all been waiting for, building the actual dashboard code." }, { "code": null, "e": 13319, "s": 13066, "text": "I know that when I first started using Dash, the main file seemed daunting. There was a lot going on. It also didn’t have distinct organizational flow to my mind. But, I made it work in a way that made sense to me. This is what I will lead you through." }, { "code": null, "e": 13376, "s": 13319, "text": "I tend to arrange my main file in the following fashion:" }, { "code": null, "e": 14081, "s": 13376, "text": "Style modifiers.Content structures. Generally, these are containers holding row data. I find it easiest to construct my file in the manner that reflects the actual layout. I start with the top and move downward.Page Layout aggregations. Content structures are put together into page layouts and organized into one reference.Application parameters. This is where the actual application behavior resides along with global items like application title, stylesheets and themes, etc.Callbacks. These are the bits of dynamic code that allows widgets to function and really makes a dashboard functional.Server Run. This is where the final line resides for actually starting the server and running the dashboard." }, { "code": null, "e": 14098, "s": 14081, "text": "Style modifiers." }, { "code": null, "e": 14294, "s": 14098, "text": "Content structures. Generally, these are containers holding row data. I find it easiest to construct my file in the manner that reflects the actual layout. I start with the top and move downward." }, { "code": null, "e": 14408, "s": 14294, "text": "Page Layout aggregations. Content structures are put together into page layouts and organized into one reference." }, { "code": null, "e": 14563, "s": 14408, "text": "Application parameters. This is where the actual application behavior resides along with global items like application title, stylesheets and themes, etc." }, { "code": null, "e": 14682, "s": 14563, "text": "Callbacks. These are the bits of dynamic code that allows widgets to function and really makes a dashboard functional." }, { "code": null, "e": 14791, "s": 14682, "text": "Server Run. This is where the final line resides for actually starting the server and running the dashboard." }, { "code": null, "e": 14963, "s": 14791, "text": "Let’s walk through a few of these and give you a feel for the flow of how all the pieces fit together. I’m going to take these a bit out of order, but it’s not a big deal." }, { "code": null, "e": 15126, "s": 14963, "text": "First, let’s look at application parameters and server run together. These comprise the bones of the dashboard and inform some of the other aspects of the layout." }, { "code": null, "e": 16041, "s": 15126, "text": "###################################################### Application parameters#####################################################app = dash.Dash( __name__, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.CYBORG],)app.title = \"CFTC Data Analysis\"app.layout = html.Div( [ dcc.Location( id=\"url\", refresh=False), html.Div(id=\"page-content\") ]) # Multi-page selector callback - left in for future use@app.callback( Output(\"page-content\", \"children\"), Input(\"url\", \"pathname\"))def display_page(pathname): # if pathname == \"/market-sentiment\": # return volumes # else: return main_page#################################################### Server Run###################################################if __name__ == \"__main__\": app.run_server( debug=True, host=\"0.0.0.0\", port=8050, dev_tools_hot_reload=True )" }, { "code": null, "e": 16309, "s": 16041, "text": "For the most part, the application parameters should be self-explanatory. The key item to note is the “external_stylesheets”. This allows for exactly what is said — an external stylesheet. In this case, I’m using a bootstrap theme named CYBORG, which is a dark theme." }, { "code": null, "e": 16728, "s": 16309, "text": "Here, we also have the app.title parameter for the application to set a title. The app.layout parameter sets up a process by which the id named “page-content” is delivered via the output of the callback function “display_page”. This is not strictly necessary, but it allows for reading of a URL path and feeding distinct content based on that path. It is used with multi-page applications. I left it in as a reference." }, { "code": null, "e": 17179, "s": 16728, "text": "Finally, we have the Server Run section. Here is where we can set the listening ip address and port. Since I run my dashboards on a local server for use on all of my computers, I am configured to listen publicly on port 8050. I also have debug set to True. This reduces the chatter in my log files. With debug set true, the application will also do a hot reload when it detects a change in any of the files, which works well for development purposes." }, { "code": null, "e": 17424, "s": 17179, "text": "A lot of articles and videos and other material has been created around callbacks. It is a complex subject and one I will only scratch the surface on. However, it’s a subject that can at least give you an understanding of how they are arranged." }, { "code": null, "e": 17670, "s": 17424, "text": "In this dashboard, there is a primary dropdown selector that updates all the charts on the page. I’ll cover the dropdown later, but for now, it’s important to understand that there is an input provided by this dropdown that has an id of “future”" }, { "code": null, "e": 17746, "s": 17670, "text": "With that in mind, let’s break down the first callback in the main.py file." }, { "code": null, "e": 18143, "s": 17746, "text": "# Sentiment charts@app.callback( dash.dependencies.Output(\"deacot_sent\", \"figure\"), [dash.dependencies.Input(\"future\", \"value\")],)def deacot_sentiment(future1): df1 = bl.df_deacot[bl.df_deacot[\"Exchange\"] == future1] df1.set_index(\"Date\", inplace=True) arr = df1[\"commodity\"].unique() asset = arr[0] fig = sf.make_sentiment_chart(df1, asset) return fig" }, { "code": null, "e": 18254, "s": 18143, "text": "In not a lot of code, there is a lot going on. Mostly, this is because of the organization we covered earlier." }, { "code": null, "e": 18456, "s": 18254, "text": "The callback begins with the decorator app.callback. Here we have a line for Output and a line for Input. Both take arguments for the id of the element they reference and the type of data being passed." }, { "code": null, "e": 18675, "s": 18456, "text": "In this case, the Input is collecting a value from the “future” id, which I mentioned in the beginning of this section. The output is sending figure data to “deacot_sent”. (Yeah, I know I should use hyphens for ids...)" }, { "code": null, "e": 18884, "s": 18675, "text": "With the input and output routes sent we have to do something to turn that value into a figure. That’s where the function “deacot_sentiment” comes in. It takes the input parameter and simply names it future1." }, { "code": null, "e": 19159, "s": 18884, "text": "This function first filters the dataframe defined in business_logic named df_deacot and matches on the value passed in from future1. We are left with a consolidated dataframe (df1) that is comprised of data where the exchange column matches the selection from the drop down." }, { "code": null, "e": 19490, "s": 19159, "text": "The next line sets the date column as the index. We next take the unique values in the commodity column and throw them into an array. Because of the way the report is filtered, we should only have a single value. However, because sometimes things don’t go as planned, we pull the first array element into a variable named “asset”." }, { "code": null, "e": 19732, "s": 19490, "text": "Our dataframe (df1) and the variable “asset” are then fed into the chart function sf.make_sentiment_chart that is located in the support_functions file. The output of the function is set to the variable “fig”, which is the code of the chart." }, { "code": null, "e": 19839, "s": 19732, "text": "Finally, fig is returned as a figure via the output of the callback. It’s heading to the id “deacot_sent”." }, { "code": null, "e": 19964, "s": 19839, "text": "Some things to note are callbacks can have more than one input as well as output. Outputs can be chained to other callbacks." }, { "code": null, "e": 20008, "s": 19964, "text": "However, let’s follow this figure’s path..." }, { "code": null, "e": 20186, "s": 20008, "text": "We just saw how an input will trigger a callback and return a figure to an id. If we jump back to the content, we can see this in action as we build out the element for display." }, { "code": null, "e": 20416, "s": 20186, "text": "As I mentioned earlier, I like to arrange my main file according to a top down layout set by rows. It helps me envision the grid and keep it in my head while building. In this case, we have a row defined for two sentiment charts:" }, { "code": null, "e": 20972, "s": 20416, "text": "# Container for sentiment chartssentiment_direction = dbc.Row( [ dbc.Col( dcc.Graph( id=\"deacot_sent\", style={\"height\": \"70vh\"}, config=lc.tool_config, ), md=6, ), dbc.Col( dcc.Graph( id=\"da_sent\", style={\"height\": \"70vh\"}, config=lc.tool_config, ), md=6, ), ])" }, { "code": null, "e": 21156, "s": 20972, "text": "The above code sets up a row with two columns that each contain a different chart. The first column has the id of “deacot_sent”, which is the target id for the output of our callback." }, { "code": null, "e": 21518, "s": 21156, "text": "Since we are holding a chart, we use the graph container provided by the dash core components (dcc) library. Here we set the id along with a number of other parameters. I am specifically setting the height as a style override. I am also adding a “config” element, which is set to be the tool_config value from the layout_config.py file that I highlighted above." }, { "code": null, "e": 21740, "s": 21518, "text": "Because the element is being populated from the output of a callback, an explicit data source is not required. If we were generating our charts in a different fashion, we might use the “figure” parameter to hold the data." }, { "code": null, "e": 21986, "s": 21740, "text": "Finally, within the dbc.Col function, we see the “md=6”. This is a format value that uses the bootstrap framework. In it, each row is divided into 12 units. Setting “md=6” tells the framework that I want my column to fill 6 or half of the total." }, { "code": null, "e": 22158, "s": 21986, "text": "The second column is identical except for a different id value. This column will be the output for another chart on the same row that takes up the other half of the space." }, { "code": null, "e": 22318, "s": 22158, "text": "The final step on our journey of input to output is to actually link the row to a page layout that will be displayed via the application. This is quite simple:" }, { "code": null, "e": 22955, "s": 22318, "text": "##################################################### Layout Creation Section####################################################main_page = html.Div( [ html.Hr(), html.H5( \"Futures Market Comparison and Analysis\", style=TEXT_STYLE ), html.Hr(), future_select, html.Hr(), info_bar, html.Hr(), sentiment_direction, html.Hr(), da_postiions, html.Hr(), da_pos_snap, html.Hr(), da_diffs, html.Hr(), references, ], style=CONTENT_STYLE,)" }, { "code": null, "e": 23200, "s": 22955, "text": "If you remember back to the section on application parameters, you will note the page-content id for the app.layout was the output of the callback that returned with main_page. It’s ok — read that sentence again, there’s a lot chained together." }, { "code": null, "e": 23422, "s": 23200, "text": "The main_page variable is just another container for an html.div. The Div is comprised of references to other elements previously constructed. We essentially just keep building blocks upon blocks to get to a final result." }, { "code": null, "e": 23679, "s": 23422, "text": "Here is where the page comes together though. In the code above, I begin with space, a title to display, more space, a row containing the selection drop down, space, an info bar, more space, and then our first row of charts. This is the row I showed above." }, { "code": null, "e": 24115, "s": 23679, "text": "This is everything we need to construct our dashboards. Actually, it’s a lot more than we need since this design is a bit large and dispersed across several files. However, you might be able to see by now why breaking out various elements for organization is effective to keep your sanity. There are a lot of blocks and elements. Organizing them into logical units can go a long way toward making a useful and maintainable application." }, { "code": null, "e": 24183, "s": 24115, "text": "Before I wrap up, I do want to pull together the drop down for you." }, { "code": null, "e": 24421, "s": 24183, "text": "The drop down drives the dashboard. It provides the point of original data and allows the entire set of reports to be evaluated based on the specific commodity. It is the first row under the title on the page and is critically important." }, { "code": null, "e": 25099, "s": 24421, "text": "# Create drop-down selectorfuture_select = dbc.Row( [ dbc.Col( [ html.Div( [ dcc.Dropdown( id=\"future\", options=[ {\"label\": i, \"value\": i} for i in bl.da_list], value=\"SILVER - COMMODITY EXCHANGE INC.\", ), ], className=\"dash-bootstrap\", ), ], md=6, ) ])" }, { "code": null, "e": 25314, "s": 25099, "text": "As before, this is a pretty normal construction. We begin with the row and add a column. Within the column is a Div that contains the dropdown with id “future”. Remember that “future” is the input on the callbacks." }, { "code": null, "e": 25724, "s": 25314, "text": "Within the dropdown, we set the options, which is simply an expanded list of labels and values based on the bl.da_list array we defined in the business_logic file. This is a unique listing of all commodities pulled from the DA report dataframe. As a practical matter, there the DA report dataframe is less inclusive than the DEACOT report, so using DA for the master list is just the least common denominator." }, { "code": null, "e": 25872, "s": 25724, "text": "We finally set a default value, which is to have something to load on startup. In this case, I use silver since that’s a commodity I look at often." }, { "code": null, "e": 26105, "s": 25872, "text": "Also important, especially when using a dark theme, is to set the classname value. This allows the appropriate style to be applied so the drop down looks right on the dark background. This will save you a lot of aesthetic headaches." }, { "code": null, "e": 26276, "s": 26105, "text": "Along the style lines, while we only have one column, it is set to only extend across half the total row. This was a design choice more than anything. You might disagree." }, { "code": null, "e": 26509, "s": 26276, "text": "This was a lot to cover. Dash is not a simple platform since there is so much that you can accomplish with it. It is incredibly capable and once you get used to its nuances, things begin to make more sense and you can build quickly." }, { "code": null, "e": 26784, "s": 26509, "text": "As I mentioned when this started, grab the code from my repository and go through it. While this was just an overview to give a taste, the actual code is stepped through with documentation. More importantly, it’s a functional system that you can run and explore on your own." }, { "code": null, "e": 27016, "s": 26784, "text": "If you do pull the code, feel free to use it as you will. Build something cool or just dissect it and learn what you can. If you do tend to use something I’ve written, just give me a shout out. Otherwise, it’s my gift to the world." } ]
C++ Program for Range sum queries without updates - GeeksforGeeks
06 Dec, 2018 Given an array arr of integers of size n. We need to compute sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times. Examples: Input : arr[] = {1, 2, 3, 4, 5} i = 1, j = 3 i = 2, j = 4 Output : 9 12 Input : arr[] = {1, 2, 3, 4, 5} i = 0, j = 4 i = 1, j = 2 Output : 15 5 // CPP program to find sum between two indexes// when there is no update.#include <bits/stdc++.h>using namespace std; void preCompute(int arr[], int n, int pre[]){ pre[0] = arr[0]; for (int i = 1; i < n; i++) pre[i] = arr[i] + pre[i - 1];} // Returns sum of elements in arr[i..j]// It is assumed that i <= jint rangeSum(int i, int j, int pre[]){ if (i == 0) return pre[j]; return pre[j] - pre[i - 1];} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int pre[n]; preCompute(arr, n, pre); cout << rangeSum(1, 3, pre) << endl; cout << rangeSum(2, 4, pre) << endl; return 0;} 9 12 Please refer complete article on Range sum queries without updates for more details! C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class cout in C++ Pi(π) in C++ with Examples Const keyword in C++ Handling the Divide by Zero Exception in C++ Why it is important to write "using namespace std" in C++ program? isdigit() function in C/C++ with Examples Dynamic _Cast in C++ Setting up Sublime Text for C++ Competitive Programming Environment
[ { "code": null, "e": 24137, "s": 24109, "text": "\n06 Dec, 2018" }, { "code": null, "e": 24319, "s": 24137, "text": "Given an array arr of integers of size n. We need to compute sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times." }, { "code": null, "e": 24329, "s": 24319, "text": "Examples:" }, { "code": null, "e": 24538, "s": 24329, "text": "Input : arr[] = {1, 2, 3, 4, 5}\n i = 1, j = 3\n i = 2, j = 4\nOutput : 9\n 12 \n\nInput : arr[] = {1, 2, 3, 4, 5}\n i = 0, j = 4 \n i = 1, j = 2 \nOutput : 15\n 5\n" }, { "code": "// CPP program to find sum between two indexes// when there is no update.#include <bits/stdc++.h>using namespace std; void preCompute(int arr[], int n, int pre[]){ pre[0] = arr[0]; for (int i = 1; i < n; i++) pre[i] = arr[i] + pre[i - 1];} // Returns sum of elements in arr[i..j]// It is assumed that i <= jint rangeSum(int i, int j, int pre[]){ if (i == 0) return pre[j]; return pre[j] - pre[i - 1];} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int pre[n]; preCompute(arr, n, pre); cout << rangeSum(1, 3, pre) << endl; cout << rangeSum(2, 4, pre) << endl; return 0;}", "e": 25213, "s": 24538, "text": null }, { "code": null, "e": 25219, "s": 25213, "text": "9\n12\n" }, { "code": null, "e": 25304, "s": 25219, "text": "Please refer complete article on Range sum queries without updates for more details!" }, { "code": null, "e": 25317, "s": 25304, "text": "C++ Programs" }, { "code": null, "e": 25415, "s": 25317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25424, "s": 25415, "text": "Comments" }, { "code": null, "e": 25437, "s": 25424, "text": "Old Comments" }, { "code": null, "e": 25478, "s": 25437, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 25537, "s": 25478, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 25549, "s": 25537, "text": "cout in C++" }, { "code": null, "e": 25576, "s": 25549, "text": "Pi(π) in C++ with Examples" }, { "code": null, "e": 25597, "s": 25576, "text": "Const keyword in C++" }, { "code": null, "e": 25642, "s": 25597, "text": "Handling the Divide by Zero Exception in C++" }, { "code": null, "e": 25709, "s": 25642, "text": "Why it is important to write \"using namespace std\" in C++ program?" }, { "code": null, "e": 25751, "s": 25709, "text": "isdigit() function in C/C++ with Examples" }, { "code": null, "e": 25772, "s": 25751, "text": "Dynamic _Cast in C++" } ]
How to Search Data with KDTree. Given a Task to Find Data in a Certain... | by Khuyen Tran | Towards Data Science
Imagine you keep a record of the number of travelers in your region every day. You are asked to give a report on the number of travelers from February 2nd to March 2nd. Assuming this data is sorted, how could you find the data within this range in a short amount of time? This is a statement of a range search problem. This seems like an easy problem. Can we just go through every data from left to right? Yes, but this will take a huge amount of time if we have significant big data, not taking into account that our data could be in k dimensions. This problem could be generalized to 2 dimensions like a 2D map. Instead of searching for every centimeter in this space, we could divide this space into a regular grid MxM. Then determine the cells that fall entirely in the range and those that intersect the range. We will include all the data from the cells that fall entirely within the range and check individual data for all not-fully included cells. The great thing about this method is that we can quickly eliminate the data that is not in the range and narrow down our search. But what if our data is non-uniform, which means there are clusters of data in some regions and few data in other regions? If we choose too few grids (M small), we will have many data points in one cell. The performance will get close to one of the sequential search. If we alternatively choose many grids (M large), we could end up with too many empty cells and waste of space. Since in real life, we often need to deal with non-uniform data like a map, we need a better approach. When dealing with clustered data like above, using regular grids will lead to poor behavior. That is why it is ideal to keep this idea of pre-segmenting the data, but segmenting based on the data density! A small secret that you may not know: The data structure I will introduce is the implementation that creates the robustness to KNearest Neighbor from sklearn instead of the well-know KNearest Neighbor algorithm’s implementation. Before thinking about k dimensions, let’s start with 2 dimensions. We are given the data points like this Instead of splitting the data into grids with equal width, we will split the data at the median value at an axis (x or y). We could start by splitting at the median values along the y-axis to divide the plane into half. Then in each half of the plane, continue dividing the sub-division into two equal sub-division by choosing the vertical lines passing through the median value in each sub-division. We repeat this recursively the same procedure in the two regions until there is no more point (or the number of points we decide) in the corresponding partition element. With this method, we would be able to partition the data based on its density! So what is the underlying data structure of this method? It is very similar to a binary search tree, but not exactly. Since the data is first split on the y-axis, y is the root node. The children are x because each half-plane is split on the x-axis. The left subtree nodes will have all the x-values inferior to the one of the root. The right subtree nodes will have all their x-values superior to the one of the root. Alternate between two axes until we reach the limit. Sounds good so far. But how can we use this data structure to search for data in a particular range? The good news is that it becomes much simpler to find data once we have created a 2-d tree. We visit the tree nodes starting from the tree root: If the node is inside the queried range, add it to the answer If the queried range intersects the zone defined by the left-subtree, explore it If the queried range intersects the zone defined by the left-subtree, explore it Let’s say we have a dataset for locations of ECOBICI’s stations (Mexico’s City bike public sharing system). Our task is to find the data in a certain range. As we can see, there are denser clusters of stations in some regions than others. To see how the data above could be split using Kdtree, clone this repo git clone https://github.com/khuyentran1401/kdtree-implementation Then cd to kdtree-implementation directory in your local machine and run python ecobi.py You should see the kd-tree representation of the data above. The regions with more lines indicate the denser clusters in that region. To find a range in a particular region, run python findrange.py You should see the prompt to enter the range. Let’s say if you choose the range between -1 and 1 on the x-axis and -1 to 1 on the y-axis you should see the coordinates of data in that range. Awesome! With KdTree, you could find the data in a particular range in a matter of seconds. Even though we do not cover how to search for the nearest point with KdTree, KdTree can also be used for Sklearn’s KNearestNeighbor efficiently. Congratulation! You have learned what KdTree is and its applications. To learn more about how to implement it and use it for your data, check out my Github repo. I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 490, "s": 171, "text": "Imagine you keep a record of the number of travelers in your region every day. You are asked to give a report on the number of travelers from February 2nd to March 2nd. Assuming this data is sorted, how could you find the data within this range in a short amount of time? This is a statement of a range search problem." }, { "code": null, "e": 720, "s": 490, "text": "This seems like an easy problem. Can we just go through every data from left to right? Yes, but this will take a huge amount of time if we have significant big data, not taking into account that our data could be in k dimensions." }, { "code": null, "e": 785, "s": 720, "text": "This problem could be generalized to 2 dimensions like a 2D map." }, { "code": null, "e": 987, "s": 785, "text": "Instead of searching for every centimeter in this space, we could divide this space into a regular grid MxM. Then determine the cells that fall entirely in the range and those that intersect the range." }, { "code": null, "e": 1256, "s": 987, "text": "We will include all the data from the cells that fall entirely within the range and check individual data for all not-fully included cells. The great thing about this method is that we can quickly eliminate the data that is not in the range and narrow down our search." }, { "code": null, "e": 1379, "s": 1256, "text": "But what if our data is non-uniform, which means there are clusters of data in some regions and few data in other regions?" }, { "code": null, "e": 1524, "s": 1379, "text": "If we choose too few grids (M small), we will have many data points in one cell. The performance will get close to one of the sequential search." }, { "code": null, "e": 1635, "s": 1524, "text": "If we alternatively choose many grids (M large), we could end up with too many empty cells and waste of space." }, { "code": null, "e": 1738, "s": 1635, "text": "Since in real life, we often need to deal with non-uniform data like a map, we need a better approach." }, { "code": null, "e": 1943, "s": 1738, "text": "When dealing with clustered data like above, using regular grids will lead to poor behavior. That is why it is ideal to keep this idea of pre-segmenting the data, but segmenting based on the data density!" }, { "code": null, "e": 2172, "s": 1943, "text": "A small secret that you may not know: The data structure I will introduce is the implementation that creates the robustness to KNearest Neighbor from sklearn instead of the well-know KNearest Neighbor algorithm’s implementation." }, { "code": null, "e": 2278, "s": 2172, "text": "Before thinking about k dimensions, let’s start with 2 dimensions. We are given the data points like this" }, { "code": null, "e": 2498, "s": 2278, "text": "Instead of splitting the data into grids with equal width, we will split the data at the median value at an axis (x or y). We could start by splitting at the median values along the y-axis to divide the plane into half." }, { "code": null, "e": 2679, "s": 2498, "text": "Then in each half of the plane, continue dividing the sub-division into two equal sub-division by choosing the vertical lines passing through the median value in each sub-division." }, { "code": null, "e": 2849, "s": 2679, "text": "We repeat this recursively the same procedure in the two regions until there is no more point (or the number of points we decide) in the corresponding partition element." }, { "code": null, "e": 2985, "s": 2849, "text": "With this method, we would be able to partition the data based on its density! So what is the underlying data structure of this method?" }, { "code": null, "e": 3046, "s": 2985, "text": "It is very similar to a binary search tree, but not exactly." }, { "code": null, "e": 3111, "s": 3046, "text": "Since the data is first split on the y-axis, y is the root node." }, { "code": null, "e": 3178, "s": 3111, "text": "The children are x because each half-plane is split on the x-axis." }, { "code": null, "e": 3261, "s": 3178, "text": "The left subtree nodes will have all the x-values inferior to the one of the root." }, { "code": null, "e": 3347, "s": 3261, "text": "The right subtree nodes will have all their x-values superior to the one of the root." }, { "code": null, "e": 3400, "s": 3347, "text": "Alternate between two axes until we reach the limit." }, { "code": null, "e": 3501, "s": 3400, "text": "Sounds good so far. But how can we use this data structure to search for data in a particular range?" }, { "code": null, "e": 3593, "s": 3501, "text": "The good news is that it becomes much simpler to find data once we have created a 2-d tree." }, { "code": null, "e": 3646, "s": 3593, "text": "We visit the tree nodes starting from the tree root:" }, { "code": null, "e": 3708, "s": 3646, "text": "If the node is inside the queried range, add it to the answer" }, { "code": null, "e": 3789, "s": 3708, "text": "If the queried range intersects the zone defined by the left-subtree, explore it" }, { "code": null, "e": 3870, "s": 3789, "text": "If the queried range intersects the zone defined by the left-subtree, explore it" }, { "code": null, "e": 4109, "s": 3870, "text": "Let’s say we have a dataset for locations of ECOBICI’s stations (Mexico’s City bike public sharing system). Our task is to find the data in a certain range. As we can see, there are denser clusters of stations in some regions than others." }, { "code": null, "e": 4180, "s": 4109, "text": "To see how the data above could be split using Kdtree, clone this repo" }, { "code": null, "e": 4246, "s": 4180, "text": "git clone https://github.com/khuyentran1401/kdtree-implementation" }, { "code": null, "e": 4319, "s": 4246, "text": "Then cd to kdtree-implementation directory in your local machine and run" }, { "code": null, "e": 4335, "s": 4319, "text": "python ecobi.py" }, { "code": null, "e": 4469, "s": 4335, "text": "You should see the kd-tree representation of the data above. The regions with more lines indicate the denser clusters in that region." }, { "code": null, "e": 4513, "s": 4469, "text": "To find a range in a particular region, run" }, { "code": null, "e": 4533, "s": 4513, "text": "python findrange.py" }, { "code": null, "e": 4724, "s": 4533, "text": "You should see the prompt to enter the range. Let’s say if you choose the range between -1 and 1 on the x-axis and -1 to 1 on the y-axis you should see the coordinates of data in that range." }, { "code": null, "e": 4961, "s": 4724, "text": "Awesome! With KdTree, you could find the data in a particular range in a matter of seconds. Even though we do not cover how to search for the nearest point with KdTree, KdTree can also be used for Sklearn’s KNearestNeighbor efficiently." }, { "code": null, "e": 5123, "s": 4961, "text": "Congratulation! You have learned what KdTree is and its applications. To learn more about how to implement it and use it for your data, check out my Github repo." }, { "code": null, "e": 5283, "s": 5123, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
Find a range of composite numbers of given length - GeeksforGeeks
27 Jan, 2022 Given an integer n, we need to find a range of positive integers such that all the number in that range are composite and length of that range is n. You may print anyone range in the case of more than one answer. A composite number is a positive integer that has at least one divisor other than 1 and itself (Source : wiki ) Examples : Input : 3 Output : [122, 124] Explanation 122, 123, 124 are all composite numbers The solution is little tricky. Since there are many possible answers, we discuss a generalized solution here. Let the length of range be n and range starts from a then, a, a+1, a+2, ...., a+n-1 all should be composite. So the problem boils down to finding such 'a'. If we closely observe p! (where p is a positive integers) then we will find that, p! has factors of 2, 3, 4, ..., p-1, Hence if we add i to p! such that 1 < i < p, then p! + i has a factor i, so p! + i must be composite. So we end up finding p! + 2, p! + 3, .... p! + p-1 are all composite and continuous integers forming a range [p! + 2, p! + p-1] The above range consists of p-2 elements. For a range of n elements we need to consider (n+2)! If we take a = (n+2)! + 2, Then, a + 1 = (n+2)! + 3 Then, a + 2 = (n+2)! + 4 ... Then, a + n-1 = (n+2)! + n+1 Hence, a = (n+2)! + 2 = 2*3*....*(n+2) + 2 a has 2 as its divisor because (n+2)! and 2 both divides 2 a + 1 = 2*3*....*(n+2) + 3 a + 1 has 3 as its divisor because (n+2)! and 3 both divides 3 ... a + n-1 = 2*3*....*(n+2) + n+1 a + n-1 has n+1 as its divisor because (n+2)! and n+1 both divides n+1 Therefore range will be [ (n+2)! + 2, ( (n+2)! + 2 ) + n-1] Example for above algorithm n = 3 Then a = (n+2)! + 2 a = 5! + 2 a + 1 = 5! + 3 a + 2 = 5! + 4 Here a is divisible by 2 Here a + 1 is divisible by 3 Here a + 2 is divisible by 4 Hence a, a+1, a+2 are all composites C++ Java Python3 C# PHP Javascript // C++ program to find a range of// composite numbers of given length#include <bits/stdc++.h>using namespace std; // method to find factorial// of given numberint factorial (int n){ if (n == 0) return 1; return n * factorial(n-1);} // to print range of length n// having all composite integersint printRange(int n){int a = factorial(n + 2) + 2;int b = a + n - 1;cout << "[" << a << ", " << b << "]";return 0;} // Driver methodint main(){ int n = 3 ; printRange(n); return 0;} // This code is contributed by Anshika Goyal // Java program to find a range of composite// numbers of given length class Test{ // method to find factorial of given number static int factorial(int n) { if (n == 0) return 1; return n*factorial(n-1); } // to print range of length n // having all composite integers static void printRange(int n) { int a = factorial(n + 2) + 2; int b = a + n - 1; System.out.println("[" + a + ", " + b + "]"); } // Driver method public static void main(String args[]) throws Exception { int n = 3 ; printRange(n); }} # Python program to find a range of composite# numbers of given length # function to calculate factorialdef factorial(n): a = 1 for i in range(2, n + 1): a *= i return a # to print range of length n# having all composite integersdef printRange(n): a = factorial(n + 2) + 2 b = a + n - 1 print("["+str(a)+", "+str(b)+"]") # driver code to test above functionsn = 3printRange(n) // C# program to find a range of// composite numbers of given// lengthusing System; class GFG { // method to find factorial // of given number static int factorial(int n) { if (n == 0) return 1; return n*factorial(n-1); } // to print range of length n // having all composite integers static void printRange(int n) { int a = factorial(n + 2) + 2; int b = a + n - 1; Console.WriteLine("[" + a + ", " + b + "]"); } // Driver method public static void Main() { int n = 3 ; printRange(n); }} // This code is contributed by anuj_67. <?php// PHP program to find a range of// composite numbers of given length // method to find factorial// of given numberfunction factorial ( $n){ if ($n == 0) return 1; return $n * factorial($n - 1);} // to print range of length n// having all composite integersfunction printRange($n){$a = factorial($n + 2) + 2;$b = $a + $n - 1;echo "[" , $a , ", " , $b , "]";return 0;} // Driver Code$n = 3 ;printRange($n); // This code is contributed by anuj_67.?> <script> // Javascript program to find a range of// composite numbers of given length // Method to find factorial// of given numberfunction factorial(n){ if (n == 0) return 1; return n * factorial(n - 1);} // To print range of length n// having all composite integersfunction printRange(n){ let a = factorial(n + 2) + 2; let b = a + n - 1; document.write(`[${a}, ${b}]`); return 0;} // Driver Codelet n = 3; printRange(n); // This code is contributed by _saurabh_jaiswal. </script> Output : [122, 124] Analysis of above algorithm Time Complexity : O(n) Auxiliary Space : O(1) This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m _saurabh_jaiswal surinderdawra388 amartyaghoshgfg factorial Prime Number Mathematical Mathematical Prime Number factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Modulo Operator (%) in C/C++ with Examples Program to find GCD or HCF of two numbers Merge two sorted arrays Prime Numbers Program to find sum of elements in a given array Operators in C / C++ Program for factorial of a number Sieve of Eratosthenes Program for Decimal to Binary Conversion Algorithm to solve Rubik's Cube
[ { "code": null, "e": 25206, "s": 25178, "text": "\n27 Jan, 2022" }, { "code": null, "e": 25532, "s": 25206, "text": "Given an integer n, we need to find a range of positive integers such that all the number in that range are composite and length of that range is n. You may print anyone range in the case of more than one answer. A composite number is a positive integer that has at least one divisor other than 1 and itself (Source : wiki ) " }, { "code": null, "e": 25544, "s": 25532, "text": "Examples : " }, { "code": null, "e": 25626, "s": 25544, "text": "Input : 3\nOutput : [122, 124]\nExplanation 122, 123, 124 are all composite numbers" }, { "code": null, "e": 25738, "s": 25626, "text": "The solution is little tricky. Since there are many possible answers, we discuss a generalized solution here. " }, { "code": null, "e": 26819, "s": 25738, "text": "Let the length of range be n and range starts \nfrom a then, a, a+1, a+2, ...., a+n-1 all should \nbe composite. So the problem boils down to finding\nsuch 'a'.\n\nIf we closely observe p! (where p is a positive \nintegers) then we will find that, p! has factors of\n2, 3, 4, ..., p-1,\nHence if we add i to p! such that 1 < i < p,\nthen p! + i has a factor i, so p! + i must be \ncomposite. So we end up finding p! + 2, p! + 3,\n .... p! + p-1 are all composite and continuous \nintegers forming a range [p! + 2, p! + p-1]\nThe above range consists of p-2 elements.\nFor a range of n elements we need to consider (n+2)!\n\nIf we take a = (n+2)! + 2, \nThen, a + 1 = (n+2)! + 3\nThen, a + 2 = (n+2)! + 4\n...\nThen, a + n-1 = (n+2)! + n+1\nHence,\na = (n+2)! + 2 = 2*3*....*(n+2) + 2\na has 2 as its divisor because (n+2)! and 2 \nboth divides 2\na + 1 = 2*3*....*(n+2) + 3\na + 1 has 3 as its divisor because (n+2)! \nand 3 both divides 3\n...\na + n-1 = 2*3*....*(n+2) + n+1\na + n-1 has n+1 as its divisor because (n+2)! \nand n+1 both divides n+1\n\nTherefore range will be [ (n+2)! + 2, ( (n+2)! + 2 ) + n-1]" }, { "code": null, "e": 26848, "s": 26819, "text": "Example for above algorithm " }, { "code": null, "e": 27035, "s": 26848, "text": "n = 3\nThen a = (n+2)! + 2\na = 5! + 2\na + 1 = 5! + 3\na + 2 = 5! + 4\nHere a is divisible by 2\nHere a + 1 is divisible by 3\nHere a + 2 is divisible by 4\nHence a, a+1, a+2 are all composites" }, { "code": null, "e": 27039, "s": 27035, "text": "C++" }, { "code": null, "e": 27044, "s": 27039, "text": "Java" }, { "code": null, "e": 27052, "s": 27044, "text": "Python3" }, { "code": null, "e": 27055, "s": 27052, "text": "C#" }, { "code": null, "e": 27059, "s": 27055, "text": "PHP" }, { "code": null, "e": 27070, "s": 27059, "text": "Javascript" }, { "code": "// C++ program to find a range of// composite numbers of given length#include <bits/stdc++.h>using namespace std; // method to find factorial// of given numberint factorial (int n){ if (n == 0) return 1; return n * factorial(n-1);} // to print range of length n// having all composite integersint printRange(int n){int a = factorial(n + 2) + 2;int b = a + n - 1;cout << \"[\" << a << \", \" << b << \"]\";return 0;} // Driver methodint main(){ int n = 3 ; printRange(n); return 0;} // This code is contributed by Anshika Goyal", "e": 27614, "s": 27070, "text": null }, { "code": "// Java program to find a range of composite// numbers of given length class Test{ // method to find factorial of given number static int factorial(int n) { if (n == 0) return 1; return n*factorial(n-1); } // to print range of length n // having all composite integers static void printRange(int n) { int a = factorial(n + 2) + 2; int b = a + n - 1; System.out.println(\"[\" + a + \", \" + b + \"]\"); } // Driver method public static void main(String args[]) throws Exception { int n = 3 ; printRange(n); }}", "e": 28234, "s": 27614, "text": null }, { "code": "# Python program to find a range of composite# numbers of given length # function to calculate factorialdef factorial(n): a = 1 for i in range(2, n + 1): a *= i return a # to print range of length n# having all composite integersdef printRange(n): a = factorial(n + 2) + 2 b = a + n - 1 print(\"[\"+str(a)+\", \"+str(b)+\"]\") # driver code to test above functionsn = 3printRange(n)", "e": 28636, "s": 28234, "text": null }, { "code": "// C# program to find a range of// composite numbers of given// lengthusing System; class GFG { // method to find factorial // of given number static int factorial(int n) { if (n == 0) return 1; return n*factorial(n-1); } // to print range of length n // having all composite integers static void printRange(int n) { int a = factorial(n + 2) + 2; int b = a + n - 1; Console.WriteLine(\"[\" + a + \", \" + b + \"]\"); } // Driver method public static void Main() { int n = 3 ; printRange(n); }} // This code is contributed by anuj_67.", "e": 29292, "s": 28636, "text": null }, { "code": "<?php// PHP program to find a range of// composite numbers of given length // method to find factorial// of given numberfunction factorial ( $n){ if ($n == 0) return 1; return $n * factorial($n - 1);} // to print range of length n// having all composite integersfunction printRange($n){$a = factorial($n + 2) + 2;$b = $a + $n - 1;echo \"[\" , $a , \", \" , $b , \"]\";return 0;} // Driver Code$n = 3 ;printRange($n); // This code is contributed by anuj_67.?>", "e": 29759, "s": 29292, "text": null }, { "code": "<script> // Javascript program to find a range of// composite numbers of given length // Method to find factorial// of given numberfunction factorial(n){ if (n == 0) return 1; return n * factorial(n - 1);} // To print range of length n// having all composite integersfunction printRange(n){ let a = factorial(n + 2) + 2; let b = a + n - 1; document.write(`[${a}, ${b}]`); return 0;} // Driver Codelet n = 3; printRange(n); // This code is contributed by _saurabh_jaiswal. </script>", "e": 30285, "s": 29759, "text": null }, { "code": null, "e": 30295, "s": 30285, "text": "Output : " }, { "code": null, "e": 30306, "s": 30295, "text": "[122, 124]" }, { "code": null, "e": 30380, "s": 30306, "text": "Analysis of above algorithm Time Complexity : O(n) Auxiliary Space : O(1)" }, { "code": null, "e": 30803, "s": 30380, "text": "This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30808, "s": 30803, "text": "vt_m" }, { "code": null, "e": 30825, "s": 30808, "text": "_saurabh_jaiswal" }, { "code": null, "e": 30842, "s": 30825, "text": "surinderdawra388" }, { "code": null, "e": 30858, "s": 30842, "text": "amartyaghoshgfg" }, { "code": null, "e": 30868, "s": 30858, "text": "factorial" }, { "code": null, "e": 30881, "s": 30868, "text": "Prime Number" }, { "code": null, "e": 30894, "s": 30881, "text": "Mathematical" }, { "code": null, "e": 30907, "s": 30894, "text": "Mathematical" }, { "code": null, "e": 30920, "s": 30907, "text": "Prime Number" }, { "code": null, "e": 30930, "s": 30920, "text": "factorial" }, { "code": null, "e": 31028, "s": 30930, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31037, "s": 31028, "text": "Comments" }, { "code": null, "e": 31050, "s": 31037, "text": "Old Comments" }, { "code": null, "e": 31093, "s": 31050, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31135, "s": 31093, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 31159, "s": 31135, "text": "Merge two sorted arrays" }, { "code": null, "e": 31173, "s": 31159, "text": "Prime Numbers" }, { "code": null, "e": 31222, "s": 31173, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31243, "s": 31222, "text": "Operators in C / C++" }, { "code": null, "e": 31277, "s": 31243, "text": "Program for factorial of a number" }, { "code": null, "e": 31299, "s": 31277, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 31340, "s": 31299, "text": "Program for Decimal to Binary Conversion" } ]
Check if frequency of all characters can become same by one removal - GeeksforGeeks
22 Nov, 2021 Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input: str = “xyyz” Output: Yes We can remove character ’y’ from above string to make the frequency of each character same. Input: str = “xyyzz” Output: Yes We can remove character ‘x’ from above string to make the frequency of each character same. Input: str = “xxxxyyzz” Output: No It is not possible to make frequency of each character same just by removing at most one character from above string. Approach: The problem can be solved using the concept of hashing. The main thing to observe in this problem is that the position of characters does not matter here so we will count the frequency of characters, if all of them are the same then we are done and there is no need to remove any character to make frequency of characters same Otherwise we can iterate over all characters one by one and decrease their frequency by one, if all frequencies become same then we will flag that it is possible to make character frequency same by at most one removal and if frequencies don’t match then we will increase that frequency again and loop for other characters. Below is a dry run of the above approach: Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to get same frequency character// string by removal of at most one char#include <bits/stdc++.h>using namespace std;#define M 26 // Utility method to get index of character ch// in lower alphabet charactersint getIdx(char ch){ return (ch - 'a');} // Returns true if all non-zero elements// values are samebool allSame(int freq[], int N){ int same; // get first non-zero element int i; for (i = 0; i < N; i++) { if (freq[i] > 0) { same = freq[i]; break; } } // check equality of each element with variable same for (int j = i + 1; j < N; j++) if (freq[j] > 0 && freq[j] != same) return false; return true;} // Returns true if we can make all character// frequencies samebool possibleSameCharFreqByOneRemoval(string str){ int l = str.length(); // fill frequency array int freq[M] = { 0 }; for (int i = 0; i < l; i++) freq[getIdx(str[i])]++; // if all frequencies are same, then return true if (allSame(freq, M)) return true; /* Try decreasing frequency of all character by one and then check all equality of all non-zero frequencies */ for (char c = 'a'; c <= 'z'; c++) { int i = getIdx(c); // Check character only if it occurs in str if (freq[i] > 0) { freq[i]--; if (allSame(freq, M)) return true; freq[i]++; } } return false;} // Driver code to test above methodsint main(){ string str = "xyyzz"; if (possibleSameCharFreqByOneRemoval(str)) cout << "Yes"; else cout << "No";} // Java program to get same frequency character// string by removal of at most one charpublic class GFG { static final int M = 26; // Utility method to get index of character ch // in lower alphabet characters static int getIdx(char ch) { return (ch - 'a'); } // Returns true if all non-zero elements // values are same static boolean allSame(int freq[], int N) { int same = 0; // get first non-zero element int i; for (i = 0; i < N; i++) { if (freq[i] > 0) { same = freq[i]; break; } } // check equality of each element with // variable same for (int j = i + 1; j < N; j++) if (freq[j] > 0 && freq[j] != same) return false; return true; } // Returns true if we can make all character // frequencies same static boolean possibleSameCharFreqByOneRemoval(String str) { int l = str.length(); // fill frequency array int[] freq = new int[M]; for (int i = 0; i < l; i++) freq[getIdx(str.charAt(i))]++; // if all frequencies are same, then return true if (allSame(freq, M)) return true; /* Try decreasing frequency of all character by one and then check all equality of all non-zero frequencies */ for (char c = 'a'; c <= 'z'; c++) { int i = getIdx(c); // Check character only if it occurs in str if (freq[i] > 0) { freq[i]--; if (allSame(freq, M)) return true; freq[i]++; } } return false; } // Driver code to test above methods public static void main(String args[]) { String str = "xyyzz"; if (possibleSameCharFreqByOneRemoval(str)) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by Sumit Ghosh # Python3 program to get same frequency character# string by removal of at most one charM = 26 # Utility method to get index of character ch# in lower alphabet charactersdef getIdx(ch): return (ord(ch) - ord('a')) # Returns true if all non-zero elements# values are samedef allSame(freq, N): # get first non-zero element for i in range(0, N): if(freq[i] > 0): same = freq[i] break # check equality of each element # with variable same for j in range(i + 1, N): if(freq[j] > 0 and freq[j] != same): return False return True # Returns true if we can make all# character frequencies samedef possibleSameCharFreqByOneRemoval(str1): l = len(str1) # fill frequency array freq = [0] * M for i in range(0, l): freq[getIdx(str1[i])] += 1 # if all frequencies are same, # then return true if(allSame(freq, M)): return True # Try decreasing frequency of all character # by one and then check all equality of all # non-zero frequencies for i in range(0, 26): # Check character only if it # occurs in str if(freq[i] > 0): freq[i] -= 1 if(allSame(freq, M)): return True freq[i] += 1 return False # Driver codeif __name__ == "__main__": str1 = "xyyzz" if(possibleSameCharFreqByOneRemoval(str1)): print("Yes") else: print("No") # This code is contributed by Sairahul099 // C# program to get same frequency// character string by removal of// at most one charusing System; class GFG { static int M = 26; // Utility method to get // index of character ch // in lower alphabet characters static int getIdx(char ch) { return (ch - 'a'); } // Returns true if all // non-zero elements // values are same static bool allSame(int[] freq, int N) { int same = 0; // get first non-zero element int i; for (i = 0; i < N; i++) { if (freq[i] > 0) { same = freq[i]; break; } } // check equality of // each element with // variable same for (int j = i + 1; j < N; j++) if (freq[j] > 0 && freq[j] != same) return false; return true; } // Returns true if we // can make all character // frequencies same static bool possibleSameCharFreqByOneRemoval(string str) { int l = str.Length; // fill frequency array int[] freq = new int[M]; for (int i = 0; i < l; i++) freq[getIdx(str[i])]++; // if all frequencies are same, // then return true if (allSame(freq, M)) return true; /* Try decreasing frequency of all character by one and then check all equality of all non-zero frequencies */ for (char c = 'a'; c <= 'z'; c++) { int i = getIdx(c); // Check character only if // it occurs in str if (freq[i] > 0) { freq[i]--; if (allSame(freq, M)) return true; freq[i]++; } } return false; } // Driver code public static void Main() { string str = "xyyzz"; if (possibleSameCharFreqByOneRemoval(str)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed// by ChitraNayal <?php// PHP program to get same frequency// character string by removal of at// most one char$M = 26; // Utility method to get index// of character ch in lower// alphabet charactersfunction getIdx($ch){ return ($ch - 'a');} // Returns true if all// non-zero elements// values are samefunction allSame(&$freq, $N){ // get first non-zero element for ($i = 0; $i < $N; $i++) { if ($freq[$i] > 0) { $same = $freq[$i]; break; } } // check equality of each // element with variable same for ($j = $i + 1; $j < $N; $j++) if ($freq[$j] > 0 && $freq[$j] != $same) return false; return true;} // Returns true if we// can make all character// frequencies samefunction possibleSameCharFreqByOneRemoval($str){ global $M; $l = strlen($str); // fill frequency array $freq = array_fill(0, $M, NULL); for ($i = 0; $i < $l; $i++) $freq[getIdx($str[$i])]++; // if all frequencies are same, // then return true if (allSame($freq, $M)) return true; /* Try decreasing frequency of all character by one and then check all equality of all non-zero frequencies */ for ($c = 'a'; $c <= 'z'; $c++) { $i = getIdx($c); // Check character only // if it occurs in str if ($freq[$i] > 0) { $freq[$i]--; if (allSame($freq, $M)) return true; $freq[$i]++; } } return false;} // Driver code$str = "xyyzz";if (possibleSameCharFreqByOneRemoval($str))echo "Yes";elseecho "No"; // This code is contributed// by ChitraNayal?> <script> // Javascript program to get same// frequency character string by// removal of at most one charlet M = 26; // Utility method to get index of character// ch in lower alphabet charactersfunction getIdx(ch){ return (ch - 'a');} // Returns true if all non-zero elements// values are samefunction allSame(freq, N){ let same = 0; // Get first non-zero element let i; for(i = 0; i < N; i++) { if (freq[i] > 0) { same = freq[i]; break; } } // Check equality of each element with // variable same for(let j = i + 1; j < N; j++) if (freq[j] > 0 && freq[j] != same) return false; return true;} // Returns true if we can make all character// frequencies samefunction possibleSameCharFreqByOneRemoval(str){ let l = str.length; // Fill frequency array let freq = new Array(M); for(let i = 0; i < M; i++) { freq[i] = 0; } for(let i = 0; i < l; i++) freq[getIdx(str[i])]++; // If all frequencies are same, // then return true if (allSame(freq, M)) return true; // Try decreasing frequency of all character // by one and then check all equality of all // non-zero frequencies for(let c = 'a'; c <= 'z'; c++) { let i = getIdx(c); // Check character only if // it occurs in str if (freq[i] > 0) { freq[i]--; if (allSame(freq, M)) return true; freq[i]++; } } return false;} // Driver codelet str = "xyyzz"; if (possibleSameCharFreqByOneRemoval(str)) document.write("Yes");else document.write("No"); // This code is contributed by avanitrachhadiya2155 </script> Output: Yes Time Complexity: O(n) assuming alphabet size is constant. Auxiliary Space: O(26) YouTubeGeeksforGeeks500K subscribersCheck if frequency of all characters can become same by one removal | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:19•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=unw9XO7vUYQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ukasp Sairahul Jella avanitrachhadiya2155 rohitkumarsinghcna Hash Strings Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Most frequent element in an array Counting frequencies of array elements Double Hashing Quadratic Probing in Hashing Implementing our Own Hash Table with Separate Chaining in Java Reverse a string in Java Write a program to reverse an array or string C++ Data Types Write a program to print all permutations of a given string Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 25310, "s": 25282, "text": "\n22 Nov, 2021" }, { "code": null, "e": 25510, "s": 25310, "text": "Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string." }, { "code": null, "e": 25522, "s": 25510, "text": "Examples: " }, { "code": null, "e": 25647, "s": 25522, "text": "Input: str = “xyyz” Output: Yes We can remove character ’y’ from above string to make the frequency of each character same. " }, { "code": null, "e": 25772, "s": 25647, "text": "Input: str = “xyyzz” Output: Yes We can remove character ‘x’ from above string to make the frequency of each character same." }, { "code": null, "e": 25925, "s": 25772, "text": "Input: str = “xxxxyyzz” Output: No It is not possible to make frequency of each character same just by removing at most one character from above string." }, { "code": null, "e": 26586, "s": 25925, "text": "Approach: The problem can be solved using the concept of hashing. The main thing to observe in this problem is that the position of characters does not matter here so we will count the frequency of characters, if all of them are the same then we are done and there is no need to remove any character to make frequency of characters same Otherwise we can iterate over all characters one by one and decrease their frequency by one, if all frequencies become same then we will flag that it is possible to make character frequency same by at most one removal and if frequencies don’t match then we will increase that frequency again and loop for other characters. " }, { "code": null, "e": 26629, "s": 26586, "text": "Below is a dry run of the above approach: " }, { "code": null, "e": 26680, "s": 26629, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26684, "s": 26680, "text": "C++" }, { "code": null, "e": 26689, "s": 26684, "text": "Java" }, { "code": null, "e": 26697, "s": 26689, "text": "Python3" }, { "code": null, "e": 26700, "s": 26697, "text": "C#" }, { "code": null, "e": 26704, "s": 26700, "text": "PHP" }, { "code": null, "e": 26715, "s": 26704, "text": "Javascript" }, { "code": "// C++ program to get same frequency character// string by removal of at most one char#include <bits/stdc++.h>using namespace std;#define M 26 // Utility method to get index of character ch// in lower alphabet charactersint getIdx(char ch){ return (ch - 'a');} // Returns true if all non-zero elements// values are samebool allSame(int freq[], int N){ int same; // get first non-zero element int i; for (i = 0; i < N; i++) { if (freq[i] > 0) { same = freq[i]; break; } } // check equality of each element with variable same for (int j = i + 1; j < N; j++) if (freq[j] > 0 && freq[j] != same) return false; return true;} // Returns true if we can make all character// frequencies samebool possibleSameCharFreqByOneRemoval(string str){ int l = str.length(); // fill frequency array int freq[M] = { 0 }; for (int i = 0; i < l; i++) freq[getIdx(str[i])]++; // if all frequencies are same, then return true if (allSame(freq, M)) return true; /* Try decreasing frequency of all character by one and then check all equality of all non-zero frequencies */ for (char c = 'a'; c <= 'z'; c++) { int i = getIdx(c); // Check character only if it occurs in str if (freq[i] > 0) { freq[i]--; if (allSame(freq, M)) return true; freq[i]++; } } return false;} // Driver code to test above methodsint main(){ string str = \"xyyzz\"; if (possibleSameCharFreqByOneRemoval(str)) cout << \"Yes\"; else cout << \"No\";}", "e": 28356, "s": 26715, "text": null }, { "code": "// Java program to get same frequency character// string by removal of at most one charpublic class GFG { static final int M = 26; // Utility method to get index of character ch // in lower alphabet characters static int getIdx(char ch) { return (ch - 'a'); } // Returns true if all non-zero elements // values are same static boolean allSame(int freq[], int N) { int same = 0; // get first non-zero element int i; for (i = 0; i < N; i++) { if (freq[i] > 0) { same = freq[i]; break; } } // check equality of each element with // variable same for (int j = i + 1; j < N; j++) if (freq[j] > 0 && freq[j] != same) return false; return true; } // Returns true if we can make all character // frequencies same static boolean possibleSameCharFreqByOneRemoval(String str) { int l = str.length(); // fill frequency array int[] freq = new int[M]; for (int i = 0; i < l; i++) freq[getIdx(str.charAt(i))]++; // if all frequencies are same, then return true if (allSame(freq, M)) return true; /* Try decreasing frequency of all character by one and then check all equality of all non-zero frequencies */ for (char c = 'a'; c <= 'z'; c++) { int i = getIdx(c); // Check character only if it occurs in str if (freq[i] > 0) { freq[i]--; if (allSame(freq, M)) return true; freq[i]++; } } return false; } // Driver code to test above methods public static void main(String args[]) { String str = \"xyyzz\"; if (possibleSameCharFreqByOneRemoval(str)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}// This code is contributed by Sumit Ghosh", "e": 30378, "s": 28356, "text": null }, { "code": "# Python3 program to get same frequency character# string by removal of at most one charM = 26 # Utility method to get index of character ch# in lower alphabet charactersdef getIdx(ch): return (ord(ch) - ord('a')) # Returns true if all non-zero elements# values are samedef allSame(freq, N): # get first non-zero element for i in range(0, N): if(freq[i] > 0): same = freq[i] break # check equality of each element # with variable same for j in range(i + 1, N): if(freq[j] > 0 and freq[j] != same): return False return True # Returns true if we can make all# character frequencies samedef possibleSameCharFreqByOneRemoval(str1): l = len(str1) # fill frequency array freq = [0] * M for i in range(0, l): freq[getIdx(str1[i])] += 1 # if all frequencies are same, # then return true if(allSame(freq, M)): return True # Try decreasing frequency of all character # by one and then check all equality of all # non-zero frequencies for i in range(0, 26): # Check character only if it # occurs in str if(freq[i] > 0): freq[i] -= 1 if(allSame(freq, M)): return True freq[i] += 1 return False # Driver codeif __name__ == \"__main__\": str1 = \"xyyzz\" if(possibleSameCharFreqByOneRemoval(str1)): print(\"Yes\") else: print(\"No\") # This code is contributed by Sairahul099", "e": 31887, "s": 30378, "text": null }, { "code": "// C# program to get same frequency// character string by removal of// at most one charusing System; class GFG { static int M = 26; // Utility method to get // index of character ch // in lower alphabet characters static int getIdx(char ch) { return (ch - 'a'); } // Returns true if all // non-zero elements // values are same static bool allSame(int[] freq, int N) { int same = 0; // get first non-zero element int i; for (i = 0; i < N; i++) { if (freq[i] > 0) { same = freq[i]; break; } } // check equality of // each element with // variable same for (int j = i + 1; j < N; j++) if (freq[j] > 0 && freq[j] != same) return false; return true; } // Returns true if we // can make all character // frequencies same static bool possibleSameCharFreqByOneRemoval(string str) { int l = str.Length; // fill frequency array int[] freq = new int[M]; for (int i = 0; i < l; i++) freq[getIdx(str[i])]++; // if all frequencies are same, // then return true if (allSame(freq, M)) return true; /* Try decreasing frequency of all character by one and then check all equality of all non-zero frequencies */ for (char c = 'a'; c <= 'z'; c++) { int i = getIdx(c); // Check character only if // it occurs in str if (freq[i] > 0) { freq[i]--; if (allSame(freq, M)) return true; freq[i]++; } } return false; } // Driver code public static void Main() { string str = \"xyyzz\"; if (possibleSameCharFreqByOneRemoval(str)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed// by ChitraNayal", "e": 33937, "s": 31887, "text": null }, { "code": "<?php// PHP program to get same frequency// character string by removal of at// most one char$M = 26; // Utility method to get index// of character ch in lower// alphabet charactersfunction getIdx($ch){ return ($ch - 'a');} // Returns true if all// non-zero elements// values are samefunction allSame(&$freq, $N){ // get first non-zero element for ($i = 0; $i < $N; $i++) { if ($freq[$i] > 0) { $same = $freq[$i]; break; } } // check equality of each // element with variable same for ($j = $i + 1; $j < $N; $j++) if ($freq[$j] > 0 && $freq[$j] != $same) return false; return true;} // Returns true if we// can make all character// frequencies samefunction possibleSameCharFreqByOneRemoval($str){ global $M; $l = strlen($str); // fill frequency array $freq = array_fill(0, $M, NULL); for ($i = 0; $i < $l; $i++) $freq[getIdx($str[$i])]++; // if all frequencies are same, // then return true if (allSame($freq, $M)) return true; /* Try decreasing frequency of all character by one and then check all equality of all non-zero frequencies */ for ($c = 'a'; $c <= 'z'; $c++) { $i = getIdx($c); // Check character only // if it occurs in str if ($freq[$i] > 0) { $freq[$i]--; if (allSame($freq, $M)) return true; $freq[$i]++; } } return false;} // Driver code$str = \"xyyzz\";if (possibleSameCharFreqByOneRemoval($str))echo \"Yes\";elseecho \"No\"; // This code is contributed// by ChitraNayal?>", "e": 35593, "s": 33937, "text": null }, { "code": "<script> // Javascript program to get same// frequency character string by// removal of at most one charlet M = 26; // Utility method to get index of character// ch in lower alphabet charactersfunction getIdx(ch){ return (ch - 'a');} // Returns true if all non-zero elements// values are samefunction allSame(freq, N){ let same = 0; // Get first non-zero element let i; for(i = 0; i < N; i++) { if (freq[i] > 0) { same = freq[i]; break; } } // Check equality of each element with // variable same for(let j = i + 1; j < N; j++) if (freq[j] > 0 && freq[j] != same) return false; return true;} // Returns true if we can make all character// frequencies samefunction possibleSameCharFreqByOneRemoval(str){ let l = str.length; // Fill frequency array let freq = new Array(M); for(let i = 0; i < M; i++) { freq[i] = 0; } for(let i = 0; i < l; i++) freq[getIdx(str[i])]++; // If all frequencies are same, // then return true if (allSame(freq, M)) return true; // Try decreasing frequency of all character // by one and then check all equality of all // non-zero frequencies for(let c = 'a'; c <= 'z'; c++) { let i = getIdx(c); // Check character only if // it occurs in str if (freq[i] > 0) { freq[i]--; if (allSame(freq, M)) return true; freq[i]++; } } return false;} // Driver codelet str = \"xyyzz\"; if (possibleSameCharFreqByOneRemoval(str)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by avanitrachhadiya2155 </script>", "e": 37332, "s": 35593, "text": null }, { "code": null, "e": 37341, "s": 37332, "text": "Output: " }, { "code": null, "e": 37345, "s": 37341, "text": "Yes" }, { "code": null, "e": 37404, "s": 37345, "text": "Time Complexity: O(n) assuming alphabet size is constant. " }, { "code": null, "e": 37428, "s": 37404, "text": "Auxiliary Space: O(26) " }, { "code": null, "e": 38294, "s": 37428, "text": "YouTubeGeeksforGeeks500K subscribersCheck if frequency of all characters can become same by one removal | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:19•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=unw9XO7vUYQ\" 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": 38718, "s": 38294, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 38724, "s": 38718, "text": "ukasp" }, { "code": null, "e": 38739, "s": 38724, "text": "Sairahul Jella" }, { "code": null, "e": 38760, "s": 38739, "text": "avanitrachhadiya2155" }, { "code": null, "e": 38779, "s": 38760, "text": "rohitkumarsinghcna" }, { "code": null, "e": 38784, "s": 38779, "text": "Hash" }, { "code": null, "e": 38792, "s": 38784, "text": "Strings" }, { "code": null, "e": 38797, "s": 38792, "text": "Hash" }, { "code": null, "e": 38805, "s": 38797, "text": "Strings" }, { "code": null, "e": 38903, "s": 38805, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38912, "s": 38903, "text": "Comments" }, { "code": null, "e": 38925, "s": 38912, "text": "Old Comments" }, { "code": null, "e": 38959, "s": 38925, "text": "Most frequent element in an array" }, { "code": null, "e": 38998, "s": 38959, "text": "Counting frequencies of array elements" }, { "code": null, "e": 39013, "s": 38998, "text": "Double Hashing" }, { "code": null, "e": 39042, "s": 39013, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 39105, "s": 39042, "text": "Implementing our Own Hash Table with Separate Chaining in Java" }, { "code": null, "e": 39130, "s": 39105, "text": "Reverse a string in Java" }, { "code": null, "e": 39176, "s": 39130, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 39191, "s": 39176, "text": "C++ Data Types" }, { "code": null, "e": 39251, "s": 39191, "text": "Write a program to print all permutations of a given string" } ]
Chocolate Distribution Problem | Set 2 - GeeksforGeeks
14 Dec, 2021 Given an array A[] consisting of N integers, where each value represents the marks of the ith student, the task is to find the minimum number of chocolates required to be distributed such that: Each student should be awarded with at least one chocolate A student with higher marks should be awarded more chocolates than his adjacent students. Examples: Input: A[] = {10, 30, 20}Output: 4Explanation : Since, 30 is larger than its adjacent, so the second student must get more chocolates. Therefore, the minimum chocolates can be distributed as {1, 2, 1} = 1 + 2 + 1 = 4 Input: A[] = {23, 14, 15, 14, 56, 29, 14}Output: 12 Method 1: Approach: The problem can be solved using Greedy approach. Follow the steps below to solve the problem: Initialize array B[] of length N with 1. Traverse from left to right from i = 1 to N – 1, updating B[i] as B[i] = B[i-1]+1 if A[i] greater the A[i-1]. After completing the above step, traverse again from right to left from i = N – 2 to 0, updating B[i] as B[i] = max(B[i], B[i+1]+1) if A[i] is greater than A[i + 1]. Otherwise, update B[i] as B[i] = max(B[i], 1). After traversing, calculate the sum of the array B[] and print it as the minimum number of candies required. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <iostream>using namespace std; // FUnction to print minimum number// of candies requiredvoid minChocolates(int A[], int N){ int B[N]; // Distribute 1 chocolate to each for (int i = 0; i < N; i++) { B[i] = 1; } // Traverse from left to right for (int i = 1; i < N; i++) { if (A[i] > A[i - 1]) B[i] = B[i - 1] + 1; else B[i] = 1; } // Traverse from right to left for (int i = N - 2; i >= 0; i--) { if (A[i] > A[i + 1]) B[i] = max(B[i + 1] + 1, B[i]); else B[i] = max(B[i], 1); } // Initialize sum int sum = 0; // Find total sum for (int i = 0; i < N; i++) { sum += B[i]; } // Return sum cout << sum << "\n";} // Driver Codeint main(){ // Given array int A[] = { 23, 14, 15, 14, 56, 29, 14 }; // Size of the given array int N = sizeof(A) / sizeof(A[0]); minChocolates(A, N);} // Java program for the above approachimport java.util.*;class GFG { // FUnction to print minimum number // of candies required static void minChocolates(int A[], int N) { int[] B = new int[N]; // Distribute 1 chocolate to each for (int i = 0; i < N; i++) { B[i] = 1; } // Traverse from left to right for (int i = 1; i < N; i++) { if (A[i] > A[i - 1]) B[i] = B[i - 1] + 1; else B[i] = 1; } // Traverse from right to left for (int i = N - 2; i >= 0; i--) { if (A[i] > A[i + 1]) B[i] = Math.max(B[i + 1] + 1, B[i]); else B[i] = Math.max(B[i], 1); } // Initialize sum int sum = 0; // Find total sum for (int i = 0; i < N; i++) { sum += B[i]; } // Return sum System.out.print(sum + "\n"); } // Driver Code public static void main(String[] args) { // Given array int A[] = { 23, 14, 15, 14, 56, 29, 14 }; // Size of the given array int N = A.length; minChocolates(A, N); }} // This code contributed by shikhasingrajput # Python3 program for the above approach # Function to print minimum number# of candies required def minChocolates(A, N): B = [1 for i in range(N)] # Traverse from left to right for i in range(1, N): if (A[i] > A[i - 1]): B[i] = B[i - 1] + 1 else: B[i] = 1 # Traverse from right to left for i in range(N - 2, -1, -1): if (A[i] > A[i + 1]): B[i] = max(B[i + 1] + 1, B[i]) else: B[i] = max(B[i], 1) # Initialize sum sum = 0 # Find total sum for i in range(N): sum += B[i] # Return sum print(sum) # Driver Codeif __name__ == '__main__': # Given array A = [23, 14, 15, 14, 56, 29, 14] # Size of the given array N = len(A) minChocolates(A, N) # This code is contributed by mohit kumar 29 // C# program for the above approachusing System;public class GFG { // FUnction to print minimum number // of candies required static void minChocolates(int[] A, int N) { int[] B = new int[N]; // Distribute 1 chocolate to each for (int i = 0; i < N; i++) { B[i] = 1; } // Traverse from left to right for (int i = 1; i < N; i++) { if (A[i] > A[i - 1]) B[i] = B[i - 1] + 1; else B[i] = 1; } // Traverse from right to left for (int i = N - 2; i >= 0; i--) { if (A[i] > A[i + 1]) B[i] = Math.Max(B[i + 1] + 1, B[i]); else B[i] = Math.Max(B[i], 1); } // Initialize sum int sum = 0; // Find total sum for (int i = 0; i < N; i++) { sum += B[i]; } // Return sum Console.Write(sum + "\n"); } // Driver Code public static void Main(String[] args) { // Given array int[] A = { 23, 14, 15, 14, 56, 29, 14 }; // Size of the given array int N = A.Length; minChocolates(A, N); }} // This code is contributed by 29AjayKumar <script> // javascript program for the above approach // FUnction to print minimum number // of candies required function minChocolates(A, N) { let B = new Array(N).fill(0); // Distribute 1 chocolate to each for (let i = 0; i < N; i++) { B[i] = 1; } // Traverse from left to right for (let i = 1; i < N; i++) { if (A[i] > A[i - 1]) B[i] = B[i - 1] + 1; else B[i] = 1; } // Traverse from right to left for (let i = N - 2; i >= 0; i--) { if (A[i] > A[i + 1]) B[i] = Math.max(B[i + 1] + 1, B[i]); else B[i] = Math.max(B[i], 1); } // Initialize sum let sum = 0; // Find total sum for (let i = 0; i < N; i++) { sum += B[i]; } // Return sum document.write(sum + "<br/>"); } // Driver Code // Given array let A = [ 23, 14, 15, 14, 56, 29, 14 ]; // Size of the given array let N = A.length; minChocolates(A, N); </script> 12 Time Complexity: O(N) where N is the length of the given array.Auxiliary Space: O(N) Method 2 : Efficient approach On careful observation, the space complexity can be reduced to O(1). I. Observation: Marks array will be a combination of strictly increasing, strictly decreasing or flat (value is same as both the neighbors) subarrays. To minimize the total number of chocolates distributed, the number of chocolates received by a person and at least one of the neighbors should **differ by 1 or less. ** An exception of second observation is mentioned below II. Distributing chocolates Case 1: subarray is strictly increasing If the values are strictly increasing, number of chocolates given to ith student will be one more than the number of chocolates given to (i-1)th student (for any i > 0) One chocolate will be given to the left most person in subarray, two the next and so on incrementally up to the person with highest marks. For a strictly increasing subarray of length k, the chocolate distribution will be [1, 2, ... , k]. Case 2 : subarray is strictly decreasing Number of chocolates given to ith student will be one more than the chocolates given to (i+1)th student ( for any i < n-1) with one chocolate to the rightmost person and max number to the leftmost person of the subarray. For a strictly decreasing subarray of length k, the chocolate distribution will be [k, k-1, ... ,1]. Case 3 : flat sequence Given that a student with highest marks will be awarded more number of chocolates than neighbors. So there is no dependency if the values are equal. Minimum value will be assigned for optimal result. One chocolate will be given to person at position i if both the adjacent values are equal to a[i] i.e, a[i-1] == a[i] == a[i+1] For a flat subarray of length k, the chocolate distribution will be [1, 1, ... ,1]. **The difference for an assigned value with both the neighbors may be greater than 1, if there is a single element in flat sequence and it lies exactly between an increasing & decreasing sequence Transition points: The points where the trend(increasing/ decreasing/ flat nature) of subarray changes. Peak point : Point which is end point of one increasing sequence and start point of other decreasing sequence then value assigned will be max(k1, k2) where k1 – value obtained from increasing sequence, k2 – value obtained from decreasing sequence. This point will be considered as part of either increasing or decreasing sequence only III. Result : As the values in an increasing/decreasing sequence differ by 1, the number of chocolates distributed to students in a specific subarray of k elements will be sum of k natural numbers. And the count will be k for a flat sequence as all the values are 1. The required value will be the total sum of the results of subarrays. IV. Implementation: Consider variables i, j initially pointing to first element, val = 1, res = 0. After traversing through the array res gives the total number of chocolates distributed. val while iterating index j (in increasing/flat subarray) represents the number of chocolates received by the person at j If the subarray is increasing or a flat sequence, val is added to res; i, j are moved forward and val is updated according to next value (a[j + 1]). If the subarray is decreasing, i is pointed to the starting point of subarray and j is moved forward till next transition point. val, res are not updated till the end of the subarray. In this case val holds the value of the peak element obtained from previous subarray. At the end of the decreasing sequence res is updated using get_sum function & val is updated to point to the number of chocolates held by the next person. V. Example: Input: A[ ] = {1, 2, 10, 7, 6, 4, 5, 5, 5, 6} Output : 19 Explanation: subarray — sequence type — count of chocolates A[0-1] — increasing sequence — [1, 2] A[2-5] — decreasing sequence — [4, 3, 2, 1] A[5-6] — increasing sequence — [1, 2] A[7-7] — flat sequence — [1] A[8-9] — increasing sequence — [1, 2] A[2], A[9] are peak points Chocolates distribution will be [1, 2, 4, 3, 2, 1, 2, 1, 1, 2] Sum of all values = 19 Below is the code for above approach C C++ Java Python3 Javascript C# // C program for above approach#include <stdio.h> // Helper function to get sum of decreasing sequenceint get_sum(int peak, int start, int end){ /* peak is the value obtained at peak point from previous flat/increasing sequence */ /* value obtained from decreasing sequence also the count of values in the sequence*/ int count = end - start + 1; /* assigning max of values obtained from increasing and decreasing sequences */ peak = (peak > count) ? peak : count; /* sum of count - 1 values & peak value sum of natural numbers : (n * (n + 1))/2 */ int s = peak + (((count - 1) * count) >> 1); return s;} // Function to return minimum number of chocolatesint minChocolates(int a[], int n){ int i = 0, j = 0; int res = 0, val = 1; while (j < n - 1) { if (a[j] > a[j + 1]) { // decreasing sequence j += 1; continue; } if (i == j) // add the chocolates received by that person res += val; else { // end point of decreasing sequence res += get_sum(val, i, j); val = 1; // reset value at that index } if (a[j] < a[j + 1]) // increasing sequence val += 1; else // flat sequence val = 1; j += 1; i = j; } // add value of chocolates at position n-1 if (i == j) res += val; else res += get_sum(val, i, j); return res;} // Driver codeint main(){ int a[] = { 5, 5, 4, 3, 2, 1 }; int n = sizeof(a) / sizeof(a[0]); printf("Minimum number of chocolates = %d", minChocolates(a, n)); return 0;} // This code is contributed by saitejagampala // C++ program for above approach #include <iostream>using namespace std; // Helper function to get sum of decreasing sequenceint get_sum(int peak, int start, int end){ /* peak is the value obtained at peak point from previous flat/increasing sequence */ /* value obtained from decreasing sequence also the count of values in the sequence*/ int count = end - start + 1; /* assigning max of values obtained from increasing and decreasing sequences */ peak = max(peak, count); /* sum of count - 1 values & peak value sum of natural numbers : (n * (n + 1))/2 */ int s = peak + (((count - 1) * count) >> 1); return s;} // Function to return minimum number of chocolatesint minChocolates(int a[], int n){ int i = 0, j = 0; int res = 0, val = 1; while (j < n - 1) { if (a[j] > a[j + 1]) { // decreasing sequence j += 1; continue; } if (i == j) // add the chocolates received by that person res += val; else { // end point of decreasing sequence res += get_sum(val, i, j); val = 1; // reset value at that index } if (a[j] < a[j + 1]) // increasing sequence val += 1; else // flat sequence val = 1; j += 1; i = j; } // add value of chocolates at position n-1 if (i == j) res += val; else res += get_sum(val, i, j); return res;} // Driver codeint main(){ int a[] = { 5, 5, 4, 3, 2, 1 }; int n = sizeof(a) / sizeof(a[0]); cout << "Minimum number of chocolates = " << minChocolates(a, n) << "\n"; return 0;} // This code is contributed by saitejagampala // Java program for above approach import java.io.*; class GFG { public static void main(String[] args) { int[] a = { 5, 5, 4, 3, 2, 1 }; int n = a.length; System.out.print("Minimum number of chocolates = " + minChocolates(a, n)); } // Function to return minimum number of chocolates public static int minChocolates(int[] a, int n) { int i = 0, j = 0; int res = 0, val = 1; while (j < n - 1) { if (a[j] > a[j + 1]) { // decreasing sequence j += 1; continue; } if (i == j) // add the chocolates received by that // person res += val; else { // end point of decreasing sequence res += get_sum(val, i, j); val = 1; // reset value at that index } if (a[j] < a[j + 1]) // increasing sequence val += 1; else // flat sequence val = 1; j += 1; i = j; } // add value of chocolates at position n-1 if (i == j) res += val; else res += get_sum(val, i, j); return res; } // helper function to get sum of decreasing sequence public static int get_sum(int peak, int start, int end) { /* peak is the value obtained at peak point from previous flat/increasing sequence */ /* value obtained from decreasing sequence also the count of values in the sequence*/ int count = end - start + 1; /* assigning max of values obtained from increasing and decreasing sequences */ peak = (peak > count) ? peak : count; /* sum of count - 1 values & peak value sum of natural numbers : (n * (n + 1))/2 */ int s = peak + (((count - 1) * count) >> 1); return s; }} // This code is contributed by saitejagampala # Python3 program for above approach # Function to return minimum number of chocolates def minChocolates(a, n): i, j = 0, 0 val, res = 1, 0 while(j < n - 1): if(a[j] > a[j + 1]): # decreasing sequence j += 1 continue if(i == j): # add the chocolates received by that person res += val else: # end point of decreasing sequence res += get_sum(val, i, j) val = 1 # reset value at that index if(a[j] < a[j + 1]): # increasing sequence val += 1 else: # flat sequence val = 1 j += 1 i = j # add value of chocolates at position n-1 if(i == j): res += val else: res += get_sum(val, i, j) return res # Helper function to get sum of decreasing sequencedef get_sum(peak, start, end): # peak is the value obtained at peak point # from previous flat/increasing sequence # value obtained from decreasing sequence # also the count of values in the sequence count = end - start + 1 # assigning max of values obtained from increasing # and decreasing sequences peak = max(peak, count) # sum of count - 1 values & peak value # sum of natural numbers : (n * (n + 1))/2 s = peak + (((count-1) * count) >> 1) return s # Driver codeif __name__ == '__main__': a = [5, 5, 4, 3, 2, 1] n = len(a) print('Minimum number of chocolates =', minChocolates(a, n)) # This code is contributed by saitejagampala <script>// Javascript program for above approach // Function to return minimum number of chocolatesfunction minChocolates(a,n){ let i = 0, j = 0; let res = 0, val = 1; while (j < n - 1) { if (a[j] > a[j + 1]) { // decreasing sequence j += 1; continue; } if (i == j) // add the chocolates received by that // person res += val; else { // end point of decreasing sequence res += get_sum(val, i, j); val = 1; // reset value at that index } if (a[j] < a[j + 1]) // increasing sequence val += 1; else // flat sequence val = 1; j += 1; i = j; } // add value of chocolates at position n-1 if (i == j) res += val; else res += get_sum(val, i, j); return res;} // helper function to get sum of decreasing sequencefunction get_sum(peak,start,end){ /* peak is the value obtained at peak point from previous flat/increasing sequence */ /* value obtained from decreasing sequence also the count of values in the sequence*/ let count = end - start + 1; /* assigning max of values obtained from increasing and decreasing sequences */ peak = (peak > count) ? peak : count; /* sum of count - 1 values & peak value sum of natural numbers : (n * (n + 1))/2 */ let s = peak + (((count - 1) * count) >> 1); return s;} let a = [5, 5, 4, 3, 2, 1];let n = a.length;document.write("Minimum number of chocolates = " + minChocolates(a, n)); // This code is contributed by unknown2108</script> // C# program for above approach using System; public class GFG{ // Function to return minimum number of chocolates public static int minChocolates(int[] a, int n) { int i = 0, j = 0; int res = 0, val = 1; while (j < n - 1) { if (a[j] > a[j + 1]) { // decreasing sequence j += 1; continue; } if (i == j) // add the chocolates received by that // person res += val; else { // end point of decreasing sequence res += get_sum(val, i, j); val = 1; // reset value at that index } if (a[j] < a[j + 1]) // increasing sequence val += 1; else // flat sequence val = 1; j += 1; i = j; } // add value of chocolates at position n-1 if (i == j) res += val; else res += get_sum(val, i, j); return res; } // helper function to get sum of decreasing sequence public static int get_sum(int peak, int start, int end) { /* peak is the value obtained at peak point from previous flat/increasing sequence */ /* value obtained from decreasing sequence also the count of values in the sequence*/ int count = end - start + 1; /* assigning max of values obtained from increasing and decreasing sequences */ peak = (peak > count) ? peak : count; /* sum of count - 1 values & peak value sum of natural numbers : (n * (n + 1))/2 */ int s = peak + (((count - 1) * count) >> 1); return s; } static public void Main (){ int[] a = { 5, 5, 4, 3, 2, 1 }; int n = a.Length; Console.WriteLine("Minimum number of chocolates = " + minChocolates(a, n)); }} // This code is contributed by patel2127 Minimum number of chocolates = 16 Time Complexity : O(N), N is the length of the array Space Complexity : O(1) Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. mohit kumar 29 shikhasingrajput 29AjayKumar saitejagampala souravghosh0416 unknown2108 patel2127 Kirti_Mangal array-traversal-question Flipkart interview-preparation Arrays Mathematical Flipkart Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24497, "s": 24469, "text": "\n14 Dec, 2021" }, { "code": null, "e": 24691, "s": 24497, "text": "Given an array A[] consisting of N integers, where each value represents the marks of the ith student, the task is to find the minimum number of chocolates required to be distributed such that:" }, { "code": null, "e": 24750, "s": 24691, "text": "Each student should be awarded with at least one chocolate" }, { "code": null, "e": 24840, "s": 24750, "text": "A student with higher marks should be awarded more chocolates than his adjacent students." }, { "code": null, "e": 24850, "s": 24840, "text": "Examples:" }, { "code": null, "e": 25067, "s": 24850, "text": "Input: A[] = {10, 30, 20}Output: 4Explanation : Since, 30 is larger than its adjacent, so the second student must get more chocolates. Therefore, the minimum chocolates can be distributed as {1, 2, 1} = 1 + 2 + 1 = 4" }, { "code": null, "e": 25120, "s": 25067, "text": "Input: A[] = {23, 14, 15, 14, 56, 29, 14}Output: 12 " }, { "code": null, "e": 25130, "s": 25120, "text": "Method 1:" }, { "code": null, "e": 25234, "s": 25130, "text": "Approach: The problem can be solved using Greedy approach. Follow the steps below to solve the problem:" }, { "code": null, "e": 25275, "s": 25234, "text": "Initialize array B[] of length N with 1." }, { "code": null, "e": 25385, "s": 25275, "text": "Traverse from left to right from i = 1 to N – 1, updating B[i] as B[i] = B[i-1]+1 if A[i] greater the A[i-1]." }, { "code": null, "e": 25598, "s": 25385, "text": "After completing the above step, traverse again from right to left from i = N – 2 to 0, updating B[i] as B[i] = max(B[i], B[i+1]+1) if A[i] is greater than A[i + 1]. Otherwise, update B[i] as B[i] = max(B[i], 1)." }, { "code": null, "e": 25707, "s": 25598, "text": "After traversing, calculate the sum of the array B[] and print it as the minimum number of candies required." }, { "code": null, "e": 25758, "s": 25707, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25762, "s": 25758, "text": "C++" }, { "code": null, "e": 25767, "s": 25762, "text": "Java" }, { "code": null, "e": 25775, "s": 25767, "text": "Python3" }, { "code": null, "e": 25778, "s": 25775, "text": "C#" }, { "code": null, "e": 25789, "s": 25778, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <iostream>using namespace std; // FUnction to print minimum number// of candies requiredvoid minChocolates(int A[], int N){ int B[N]; // Distribute 1 chocolate to each for (int i = 0; i < N; i++) { B[i] = 1; } // Traverse from left to right for (int i = 1; i < N; i++) { if (A[i] > A[i - 1]) B[i] = B[i - 1] + 1; else B[i] = 1; } // Traverse from right to left for (int i = N - 2; i >= 0; i--) { if (A[i] > A[i + 1]) B[i] = max(B[i + 1] + 1, B[i]); else B[i] = max(B[i], 1); } // Initialize sum int sum = 0; // Find total sum for (int i = 0; i < N; i++) { sum += B[i]; } // Return sum cout << sum << \"\\n\";} // Driver Codeint main(){ // Given array int A[] = { 23, 14, 15, 14, 56, 29, 14 }; // Size of the given array int N = sizeof(A) / sizeof(A[0]); minChocolates(A, N);}", "e": 26782, "s": 25789, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG { // FUnction to print minimum number // of candies required static void minChocolates(int A[], int N) { int[] B = new int[N]; // Distribute 1 chocolate to each for (int i = 0; i < N; i++) { B[i] = 1; } // Traverse from left to right for (int i = 1; i < N; i++) { if (A[i] > A[i - 1]) B[i] = B[i - 1] + 1; else B[i] = 1; } // Traverse from right to left for (int i = N - 2; i >= 0; i--) { if (A[i] > A[i + 1]) B[i] = Math.max(B[i + 1] + 1, B[i]); else B[i] = Math.max(B[i], 1); } // Initialize sum int sum = 0; // Find total sum for (int i = 0; i < N; i++) { sum += B[i]; } // Return sum System.out.print(sum + \"\\n\"); } // Driver Code public static void main(String[] args) { // Given array int A[] = { 23, 14, 15, 14, 56, 29, 14 }; // Size of the given array int N = A.length; minChocolates(A, N); }} // This code contributed by shikhasingrajput", "e": 28024, "s": 26782, "text": null }, { "code": "# Python3 program for the above approach # Function to print minimum number# of candies required def minChocolates(A, N): B = [1 for i in range(N)] # Traverse from left to right for i in range(1, N): if (A[i] > A[i - 1]): B[i] = B[i - 1] + 1 else: B[i] = 1 # Traverse from right to left for i in range(N - 2, -1, -1): if (A[i] > A[i + 1]): B[i] = max(B[i + 1] + 1, B[i]) else: B[i] = max(B[i], 1) # Initialize sum sum = 0 # Find total sum for i in range(N): sum += B[i] # Return sum print(sum) # Driver Codeif __name__ == '__main__': # Given array A = [23, 14, 15, 14, 56, 29, 14] # Size of the given array N = len(A) minChocolates(A, N) # This code is contributed by mohit kumar 29", "e": 28868, "s": 28024, "text": null }, { "code": "// C# program for the above approachusing System;public class GFG { // FUnction to print minimum number // of candies required static void minChocolates(int[] A, int N) { int[] B = new int[N]; // Distribute 1 chocolate to each for (int i = 0; i < N; i++) { B[i] = 1; } // Traverse from left to right for (int i = 1; i < N; i++) { if (A[i] > A[i - 1]) B[i] = B[i - 1] + 1; else B[i] = 1; } // Traverse from right to left for (int i = N - 2; i >= 0; i--) { if (A[i] > A[i + 1]) B[i] = Math.Max(B[i + 1] + 1, B[i]); else B[i] = Math.Max(B[i], 1); } // Initialize sum int sum = 0; // Find total sum for (int i = 0; i < N; i++) { sum += B[i]; } // Return sum Console.Write(sum + \"\\n\"); } // Driver Code public static void Main(String[] args) { // Given array int[] A = { 23, 14, 15, 14, 56, 29, 14 }; // Size of the given array int N = A.Length; minChocolates(A, N); }} // This code is contributed by 29AjayKumar", "e": 30104, "s": 28868, "text": null }, { "code": "<script> // javascript program for the above approach // FUnction to print minimum number // of candies required function minChocolates(A, N) { let B = new Array(N).fill(0); // Distribute 1 chocolate to each for (let i = 0; i < N; i++) { B[i] = 1; } // Traverse from left to right for (let i = 1; i < N; i++) { if (A[i] > A[i - 1]) B[i] = B[i - 1] + 1; else B[i] = 1; } // Traverse from right to left for (let i = N - 2; i >= 0; i--) { if (A[i] > A[i + 1]) B[i] = Math.max(B[i + 1] + 1, B[i]); else B[i] = Math.max(B[i], 1); } // Initialize sum let sum = 0; // Find total sum for (let i = 0; i < N; i++) { sum += B[i]; } // Return sum document.write(sum + \"<br/>\"); } // Driver Code // Given array let A = [ 23, 14, 15, 14, 56, 29, 14 ]; // Size of the given array let N = A.length; minChocolates(A, N); </script>", "e": 31234, "s": 30104, "text": null }, { "code": null, "e": 31237, "s": 31234, "text": "12" }, { "code": null, "e": 31324, "s": 31239, "text": "Time Complexity: O(N) where N is the length of the given array.Auxiliary Space: O(N)" }, { "code": null, "e": 31354, "s": 31324, "text": "Method 2 : Efficient approach" }, { "code": null, "e": 31423, "s": 31354, "text": "On careful observation, the space complexity can be reduced to O(1)." }, { "code": null, "e": 31439, "s": 31423, "text": "I. Observation:" }, { "code": null, "e": 31574, "s": 31439, "text": "Marks array will be a combination of strictly increasing, strictly decreasing or flat (value is same as both the neighbors) subarrays." }, { "code": null, "e": 31740, "s": 31574, "text": "To minimize the total number of chocolates distributed, the number of chocolates received by a person and at least one of the neighbors should **differ by 1 or less." }, { "code": null, "e": 31797, "s": 31740, "text": "** An exception of second observation is mentioned below" }, { "code": null, "e": 31825, "s": 31797, "text": "II. Distributing chocolates" }, { "code": null, "e": 31865, "s": 31825, "text": "Case 1: subarray is strictly increasing" }, { "code": null, "e": 32035, "s": 31865, "text": "If the values are strictly increasing, number of chocolates given to ith student will be one more than the number of chocolates given to (i-1)th student (for any i > 0)" }, { "code": null, "e": 32174, "s": 32035, "text": "One chocolate will be given to the left most person in subarray, two the next and so on incrementally up to the person with highest marks." }, { "code": null, "e": 32274, "s": 32174, "text": "For a strictly increasing subarray of length k, the chocolate distribution will be [1, 2, ... , k]." }, { "code": null, "e": 32315, "s": 32274, "text": "Case 2 : subarray is strictly decreasing" }, { "code": null, "e": 32537, "s": 32315, "text": "Number of chocolates given to ith student will be one more than the chocolates given to (i+1)th student ( for any i < n-1) with one chocolate to the rightmost person and max number to the leftmost person of the subarray." }, { "code": null, "e": 32638, "s": 32537, "text": "For a strictly decreasing subarray of length k, the chocolate distribution will be [k, k-1, ... ,1]." }, { "code": null, "e": 32661, "s": 32638, "text": "Case 3 : flat sequence" }, { "code": null, "e": 32861, "s": 32661, "text": "Given that a student with highest marks will be awarded more number of chocolates than neighbors. So there is no dependency if the values are equal. Minimum value will be assigned for optimal result." }, { "code": null, "e": 32989, "s": 32861, "text": "One chocolate will be given to person at position i if both the adjacent values are equal to a[i] i.e, a[i-1] == a[i] == a[i+1]" }, { "code": null, "e": 33073, "s": 32989, "text": "For a flat subarray of length k, the chocolate distribution will be [1, 1, ... ,1]." }, { "code": null, "e": 33269, "s": 33073, "text": "**The difference for an assigned value with both the neighbors may be greater than 1, if there is a single element in flat sequence and it lies exactly between an increasing & decreasing sequence" }, { "code": null, "e": 33373, "s": 33269, "text": "Transition points: The points where the trend(increasing/ decreasing/ flat nature) of subarray changes." }, { "code": null, "e": 33483, "s": 33373, "text": "Peak point : Point which is end point of one increasing sequence and start point of other decreasing sequence" }, { "code": null, "e": 33523, "s": 33483, "text": "then value assigned will be max(k1, k2)" }, { "code": null, "e": 33575, "s": 33523, "text": "where k1 – value obtained from increasing sequence," }, { "code": null, "e": 33621, "s": 33575, "text": "k2 – value obtained from decreasing sequence." }, { "code": null, "e": 33709, "s": 33621, "text": "This point will be considered as part of either increasing or decreasing sequence only " }, { "code": null, "e": 33724, "s": 33709, "text": "III. Result : " }, { "code": null, "e": 34049, "s": 33724, "text": " As the values in an increasing/decreasing sequence differ by 1, the number of chocolates distributed to students in a specific subarray of k elements will be sum of k natural numbers. And the count will be k for a flat sequence as all the values are 1. The required value will be the total sum of the results of subarrays." }, { "code": null, "e": 34069, "s": 34049, "text": "IV. Implementation:" }, { "code": null, "e": 34148, "s": 34069, "text": "Consider variables i, j initially pointing to first element, val = 1, res = 0." }, { "code": null, "e": 34237, "s": 34148, "text": "After traversing through the array res gives the total number of chocolates distributed." }, { "code": null, "e": 34359, "s": 34237, "text": "val while iterating index j (in increasing/flat subarray) represents the number of chocolates received by the person at j" }, { "code": null, "e": 34508, "s": 34359, "text": "If the subarray is increasing or a flat sequence, val is added to res; i, j are moved forward and val is updated according to next value (a[j + 1])." }, { "code": null, "e": 34933, "s": 34508, "text": "If the subarray is decreasing, i is pointed to the starting point of subarray and j is moved forward till next transition point. val, res are not updated till the end of the subarray. In this case val holds the value of the peak element obtained from previous subarray. At the end of the decreasing sequence res is updated using get_sum function & val is updated to point to the number of chocolates held by the next person." }, { "code": null, "e": 34945, "s": 34933, "text": "V. Example:" }, { "code": null, "e": 34991, "s": 34945, "text": "Input: A[ ] = {1, 2, 10, 7, 6, 4, 5, 5, 5, 6}" }, { "code": null, "e": 35003, "s": 34991, "text": "Output : 19" }, { "code": null, "e": 35016, "s": 35003, "text": "Explanation:" }, { "code": null, "e": 35067, "s": 35016, "text": "subarray — sequence type — count of chocolates" }, { "code": null, "e": 35105, "s": 35067, "text": "A[0-1] — increasing sequence — [1, 2]" }, { "code": null, "e": 35149, "s": 35105, "text": "A[2-5] — decreasing sequence — [4, 3, 2, 1]" }, { "code": null, "e": 35187, "s": 35149, "text": "A[5-6] — increasing sequence — [1, 2]" }, { "code": null, "e": 35222, "s": 35187, "text": "A[7-7] — flat sequence — [1]" }, { "code": null, "e": 35260, "s": 35222, "text": "A[8-9] — increasing sequence — [1, 2]" }, { "code": null, "e": 35287, "s": 35260, "text": "A[2], A[9] are peak points" }, { "code": null, "e": 35320, "s": 35287, "text": "Chocolates distribution will be " }, { "code": null, "e": 35351, "s": 35320, "text": "[1, 2, 4, 3, 2, 1, 2, 1, 1, 2]" }, { "code": null, "e": 35374, "s": 35351, "text": "Sum of all values = 19" }, { "code": null, "e": 35411, "s": 35374, "text": "Below is the code for above approach" }, { "code": null, "e": 35413, "s": 35411, "text": "C" }, { "code": null, "e": 35417, "s": 35413, "text": "C++" }, { "code": null, "e": 35422, "s": 35417, "text": "Java" }, { "code": null, "e": 35430, "s": 35422, "text": "Python3" }, { "code": null, "e": 35441, "s": 35430, "text": "Javascript" }, { "code": null, "e": 35444, "s": 35441, "text": "C#" }, { "code": "// C program for above approach#include <stdio.h> // Helper function to get sum of decreasing sequenceint get_sum(int peak, int start, int end){ /* peak is the value obtained at peak point from previous flat/increasing sequence */ /* value obtained from decreasing sequence also the count of values in the sequence*/ int count = end - start + 1; /* assigning max of values obtained from increasing and decreasing sequences */ peak = (peak > count) ? peak : count; /* sum of count - 1 values & peak value sum of natural numbers : (n * (n + 1))/2 */ int s = peak + (((count - 1) * count) >> 1); return s;} // Function to return minimum number of chocolatesint minChocolates(int a[], int n){ int i = 0, j = 0; int res = 0, val = 1; while (j < n - 1) { if (a[j] > a[j + 1]) { // decreasing sequence j += 1; continue; } if (i == j) // add the chocolates received by that person res += val; else { // end point of decreasing sequence res += get_sum(val, i, j); val = 1; // reset value at that index } if (a[j] < a[j + 1]) // increasing sequence val += 1; else // flat sequence val = 1; j += 1; i = j; } // add value of chocolates at position n-1 if (i == j) res += val; else res += get_sum(val, i, j); return res;} // Driver codeint main(){ int a[] = { 5, 5, 4, 3, 2, 1 }; int n = sizeof(a) / sizeof(a[0]); printf(\"Minimum number of chocolates = %d\", minChocolates(a, n)); return 0;} // This code is contributed by saitejagampala", "e": 37191, "s": 35444, "text": null }, { "code": "// C++ program for above approach #include <iostream>using namespace std; // Helper function to get sum of decreasing sequenceint get_sum(int peak, int start, int end){ /* peak is the value obtained at peak point from previous flat/increasing sequence */ /* value obtained from decreasing sequence also the count of values in the sequence*/ int count = end - start + 1; /* assigning max of values obtained from increasing and decreasing sequences */ peak = max(peak, count); /* sum of count - 1 values & peak value sum of natural numbers : (n * (n + 1))/2 */ int s = peak + (((count - 1) * count) >> 1); return s;} // Function to return minimum number of chocolatesint minChocolates(int a[], int n){ int i = 0, j = 0; int res = 0, val = 1; while (j < n - 1) { if (a[j] > a[j + 1]) { // decreasing sequence j += 1; continue; } if (i == j) // add the chocolates received by that person res += val; else { // end point of decreasing sequence res += get_sum(val, i, j); val = 1; // reset value at that index } if (a[j] < a[j + 1]) // increasing sequence val += 1; else // flat sequence val = 1; j += 1; i = j; } // add value of chocolates at position n-1 if (i == j) res += val; else res += get_sum(val, i, j); return res;} // Driver codeint main(){ int a[] = { 5, 5, 4, 3, 2, 1 }; int n = sizeof(a) / sizeof(a[0]); cout << \"Minimum number of chocolates = \" << minChocolates(a, n) << \"\\n\"; return 0;} // This code is contributed by saitejagampala", "e": 38956, "s": 37191, "text": null }, { "code": "// Java program for above approach import java.io.*; class GFG { public static void main(String[] args) { int[] a = { 5, 5, 4, 3, 2, 1 }; int n = a.length; System.out.print(\"Minimum number of chocolates = \" + minChocolates(a, n)); } // Function to return minimum number of chocolates public static int minChocolates(int[] a, int n) { int i = 0, j = 0; int res = 0, val = 1; while (j < n - 1) { if (a[j] > a[j + 1]) { // decreasing sequence j += 1; continue; } if (i == j) // add the chocolates received by that // person res += val; else { // end point of decreasing sequence res += get_sum(val, i, j); val = 1; // reset value at that index } if (a[j] < a[j + 1]) // increasing sequence val += 1; else // flat sequence val = 1; j += 1; i = j; } // add value of chocolates at position n-1 if (i == j) res += val; else res += get_sum(val, i, j); return res; } // helper function to get sum of decreasing sequence public static int get_sum(int peak, int start, int end) { /* peak is the value obtained at peak point from previous flat/increasing sequence */ /* value obtained from decreasing sequence also the count of values in the sequence*/ int count = end - start + 1; /* assigning max of values obtained from increasing and decreasing sequences */ peak = (peak > count) ? peak : count; /* sum of count - 1 values & peak value sum of natural numbers : (n * (n + 1))/2 */ int s = peak + (((count - 1) * count) >> 1); return s; }} // This code is contributed by saitejagampala", "e": 41001, "s": 38956, "text": null }, { "code": "# Python3 program for above approach # Function to return minimum number of chocolates def minChocolates(a, n): i, j = 0, 0 val, res = 1, 0 while(j < n - 1): if(a[j] > a[j + 1]): # decreasing sequence j += 1 continue if(i == j): # add the chocolates received by that person res += val else: # end point of decreasing sequence res += get_sum(val, i, j) val = 1 # reset value at that index if(a[j] < a[j + 1]): # increasing sequence val += 1 else: # flat sequence val = 1 j += 1 i = j # add value of chocolates at position n-1 if(i == j): res += val else: res += get_sum(val, i, j) return res # Helper function to get sum of decreasing sequencedef get_sum(peak, start, end): # peak is the value obtained at peak point # from previous flat/increasing sequence # value obtained from decreasing sequence # also the count of values in the sequence count = end - start + 1 # assigning max of values obtained from increasing # and decreasing sequences peak = max(peak, count) # sum of count - 1 values & peak value # sum of natural numbers : (n * (n + 1))/2 s = peak + (((count-1) * count) >> 1) return s # Driver codeif __name__ == '__main__': a = [5, 5, 4, 3, 2, 1] n = len(a) print('Minimum number of chocolates =', minChocolates(a, n)) # This code is contributed by saitejagampala", "e": 42574, "s": 41001, "text": null }, { "code": "<script>// Javascript program for above approach // Function to return minimum number of chocolatesfunction minChocolates(a,n){ let i = 0, j = 0; let res = 0, val = 1; while (j < n - 1) { if (a[j] > a[j + 1]) { // decreasing sequence j += 1; continue; } if (i == j) // add the chocolates received by that // person res += val; else { // end point of decreasing sequence res += get_sum(val, i, j); val = 1; // reset value at that index } if (a[j] < a[j + 1]) // increasing sequence val += 1; else // flat sequence val = 1; j += 1; i = j; } // add value of chocolates at position n-1 if (i == j) res += val; else res += get_sum(val, i, j); return res;} // helper function to get sum of decreasing sequencefunction get_sum(peak,start,end){ /* peak is the value obtained at peak point from previous flat/increasing sequence */ /* value obtained from decreasing sequence also the count of values in the sequence*/ let count = end - start + 1; /* assigning max of values obtained from increasing and decreasing sequences */ peak = (peak > count) ? peak : count; /* sum of count - 1 values & peak value sum of natural numbers : (n * (n + 1))/2 */ let s = peak + (((count - 1) * count) >> 1); return s;} let a = [5, 5, 4, 3, 2, 1];let n = a.length;document.write(\"Minimum number of chocolates = \" + minChocolates(a, n)); // This code is contributed by unknown2108</script>", "e": 44525, "s": 42574, "text": null }, { "code": "// C# program for above approach using System; public class GFG{ // Function to return minimum number of chocolates public static int minChocolates(int[] a, int n) { int i = 0, j = 0; int res = 0, val = 1; while (j < n - 1) { if (a[j] > a[j + 1]) { // decreasing sequence j += 1; continue; } if (i == j) // add the chocolates received by that // person res += val; else { // end point of decreasing sequence res += get_sum(val, i, j); val = 1; // reset value at that index } if (a[j] < a[j + 1]) // increasing sequence val += 1; else // flat sequence val = 1; j += 1; i = j; } // add value of chocolates at position n-1 if (i == j) res += val; else res += get_sum(val, i, j); return res; } // helper function to get sum of decreasing sequence public static int get_sum(int peak, int start, int end) { /* peak is the value obtained at peak point from previous flat/increasing sequence */ /* value obtained from decreasing sequence also the count of values in the sequence*/ int count = end - start + 1; /* assigning max of values obtained from increasing and decreasing sequences */ peak = (peak > count) ? peak : count; /* sum of count - 1 values & peak value sum of natural numbers : (n * (n + 1))/2 */ int s = peak + (((count - 1) * count) >> 1); return s; } static public void Main (){ int[] a = { 5, 5, 4, 3, 2, 1 }; int n = a.Length; Console.WriteLine(\"Minimum number of chocolates = \" + minChocolates(a, n)); }} // This code is contributed by patel2127", "e": 46592, "s": 44525, "text": null }, { "code": null, "e": 46626, "s": 46592, "text": "Minimum number of chocolates = 16" }, { "code": null, "e": 46680, "s": 46626, "text": "Time Complexity : O(N), N is the length of the array" }, { "code": null, "e": 46704, "s": 46680, "text": "Space Complexity : O(1)" }, { "code": null, "e": 46829, "s": 46704, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 46844, "s": 46829, "text": "mohit kumar 29" }, { "code": null, "e": 46861, "s": 46844, "text": "shikhasingrajput" }, { "code": null, "e": 46873, "s": 46861, "text": "29AjayKumar" }, { "code": null, "e": 46888, "s": 46873, "text": "saitejagampala" }, { "code": null, "e": 46904, "s": 46888, "text": "souravghosh0416" }, { "code": null, "e": 46916, "s": 46904, "text": "unknown2108" }, { "code": null, "e": 46926, "s": 46916, "text": "patel2127" }, { "code": null, "e": 46939, "s": 46926, "text": "Kirti_Mangal" }, { "code": null, "e": 46964, "s": 46939, "text": "array-traversal-question" }, { "code": null, "e": 46973, "s": 46964, "text": "Flipkart" }, { "code": null, "e": 46995, "s": 46973, "text": "interview-preparation" }, { "code": null, "e": 47002, "s": 46995, "text": "Arrays" }, { "code": null, "e": 47015, "s": 47002, "text": "Mathematical" }, { "code": null, "e": 47024, "s": 47015, "text": "Flipkart" }, { "code": null, "e": 47031, "s": 47024, "text": "Arrays" }, { "code": null, "e": 47044, "s": 47031, "text": "Mathematical" }, { "code": null, "e": 47142, "s": 47044, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47151, "s": 47142, "text": "Comments" }, { "code": null, "e": 47164, "s": 47151, "text": "Old Comments" }, { "code": null, "e": 47212, "s": 47164, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 47256, "s": 47212, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 47279, "s": 47256, "text": "Introduction to Arrays" }, { "code": null, "e": 47311, "s": 47279, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 47325, "s": 47311, "text": "Linear Search" }, { "code": null, "e": 47355, "s": 47325, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 47415, "s": 47355, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 47430, "s": 47415, "text": "C++ Data Types" }, { "code": null, "e": 47473, "s": 47430, "text": "Set in C++ Standard Template Library (STL)" } ]
Perl last Statement
When a last statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. You can provide a LABEL with last statement where LABEL is the label for a loop. A last statement can be used inside a nested loop where it will be applicable to the nearest loop if a LABEL is not specified. If there is any continue block on the loop, then it is not executed. You will see the continue statement in a separate chapter. The syntax of a last statement in Perl is − last [LABEL]; #!/usr/local/bin/perl $a = 10; while( $a < 20 ) { if( $a == 15) { # terminate the loop. $a = $a + 1; last; } print "value of a: $a\n"; $a = $a + 1; } When the above code is executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 Let's take one example where we are going to use a LABEL along with next statement − #!/usr/local/bin/perl $a = 0; OUTER: while( $a < 4 ) { $b = 0; print "value of a: $a\n"; INNER:while ( $b < 4) { if( $a == 2) { # terminate outer loop last OUTER; } $b = $b + 1; print "Value of b : $b\n"; } print "\n"; $a = $a + 1; } When the above code is executed, it produces the following result − value of a : 0 Value of b : 1 Value of b : 2 Value of b : 3 Value of b : 4 value of a : 1 Value of b : 1 Value of b : 2 Value of b : 3 Value of b : 4 value of a : 2 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2591, "s": 2220, "text": "When a last statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. You can provide a LABEL with last statement where LABEL is the label for a loop. A last statement can be used inside a nested loop where it will be applicable to the nearest loop if a LABEL is not specified." }, { "code": null, "e": 2719, "s": 2591, "text": "If there is any continue block on the loop, then it is not executed. You will see the continue statement in a separate chapter." }, { "code": null, "e": 2763, "s": 2719, "text": "The syntax of a last statement in Perl is −" }, { "code": null, "e": 2778, "s": 2763, "text": "last [LABEL];\n" }, { "code": null, "e": 2959, "s": 2778, "text": "#!/usr/local/bin/perl\n\n$a = 10;\nwhile( $a < 20 ) {\n if( $a == 15) {\n # terminate the loop.\n $a = $a + 1;\n last;\n }\n print \"value of a: $a\\n\";\n $a = $a + 1;\n}" }, { "code": null, "e": 3027, "s": 2959, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3103, "s": 3027, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\n" }, { "code": null, "e": 3188, "s": 3103, "text": "Let's take one example where we are going to use a LABEL along with next statement −" }, { "code": null, "e": 3483, "s": 3188, "text": "#!/usr/local/bin/perl\n\n$a = 0;\nOUTER: while( $a < 4 ) {\n $b = 0;\n print \"value of a: $a\\n\";\n INNER:while ( $b < 4) {\n if( $a == 2) {\n # terminate outer loop\n last OUTER;\n }\n $b = $b + 1;\n print \"Value of b : $b\\n\";\n }\n print \"\\n\";\n $a = $a + 1;\n}" }, { "code": null, "e": 3551, "s": 3483, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3719, "s": 3551, "text": "value of a : 0\nValue of b : 1\nValue of b : 2\nValue of b : 3\nValue of b : 4\n\nvalue of a : 1\nValue of b : 1\nValue of b : 2\nValue of b : 3\nValue of b : 4\n\nvalue of a : 2\n" }, { "code": null, "e": 3754, "s": 3719, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3768, "s": 3754, "text": " Devi Killada" }, { "code": null, "e": 3803, "s": 3768, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3823, "s": 3803, "text": " Harshit Srivastava" }, { "code": null, "e": 3856, "s": 3823, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3872, "s": 3856, "text": " TELCOMA Global" }, { "code": null, "e": 3905, "s": 3872, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3922, "s": 3905, "text": " Mohammad Nauman" }, { "code": null, "e": 3955, "s": 3922, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3978, "s": 3955, "text": " Stone River ELearning" }, { "code": null, "e": 4013, "s": 3978, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4036, "s": 4013, "text": " Stone River ELearning" }, { "code": null, "e": 4043, "s": 4036, "text": " Print" }, { "code": null, "e": 4054, "s": 4043, "text": " Add Notes" } ]
Create Landing Pages For Your Projects With GitHub Pages | by Naveen Venkatesan | Towards Data Science
I come from an experimental science background where we deal with a ton of home-built experiment setups and data analysis scripts. Often, the result of this can be poorly documented and difficult-to-use code, especially after the original graduate student (who wrote it) has graduated and left. For this reason, when I developed some data analysis scripts during my grad school research, I decided I wanted to try and document/demonstrate it as well as I could so that any future users could use it intuitively. The result of my efforts is this landing page. I was able to generate this website with GitHub Pages, which is a service that allows you to easily host a static website for your repository. Doing this is extremely simple, and your website will be at the URL: https://<username>.github.io/<repository_name> For simplicity, we don’t want a user that clones our master branch to also see all the of the HTML/CSS/JS files that will be associated with our project website. To get around this issue, we can use something called an orphan branch — essentially a branch that sits at the root of the tree with no previous commits. Then, by having all of our website files live in the orphan branch, when the repository is cloned, only the files on master will be shown by default (though anyone can still go to the website branch if they wish). We create our orphan branch, which we will call gh-pages with the following command: git checkout --orphan gh-pages This is the part that I found the scariest when I first did this. You are going to remove everything from your folder in order to clear the gh-pages branch. Don’t worry, your master branch files are not gone! Use the following command: git rm -rf . You will notice that all the files will vanish from your local working directory, which is what freaked me out the first time I did this. Again, do not worry, everything will be fine! Now, add your index.html file, along with any CSS stylesheets, Javascript, and other resources your website would need to run into your local working directory. Now stage and commit your changes: git add *git commit -m "Commit Message" Finally, we want to make sure we are pushing our changes to the appropriate branch (gh-pages). git push origin gh-pages Navigate online to your GitHub repository and go to the settings. As you scroll down, you will notice a section titled “GitHub Pages”. Under the area titled “Source”, you will see a drop-down menu, which you can use to select the branch from which to build your website. We will go ahead and select gh-pages. Wait a couple minutes, and BAM! Your site should be live! Navigate your browser to https://<username>.github.io/<repo_name> to see your wonderful creation. As you continue to edit your website and source code, you will quickly notice that you will have to keep switching between your two branches: # Switch to master branchgit checkout master# Switch to gh-pages branchgit checkout gh-pages Although simple, this may become cumbersome after a while — fortunately, we can use feature called worktree to create separate directories for each of these branches. First, let’s either create a separate, new directory with the same name as our repository, or clear out our local working directory. If we clear out the current directory, we want to remove all the git tracking info, which we can do with the following: # Remove git trackingrm -rf .git* Now, let’s re-clone our repository into a subdirectory. We’ll call this directory source and it will be where we keep all our source code. git clone https://github.com/<username>/<reponame> source You will notice that you now have a folder called source with all the files from the master branch. Now let’s create a new directory called gh-pages that will house all our website files: mkdir gh-pages Navigate into the source folder: cd source/ Now, we use worktree and make our gh-pages directory correspond to the remote gh-pages branch. git worktree add ../gh-pages gh-pages And you’re done! Now, you will notice that when you go to the gh-pages directory, you will only see the files on the gh-pages branch, and if you run a git branch command, you will see that you are on the master when in the source directory, and gh-pages when in the gh-pages directory. You can now freely edit both your repository website and source code at the same time, and you have an awesome landing page for your project on GitHub! Thank you for reading! You can see some of my work at my personal GitHub page. I appreciate any feedback, and you can find me on Twitter and connect with me on LinkedIn for more updates and articles.
[ { "code": null, "e": 731, "s": 172, "text": "I come from an experimental science background where we deal with a ton of home-built experiment setups and data analysis scripts. Often, the result of this can be poorly documented and difficult-to-use code, especially after the original graduate student (who wrote it) has graduated and left. For this reason, when I developed some data analysis scripts during my grad school research, I decided I wanted to try and document/demonstrate it as well as I could so that any future users could use it intuitively. The result of my efforts is this landing page." }, { "code": null, "e": 943, "s": 731, "text": "I was able to generate this website with GitHub Pages, which is a service that allows you to easily host a static website for your repository. Doing this is extremely simple, and your website will be at the URL:" }, { "code": null, "e": 990, "s": 943, "text": "https://<username>.github.io/<repository_name>" }, { "code": null, "e": 1520, "s": 990, "text": "For simplicity, we don’t want a user that clones our master branch to also see all the of the HTML/CSS/JS files that will be associated with our project website. To get around this issue, we can use something called an orphan branch — essentially a branch that sits at the root of the tree with no previous commits. Then, by having all of our website files live in the orphan branch, when the repository is cloned, only the files on master will be shown by default (though anyone can still go to the website branch if they wish)." }, { "code": null, "e": 1605, "s": 1520, "text": "We create our orphan branch, which we will call gh-pages with the following command:" }, { "code": null, "e": 1636, "s": 1605, "text": "git checkout --orphan gh-pages" }, { "code": null, "e": 1872, "s": 1636, "text": "This is the part that I found the scariest when I first did this. You are going to remove everything from your folder in order to clear the gh-pages branch. Don’t worry, your master branch files are not gone! Use the following command:" }, { "code": null, "e": 1885, "s": 1872, "text": "git rm -rf ." }, { "code": null, "e": 2069, "s": 1885, "text": "You will notice that all the files will vanish from your local working directory, which is what freaked me out the first time I did this. Again, do not worry, everything will be fine!" }, { "code": null, "e": 2265, "s": 2069, "text": "Now, add your index.html file, along with any CSS stylesheets, Javascript, and other resources your website would need to run into your local working directory. Now stage and commit your changes:" }, { "code": null, "e": 2305, "s": 2265, "text": "git add *git commit -m \"Commit Message\"" }, { "code": null, "e": 2400, "s": 2305, "text": "Finally, we want to make sure we are pushing our changes to the appropriate branch (gh-pages)." }, { "code": null, "e": 2425, "s": 2400, "text": "git push origin gh-pages" }, { "code": null, "e": 2734, "s": 2425, "text": "Navigate online to your GitHub repository and go to the settings. As you scroll down, you will notice a section titled “GitHub Pages”. Under the area titled “Source”, you will see a drop-down menu, which you can use to select the branch from which to build your website. We will go ahead and select gh-pages." }, { "code": null, "e": 2890, "s": 2734, "text": "Wait a couple minutes, and BAM! Your site should be live! Navigate your browser to https://<username>.github.io/<repo_name> to see your wonderful creation." }, { "code": null, "e": 3032, "s": 2890, "text": "As you continue to edit your website and source code, you will quickly notice that you will have to keep switching between your two branches:" }, { "code": null, "e": 3125, "s": 3032, "text": "# Switch to master branchgit checkout master# Switch to gh-pages branchgit checkout gh-pages" }, { "code": null, "e": 3292, "s": 3125, "text": "Although simple, this may become cumbersome after a while — fortunately, we can use feature called worktree to create separate directories for each of these branches." }, { "code": null, "e": 3545, "s": 3292, "text": "First, let’s either create a separate, new directory with the same name as our repository, or clear out our local working directory. If we clear out the current directory, we want to remove all the git tracking info, which we can do with the following:" }, { "code": null, "e": 3579, "s": 3545, "text": "# Remove git trackingrm -rf .git*" }, { "code": null, "e": 3718, "s": 3579, "text": "Now, let’s re-clone our repository into a subdirectory. We’ll call this directory source and it will be where we keep all our source code." }, { "code": null, "e": 3776, "s": 3718, "text": "git clone https://github.com/<username>/<reponame> source" }, { "code": null, "e": 3964, "s": 3776, "text": "You will notice that you now have a folder called source with all the files from the master branch. Now let’s create a new directory called gh-pages that will house all our website files:" }, { "code": null, "e": 3979, "s": 3964, "text": "mkdir gh-pages" }, { "code": null, "e": 4012, "s": 3979, "text": "Navigate into the source folder:" }, { "code": null, "e": 4023, "s": 4012, "text": "cd source/" }, { "code": null, "e": 4118, "s": 4023, "text": "Now, we use worktree and make our gh-pages directory correspond to the remote gh-pages branch." }, { "code": null, "e": 4156, "s": 4118, "text": "git worktree add ../gh-pages gh-pages" }, { "code": null, "e": 4442, "s": 4156, "text": "And you’re done! Now, you will notice that when you go to the gh-pages directory, you will only see the files on the gh-pages branch, and if you run a git branch command, you will see that you are on the master when in the source directory, and gh-pages when in the gh-pages directory." }, { "code": null, "e": 4594, "s": 4442, "text": "You can now freely edit both your repository website and source code at the same time, and you have an awesome landing page for your project on GitHub!" } ]
ES6 | Environment Setup - GeeksforGeeks
05 Aug, 2021 ES6 can run on local machines, only it needs a browser and a text editor. Otherwise, ES6 can run on any host, on any OS. For ES6, it may not be an all-time execute on the browsers. So we need some extra mechanism to executes the ES6 version. NodeJS Code Editor Browser NodeJS: For web server, NodeJS is an open-source, cross-platform, JavaScript run-time environment that executes JavaScript code outside of a browser. To install the NodeJS in your machine follow the below links. Installation of Node.js on Windows Installation of Node.js on Linux Code Editor: To write the executable code we will require a text editor. In my opinion, VS code editor is the first choice you can choose. To install VS Code follow the below links. First, you have to download and install the Visual Studio. For that, you can refer to Downloading and Installing Visual Studio. Browser: To run the ES6 program. I prefer to use Google Chrome, there are so many other browsers like Firefox, Internet Explorer, Safari.Execute the ES6 code: Step 1: Now make a folder anywhere of your PC and run command prompt in that folder and make a HTML file by using VS Code editor paste the below code inside the file and save it. html <!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"/> <title>hello world!</title> </head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> </body></html> Step 2: Then write the below command in the command prompt, and hit enter. npm install http-server -g npm is a package manager for the JavaScript programming, by default it is provided by the NodeJS. Full form of npm is Node Package manager. It has many libraries and we can easily use them by Node. here we are use a library http-server to establish server. Step 3: Then, after the installation below command will turn on the server. http-server -p 1234 //1234 is a random port number Step 4: After that, open your browser and write below URL in the search box. Then, the HTML page you make earlier after making the folder will show on the web. localhost:1234/filename.html surinderdawra388 ES6 JavaScript-Misc Picked JavaScript Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to filter object array based on attributes? Installation of Node.js on Linux Node.js fs.readFileSync() Method How to update Node.js and NPM to next version ? Node.js fs.readFile() Method Node.js fs.writeFile() Method
[ { "code": null, "e": 25560, "s": 25532, "text": "\n05 Aug, 2021" }, { "code": null, "e": 25804, "s": 25560, "text": "ES6 can run on local machines, only it needs a browser and a text editor. Otherwise, ES6 can run on any host, on any OS. For ES6, it may not be an all-time execute on the browsers. So we need some extra mechanism to executes the ES6 version. " }, { "code": null, "e": 25811, "s": 25804, "text": "NodeJS" }, { "code": null, "e": 25823, "s": 25811, "text": "Code Editor" }, { "code": null, "e": 25831, "s": 25823, "text": "Browser" }, { "code": null, "e": 26045, "s": 25831, "text": "NodeJS: For web server, NodeJS is an open-source, cross-platform, JavaScript run-time environment that executes JavaScript code outside of a browser. To install the NodeJS in your machine follow the below links. " }, { "code": null, "e": 26080, "s": 26045, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 26113, "s": 26080, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26296, "s": 26113, "text": "Code Editor: To write the executable code we will require a text editor. In my opinion, VS code editor is the first choice you can choose. To install VS Code follow the below links. " }, { "code": null, "e": 26424, "s": 26296, "text": "First, you have to download and install the Visual Studio. For that, you can refer to Downloading and Installing Visual Studio." }, { "code": null, "e": 26585, "s": 26424, "text": "Browser: To run the ES6 program. I prefer to use Google Chrome, there are so many other browsers like Firefox, Internet Explorer, Safari.Execute the ES6 code: " }, { "code": null, "e": 26766, "s": 26585, "text": "Step 1: Now make a folder anywhere of your PC and run command prompt in that folder and make a HTML file by using VS Code editor paste the below code inside the file and save it. " }, { "code": null, "e": 26771, "s": 26766, "text": "html" }, { "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\"/> <title>hello world!</title> </head> <body> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> </body></html>", "e": 27179, "s": 26771, "text": null }, { "code": null, "e": 27256, "s": 27179, "text": "Step 2: Then write the below command in the command prompt, and hit enter. " }, { "code": null, "e": 27283, "s": 27256, "text": "npm install http-server -g" }, { "code": null, "e": 27542, "s": 27283, "text": "npm is a package manager for the JavaScript programming, by default it is provided by the NodeJS. Full form of npm is Node Package manager. It has many libraries and we can easily use them by Node. here we are use a library http-server to establish server. " }, { "code": null, "e": 27620, "s": 27542, "text": "Step 3: Then, after the installation below command will turn on the server. " }, { "code": null, "e": 27671, "s": 27620, "text": "http-server -p 1234\n//1234 is a random port number" }, { "code": null, "e": 27835, "s": 27673, "text": "Step 4: After that, open your browser and write below URL in the search box. Then, the HTML page you make earlier after making the folder will show on the web. " }, { "code": null, "e": 27864, "s": 27835, "text": "localhost:1234/filename.html" }, { "code": null, "e": 27885, "s": 27868, "text": "surinderdawra388" }, { "code": null, "e": 27889, "s": 27885, "text": "ES6" }, { "code": null, "e": 27905, "s": 27889, "text": "JavaScript-Misc" }, { "code": null, "e": 27912, "s": 27905, "text": "Picked" }, { "code": null, "e": 27923, "s": 27912, "text": "JavaScript" }, { "code": null, "e": 27931, "s": 27923, "text": "Node.js" }, { "code": null, "e": 27948, "s": 27931, "text": "Web Technologies" }, { "code": null, "e": 28046, "s": 27948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28107, "s": 28046, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28148, "s": 28107, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28188, "s": 28148, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28242, "s": 28188, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28290, "s": 28242, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 28323, "s": 28290, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28356, "s": 28323, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 28404, "s": 28356, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28433, "s": 28404, "text": "Node.js fs.readFile() Method" } ]
Differentiate between Ambiguous and Unambiguous Grammar
Before understanding the differences between ambiguous grammar and unambiguous grammar, let us learn about these concepts. A grammar is said to be ambiguous if there exists more than one left most derivation or more than one right most derivation or more than one parse tree for a given input string. If the grammar is not ambiguous then we call unambiguous grammar If the grammar is not ambiguous then we call unambiguous grammar If the grammar has ambiguity then it is good for compiler construction If the grammar has ambiguity then it is good for compiler construction No method can automatically detect and remove the ambiguity, but we can remove the ambiguity by re-writing the whole grammar without ambiguity. No method can automatically detect and remove the ambiguity, but we can remove the ambiguity by re-writing the whole grammar without ambiguity. Let us consider a grammar with production rules − E=I E=E+E E=E*E E=(E) E= ε|0|1|2|3......9 A grammar can be unambiguous if the grammar does not contain ambiguity that means if it does not contain more than one left most derivation or more than one right most derivation or more than one parse tree for the given input string. S -> AB A -> Aa / a B -> b The major differences between ambiguous and unambiguous grammar are as follows −
[ { "code": null, "e": 1185, "s": 1062, "text": "Before understanding the differences between ambiguous grammar and unambiguous grammar, let us learn about these concepts." }, { "code": null, "e": 1363, "s": 1185, "text": "A grammar is said to be ambiguous if there exists more than one left most derivation or more than one right most derivation or more than one parse tree for a given input string." }, { "code": null, "e": 1428, "s": 1363, "text": "If the grammar is not ambiguous then we call unambiguous grammar" }, { "code": null, "e": 1493, "s": 1428, "text": "If the grammar is not ambiguous then we call unambiguous grammar" }, { "code": null, "e": 1564, "s": 1493, "text": "If the grammar has ambiguity then it is good for compiler construction" }, { "code": null, "e": 1635, "s": 1564, "text": "If the grammar has ambiguity then it is good for compiler construction" }, { "code": null, "e": 1779, "s": 1635, "text": "No method can automatically detect and remove the ambiguity, but we can remove the ambiguity by re-writing the whole grammar without ambiguity." }, { "code": null, "e": 1923, "s": 1779, "text": "No method can automatically detect and remove the ambiguity, but we can remove the ambiguity by re-writing the whole grammar without ambiguity." }, { "code": null, "e": 1973, "s": 1923, "text": "Let us consider a grammar with production rules −" }, { "code": null, "e": 2015, "s": 1973, "text": "E=I\nE=E+E\nE=E*E\nE=(E)\nE= ε|0|1|2|3......9" }, { "code": null, "e": 2250, "s": 2015, "text": "A grammar can be unambiguous if the grammar does not contain ambiguity that means if it does not contain more than one left most derivation or more than one right most derivation or more than one parse tree for the given input string." }, { "code": null, "e": 2277, "s": 2250, "text": "S -> AB\nA -> Aa / a\nB -> b" }, { "code": null, "e": 2358, "s": 2277, "text": "The major differences between ambiguous and unambiguous grammar are as follows −" } ]
Geek and Code | Practice | GeeksforGeeks
Geek's file currently has zero lines of codes. Each morning geek can add some arbitrary lines of code(possibly zero too). Each night, each line of the code splits into two lines. Geek wants N lines of code at some moment. Find the minimum lines of code geek adds. Input: 1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. 2. The first line of each test case contains a single integer N. Output: For each test case, print the answer Constraints: 1. 1 <= T <= 105 2. 1 <= N <= 109 Example: Input: 2 14 1 Output: 3 1 Explanation: Test Case 1: The first-morning geek can add one line of code, then in the next morning geek file will contain 2 lines of code, and then geek again can add one line of code, then in the next morning geek file will contain 6 lines of code and then geek again can add one line of code, then in the next morning geek file will contain 14. So, in the whole process geek adds 3 lines of code. -1 ankitparashxr3 months ago java Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t!=0) { int count = 0; int n = sc.nextInt(); String str = Integer.toBinaryString(n); for(int i =0;i<str.length();i++) { if(str.charAt(i)=='1') { count++; } } System.out.println(count); t--; 0 chessnoobdj4 months ago Easy c++ #include<iostream> using namespace std; int main(){ int t; cin >> t; while(t--){ int n = 0; cin >> n; int cnt = 0; while(n&(n-1)){ if(n%2 == 0) n /= 2; else{ n -= 1; cnt += 1; } } cout << cnt+1 << "\n"; } return 0; } 0 amitsharmacode5 months ago int main() {int T,N[100000],num,i,j,count;//codescanf("%d",&T);for(i=0;i<T;i++){ scanf("%d",&N[i]);}for(i=0;i<T;i++){ count=0; num = N[i]; for(j=0;j<32;j++) { if((num>>j)&1) count++; } printf("%d\n",count); }return 0;} -1 c1phani1simha6 months ago #include<iostream>#include<bits/stdc++.h>using namespace std;int main(){int t,x;cin>>t;while(t--){ cin>>x; cout<<__builtin_popcount(x)<<endl;}return 0;} 0 Amit Singh Negi11 months ago Amit Singh Negi https://uploads.disquscdn.c... 0 KARAN RANSING1 year ago KARAN RANSING int main(){ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);int t=1;cin>>t;while(t--){ll n;cin>>n;ll ans=0;while(n!=0){ if((n&1)) ans++; n>>=1;}cout<<ans<<"\n"; }="" }=""> 0 mscodi1 year ago mscodi #include<stdio.h>int bin(unsigned n){ int m=0,temp=0; while(n!=0){ temp=n%2; if(temp==1) m++; n=n/2; } return m; }int main(){ int n, t=0,m=0;scanf("%d",&t); while(t--){ scanf("%d",&n); m=bin(n); printf("%d\n",m);}} 0 codeblooded mkv1 year ago codeblooded mkv int main() {cin>>t;while(t--){ int n; cin>>n; int count; for(unsigned int i=0;i<n;i++) {="" i="i+1;" i="2*i;" count++;="" if(i="">n) {cout<<count; count="0;" break;="" }="" }="" }="" return="" 0;="" }="" why="" it's="" giving="" wrong="" answers="" here="" it="" works="" fine="" on="" other="" g++=""> We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 491, "s": 226, "text": "Geek's file currently has zero lines of codes. Each morning geek can add some arbitrary lines of code(possibly zero too). Each night, each line of the code splits into two lines. Geek wants N lines of code at some moment. Find the minimum lines of code geek adds. " }, { "code": null, "e": 700, "s": 491, "text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains a single integer N." }, { "code": null, "e": 819, "s": 700, "text": "\nOutput: For each test case, print the answer\n\nConstraints:\n1. 1 <= T <= 105\n2. 1 <= N <= 109\n\nExample:\nInput:\n2\n14\n1" }, { "code": null, "e": 1233, "s": 819, "text": "Output:\n3\n1\n\nExplanation:\nTest Case 1: The first-morning geek can add one line of code, then in the next morning geek file will contain 2 lines of code, and then geek again can add one line of code, then in the next morning geek file will contain 6 lines of code and then geek again can add one line of code, then in the next morning geek file will contain 14. So, in the whole process geek adds 3 lines of code. " }, { "code": null, "e": 1236, "s": 1233, "text": "-1" }, { "code": null, "e": 1262, "s": 1236, "text": "ankitparashxr3 months ago" }, { "code": null, "e": 1267, "s": 1262, "text": "java" }, { "code": null, "e": 1620, "s": 1267, "text": "Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t!=0) { int count = 0; int n = sc.nextInt(); String str = Integer.toBinaryString(n); for(int i =0;i<str.length();i++) { if(str.charAt(i)=='1') { count++; } } System.out.println(count); t--;" }, { "code": null, "e": 1622, "s": 1620, "text": "0" }, { "code": null, "e": 1646, "s": 1622, "text": "chessnoobdj4 months ago" }, { "code": null, "e": 1655, "s": 1646, "text": "Easy c++" }, { "code": null, "e": 2025, "s": 1655, "text": "#include<iostream>\nusing namespace std;\n\nint main(){\n int t;\n cin >> t;\n while(t--){\n int n = 0;\n cin >> n;\n int cnt = 0;\n while(n&(n-1)){\n if(n%2 == 0)\n n /= 2;\n else{\n n -= 1;\n cnt += 1;\n }\n }\n cout << cnt+1 << \"\\n\";\n }\n return 0;\n}" }, { "code": null, "e": 2027, "s": 2025, "text": "0" }, { "code": null, "e": 2054, "s": 2027, "text": "amitsharmacode5 months ago" }, { "code": null, "e": 2306, "s": 2054, "text": "int main() {int T,N[100000],num,i,j,count;//codescanf(\"%d\",&T);for(i=0;i<T;i++){ scanf(\"%d\",&N[i]);}for(i=0;i<T;i++){ count=0; num = N[i]; for(j=0;j<32;j++) { if((num>>j)&1) count++; } printf(\"%d\\n\",count); }return 0;}" }, { "code": null, "e": 2309, "s": 2306, "text": "-1" }, { "code": null, "e": 2335, "s": 2309, "text": "c1phani1simha6 months ago" }, { "code": null, "e": 2494, "s": 2335, "text": "#include<iostream>#include<bits/stdc++.h>using namespace std;int main(){int t,x;cin>>t;while(t--){ cin>>x; cout<<__builtin_popcount(x)<<endl;}return 0;}" }, { "code": null, "e": 2496, "s": 2494, "text": "0" }, { "code": null, "e": 2525, "s": 2496, "text": "Amit Singh Negi11 months ago" }, { "code": null, "e": 2541, "s": 2525, "text": "Amit Singh Negi" }, { "code": null, "e": 2572, "s": 2541, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 2574, "s": 2572, "text": "0" }, { "code": null, "e": 2598, "s": 2574, "text": "KARAN RANSING1 year ago" }, { "code": null, "e": 2612, "s": 2598, "text": "KARAN RANSING" }, { "code": null, "e": 2809, "s": 2612, "text": "int main(){ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);int t=1;cin>>t;while(t--){ll n;cin>>n;ll ans=0;while(n!=0){ if((n&1)) ans++; n>>=1;}cout<<ans<<\"\\n\"; }=\"\" }=\"\">" }, { "code": null, "e": 2811, "s": 2809, "text": "0" }, { "code": null, "e": 2828, "s": 2811, "text": "mscodi1 year ago" }, { "code": null, "e": 2835, "s": 2828, "text": "mscodi" }, { "code": null, "e": 3111, "s": 2835, "text": "#include<stdio.h>int bin(unsigned n){ int m=0,temp=0; while(n!=0){ temp=n%2; if(temp==1) m++; n=n/2; } return m; }int main(){ int n, t=0,m=0;scanf(\"%d\",&t); while(t--){ scanf(\"%d\",&n); m=bin(n); printf(\"%d\\n\",m);}}" }, { "code": null, "e": 3113, "s": 3111, "text": "0" }, { "code": null, "e": 3139, "s": 3113, "text": "codeblooded mkv1 year ago" }, { "code": null, "e": 3155, "s": 3139, "text": "codeblooded mkv" }, { "code": null, "e": 3186, "s": 3155, "text": "int main() {cin>>t;while(t--){" }, { "code": null, "e": 3478, "s": 3186, "text": " int n; cin>>n; int count; for(unsigned int i=0;i<n;i++) {=\"\" i=\"i+1;\" i=\"2*i;\" count++;=\"\" if(i=\"\">n) {cout<<count; count=\"0;\" break;=\"\" }=\"\" }=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\" why=\"\" it's=\"\" giving=\"\" wrong=\"\" answers=\"\" here=\"\" it=\"\" works=\"\" fine=\"\" on=\"\" other=\"\" g++=\"\">" }, { "code": null, "e": 3624, "s": 3478, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3660, "s": 3624, "text": " Login to access your submissions. " }, { "code": null, "e": 3670, "s": 3660, "text": "\nProblem\n" }, { "code": null, "e": 3680, "s": 3670, "text": "\nContest\n" }, { "code": null, "e": 3743, "s": 3680, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3891, "s": 3743, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4099, "s": 3891, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4205, "s": 4099, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Application Layer
Web applications and web servers are critical to our online presence and the attacks observed against them constitute more than 70% of the total attacks attempted on the Internet. These attacks attempt to convert trusted websites into malicious ones. Due to this reason, web server and web application pen testing plays an important role. Why do we need to consider the safety of web servers? It is because with the rapid growth of e-commerce industry, the prime target of attackers is web server. For web server pentesting, we must know about web server, its hosting software & operating systems along with the applications, which are running on them. Gathering such information about web server is called footprinting of web server. In our subsequent section, we will discuss the different methods for footprinting of a web server. Web servers are server software or hardware dedicated to handle requests and serve responses. This is a key area for a pentester to focus on while doing penetration testing of web servers. Let us now discuss a few methods, implemented in Python, which can be executed for footprinting of a web server − A very good practice for a penetration tester is to start by listing the various available HTTP methods. Following is a Python script with the help of which we can connect to the target web server and enumerate the available HTTP methods − To begin with, we need to import the requests library − import requests After importing the requests library, create an array of HTTP methods, which we are going to send. We will make use of some standard methods like 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' and a non-standard method ‘TEST’ to check how a web server can handle the unexpected input. method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST'] The following line of code is the main loop of the script, which will send the HTTP packets to the web server and print the method and the status code. for method in method_list: req = requests.request(method, 'Enter the URL’) print (method, req.status_code, req.reason) The next line will test for the possibility of cross site tracing (XST) by sending the TRACE method. if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text: print ('Cross Site Tracing(XST) is possible') After running the above script for a particular web server, we will get 200 OK responses for a particular method accepted by the web server. We will get a 403 Forbidden response if the web server explicitly denies the method. Once we send the TRACE method for testing cross site tracing (XST), we will get 405 Not Allowed responses from the web server otherwise we will get the message ‘Cross Site Tracing(XST) is possible’. HTTP headers are found in both requests and responses from the web server. They also carry very important information about servers. That is why penetration tester is always interested in parsing information through HTTP headers. Following is a Python script for getting the information about headers of the web server − To begin with, let us import the requests library − import requests We need to send a GET request to the web server. The following line of code makes a simple GET request through the requests library. request = requests.get('enter the URL') Next, we will generate a list of headers about which you need the information. header_list = [ 'Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', ‘Connection’, ‘Content-Length’] Next is a try and except block. for header in header_list: try: result = request.header_list[header] print ('%s: %s' % (header, result)) except Exception as err: print ('%s: No Details Found' % header) After running the above script for a particular web server, we will get the information about the headers provided in the header list. If there will be no information for a particular header then it will give the message ‘No Details Found’. You can also learn more about HTTP_header fields from the link — https://www.tutorialspoint.com/http/http_header_fields.htm. We can use HTTP header information to test insecure web server configurations. In the following Python script, we are going to use try/except block to test insecure web server headers for number of URLs that are saved in a text file name websites.txt − import requests urls = open("websites.txt", "r") for url in urls: url = url.strip() req = requests.get(url) print (url, 'report:') try: protection_xss = req.headers['X-XSS-Protection'] if protection_xss != '1; mode = block': print ('X-XSS-Protection not set properly, it may be possible:', protection_xss) except: print ('X-XSS-Protection not set, it may be possible') try: options_content_type = req.headers['X-Content-Type-Options'] if options_content_type != 'nosniff': print ('X-Content-Type-Options not set properly:', options_content_type) except: print ('X-Content-Type-Options not set') try: transport_security = req.headers['Strict-Transport-Security'] except: print ('HSTS header not set properly, Man in the middle attacks is possible') try: content_security = req.headers['Content-Security-Policy'] print ('Content-Security-Policy set:', content_security) except: print ('Content-Security-Policy missing') In our previous section, we discussed footprinting of a web server. Similarly, footprinting of a web application is also considered important from the point of view of a penetration tester. In our subsequent section, we will learn about the different methods for footprinting of a web application. Web application is a client-server program, which is run by the client in a web server. This is another key area for a pentester to focus on while doing penetration testing of web application. Let us now discuss the different methods, implemented in Python, which can be used for footprinting of a web application − Suppose we want to collect all the hyperlinks from a web page; we can make use of a parser called BeautifulSoup. The parser is a Python library for pulling data out of HTML and XML files. It can be used with urlib because it needs an input (document or url) to create a soup object and it can’t fetch web page by itself. To begin with, let us import the necessary packages. We will import urlib and BeautifulSoup. Remember before importing BeautifulSoup, we need to install it. import urllib from bs4 import BeautifulSoup The Python script given below will gather the title of web page and hyperlinks − Now, we need a variable, which can store the URL of the website. Here, we will use a variable named ‘url’. We will also use the page.read() function that can store the web page and assign the web page to the variable html_page. url = raw_input("Enter the URL ") page = urllib.urlopen(url) html_page = page.read() The html_page will be assigned as an input to create soup object. soup_object = BeautifulSoup(html_page) Following two lines will print the title name with tags and without tags respectively. print soup_object.title print soup_object.title.text The line of code shown below will save all the hyperlinks. for link in soup_object.find_all('a'): print(link.get('href')) Banner is like a text message that contains information about the server and banner grabbing is the process of fetching that information provided by the banner itself. Now, we need to know how this banner is generated. It is generated by the header of the packet that is sent. And while the client tries to connect to a port, the server responds because the header contains information about the server. The following Python script helps grab the banner using socket programming − import socket s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0800)) targethost = str(raw_input("Enter the host name: ")) targetport = int(raw_input("Enter Port: ")) s.connect((targethost,targetport)) def garb(s:) try: s.send('GET HTTP/1.1 \r\n') ret = sock.recv(1024) print ('[+]' + str(ret)) return except Exception as error: print ('[-]' Not information grabbed:' + str(error)) return After running the above script, we will get similar kind of information about headers as we got from the Python script of footprinting of HTTP headers in the previous section. 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": 2196, "s": 1857, "text": "Web applications and web servers are critical to our online presence and the attacks observed against them constitute more than 70% of the total attacks attempted on the Internet. These attacks attempt to convert trusted websites into malicious ones. Due to this reason, web server and web application pen testing plays an important role." }, { "code": null, "e": 2592, "s": 2196, "text": "Why do we need to consider the safety of web servers? It is because with the rapid growth of e-commerce industry, the prime target of attackers is web server. For web server pentesting, we must know about web server, its hosting software & operating systems along with the applications, which are running on them. Gathering such information about web server is called footprinting of web server." }, { "code": null, "e": 2691, "s": 2592, "text": "In our subsequent section, we will discuss the different methods for footprinting of a web server." }, { "code": null, "e": 2880, "s": 2691, "text": "Web servers are server software or hardware dedicated to handle requests and serve responses. This is a key area for a pentester to focus on while doing penetration testing of web servers." }, { "code": null, "e": 2994, "s": 2880, "text": "Let us now discuss a few methods, implemented in Python, which can be executed for footprinting of a web server −" }, { "code": null, "e": 3234, "s": 2994, "text": "A very good practice for a penetration tester is to start by listing the various available HTTP methods. Following is a Python script with the help of which we can connect to the target web server and enumerate the available HTTP methods −" }, { "code": null, "e": 3290, "s": 3234, "text": "To begin with, we need to import the requests library −" }, { "code": null, "e": 3307, "s": 3290, "text": "import requests\n" }, { "code": null, "e": 3587, "s": 3307, "text": "After importing the requests library, create an array of HTTP methods, which we are going to send. We will make use of some standard methods like 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS' and a non-standard method ‘TEST’ to check how a web server can handle the unexpected input." }, { "code": null, "e": 3662, "s": 3587, "text": "method_list = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']\n" }, { "code": null, "e": 3814, "s": 3662, "text": "The following line of code is the main loop of the script, which will send the HTTP packets to the web server and print the method and the status code." }, { "code": null, "e": 3939, "s": 3814, "text": "for method in method_list:\n req = requests.request(method, 'Enter the URL’)\n print (method, req.status_code, req.reason)" }, { "code": null, "e": 4040, "s": 3939, "text": "The next line will test for the possibility of cross site tracing (XST) by sending the TRACE method." }, { "code": null, "e": 4146, "s": 4040, "text": "if method == 'TRACE' and 'TRACE / HTTP/1.1' in req.text:\n print ('Cross Site Tracing(XST) is possible')" }, { "code": null, "e": 4571, "s": 4146, "text": "After running the above script for a particular web server, we will get 200 OK responses for a particular method accepted by the web server. We will get a 403 Forbidden response if the web server explicitly denies the method. Once we send the TRACE method for testing cross site tracing (XST), we will get 405 Not Allowed responses from the web server otherwise we will get the message ‘Cross Site Tracing(XST) is possible’." }, { "code": null, "e": 4892, "s": 4571, "text": "HTTP headers are found in both requests and responses from the web server. They also carry very important information about servers. That is why penetration tester is always interested in parsing information through HTTP headers. Following is a Python script for getting the information about headers of the web server −" }, { "code": null, "e": 4944, "s": 4892, "text": "To begin with, let us import the requests library −" }, { "code": null, "e": 4961, "s": 4944, "text": "import requests\n" }, { "code": null, "e": 5094, "s": 4961, "text": "We need to send a GET request to the web server. The following line of code makes a simple GET request through the requests library." }, { "code": null, "e": 5135, "s": 5094, "text": "request = requests.get('enter the URL')\n" }, { "code": null, "e": 5214, "s": 5135, "text": "Next, we will generate a list of headers about which you need the information." }, { "code": null, "e": 5325, "s": 5214, "text": "header_list = [\n 'Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code', ‘Connection’, ‘Content-Length’]\n" }, { "code": null, "e": 5357, "s": 5325, "text": "Next is a try and except block." }, { "code": null, "e": 5551, "s": 5357, "text": "for header in header_list:\n try:\n result = request.header_list[header]\n print ('%s: %s' % (header, result))\n except Exception as err:\n print ('%s: No Details Found' % header)" }, { "code": null, "e": 5917, "s": 5551, "text": "After running the above script for a particular web server, we will get the information about the headers provided in the header list. If there will be no information for a particular header then it will give the message ‘No Details Found’. You can also learn more about HTTP_header fields from the link — https://www.tutorialspoint.com/http/http_header_fields.htm." }, { "code": null, "e": 6170, "s": 5917, "text": "We can use HTTP header information to test insecure web server configurations. In the following Python script, we are going to use try/except block to test insecure web server headers for number of URLs that are saved in a text file name websites.txt −" }, { "code": null, "e": 7225, "s": 6170, "text": "import requests\nurls = open(\"websites.txt\", \"r\")\n\nfor url in urls:\n url = url.strip()\n req = requests.get(url)\n print (url, 'report:')\n \n try:\n protection_xss = req.headers['X-XSS-Protection']\n if protection_xss != '1; mode = block':\n print ('X-XSS-Protection not set properly, it may be possible:', protection_xss)\n except:\n print ('X-XSS-Protection not set, it may be possible')\n \n try:\n options_content_type = req.headers['X-Content-Type-Options']\n if options_content_type != 'nosniff':\n print ('X-Content-Type-Options not set properly:', options_content_type)\n except:\n print ('X-Content-Type-Options not set')\n \n try:\n transport_security = req.headers['Strict-Transport-Security']\n except:\n print ('HSTS header not set properly, Man in the middle attacks is possible')\n \n try:\n content_security = req.headers['Content-Security-Policy']\n print ('Content-Security-Policy set:', content_security)\n except:\n print ('Content-Security-Policy missing')" }, { "code": null, "e": 7415, "s": 7225, "text": "In our previous section, we discussed footprinting of a web server. Similarly, footprinting of a web application is also considered important from the point of view of a penetration tester." }, { "code": null, "e": 7523, "s": 7415, "text": "In our subsequent section, we will learn about the different methods for footprinting of a web application." }, { "code": null, "e": 7716, "s": 7523, "text": "Web application is a client-server program, which is run by the client in a web server. This is another key area for a pentester to focus on while doing penetration testing of web application." }, { "code": null, "e": 7839, "s": 7716, "text": "Let us now discuss the different methods, implemented in Python, which can be used for footprinting of a web application −" }, { "code": null, "e": 8160, "s": 7839, "text": "Suppose we want to collect all the hyperlinks from a web page; we can make use of a parser called BeautifulSoup. The parser is a Python library for pulling data out of HTML and XML files. It can be used with urlib because it needs an input (document or url) to create a soup object and it can’t fetch web page by itself." }, { "code": null, "e": 8317, "s": 8160, "text": "To begin with, let us import the necessary packages. We will import urlib and BeautifulSoup. Remember before importing BeautifulSoup, we need to install it." }, { "code": null, "e": 8362, "s": 8317, "text": "import urllib\nfrom bs4 import BeautifulSoup\n" }, { "code": null, "e": 8443, "s": 8362, "text": "The Python script given below will gather the title of web page and hyperlinks −" }, { "code": null, "e": 8671, "s": 8443, "text": "Now, we need a variable, which can store the URL of the website. Here, we will use a variable named ‘url’. We will also use the page.read() function that can store the web page and assign the web page to the variable html_page." }, { "code": null, "e": 8757, "s": 8671, "text": "url = raw_input(\"Enter the URL \")\npage = urllib.urlopen(url)\nhtml_page = page.read()\n" }, { "code": null, "e": 8823, "s": 8757, "text": "The html_page will be assigned as an input to create soup object." }, { "code": null, "e": 8863, "s": 8823, "text": "soup_object = BeautifulSoup(html_page)\n" }, { "code": null, "e": 8950, "s": 8863, "text": "Following two lines will print the title name with tags and without tags respectively." }, { "code": null, "e": 9004, "s": 8950, "text": "print soup_object.title\nprint soup_object.title.text\n" }, { "code": null, "e": 9063, "s": 9004, "text": "The line of code shown below will save all the hyperlinks." }, { "code": null, "e": 9129, "s": 9063, "text": "for link in soup_object.find_all('a'):\n print(link.get('href'))" }, { "code": null, "e": 9533, "s": 9129, "text": "Banner is like a text message that contains information about the server and banner grabbing is the process of fetching that information provided by the banner itself. Now, we need to know how this banner is generated. It is generated by the header of the packet that is sent. And while the client tries to connect to a port, the server responds because the header contains information about the server." }, { "code": null, "e": 9610, "s": 9533, "text": "The following Python script helps grab the banner using socket programming −" }, { "code": null, "e": 10062, "s": 9610, "text": "import socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket. htons(0x0800))\n\ntargethost = str(raw_input(\"Enter the host name: \"))\ntargetport = int(raw_input(\"Enter Port: \"))\ns.connect((targethost,targetport))\n\ndef garb(s:)\n try:\n s.send('GET HTTP/1.1 \\r\\n')\n ret = sock.recv(1024)\n print ('[+]' + str(ret))\n return\n except Exception as error:\n print ('[-]' Not information grabbed:' + str(error))\n return" }, { "code": null, "e": 10238, "s": 10062, "text": "After running the above script, we will get similar kind of information about headers as we got from the Python script of footprinting of HTTP headers in the previous section." }, { "code": null, "e": 10275, "s": 10238, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 10291, "s": 10275, "text": " Malhar Lathkar" }, { "code": null, "e": 10324, "s": 10291, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 10343, "s": 10324, "text": " Arnab Chakraborty" }, { "code": null, "e": 10378, "s": 10343, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 10400, "s": 10378, "text": " In28Minutes Official" }, { "code": null, "e": 10434, "s": 10400, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 10462, "s": 10434, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10497, "s": 10462, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 10511, "s": 10497, "text": " Lets Kode It" }, { "code": null, "e": 10544, "s": 10511, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 10561, "s": 10544, "text": " Abhilash Nelson" }, { "code": null, "e": 10568, "s": 10561, "text": " Print" }, { "code": null, "e": 10579, "s": 10568, "text": " Add Notes" } ]
Rotating an Array | Practice | GeeksforGeeks
Given an array of size N. The task is to rotate array by D elements where D ≤ N. Example 1: Input: N = 7 Arr[] = {1, 2, 3, 4, 5, 6, 7} D = 2 Output: 3 4 5 6 7 1 2 Explanation: Rotate by 1: [2, 3, 4, 5, 6, 7, 1] Rotate by 2: [3, 4, 5, 6, 7, 1, 2] Example 2: Input: N = 4 Arr[] = {1, 3, 4, 2} D = 3 Output: 2 1 3 4 Your Task: You don't need to read input or print anything. Your task is to complete the function leftRotate() which takes the array of integers arr[], its size n and d as input parameters and rotates arr[] in-place without using any extra memory. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 105 1 ≤ Arr[i] ≤ 1000 0 ≤ D ≤ N 0 arvind16yadav17 hours ago /*JAVA CODE*/ void leftRotate(int[] arr, int n, int d) { // code here int brr[] = new int[d]; for(int i=0; i<d; i++){ brr[i] = arr[i]; } for(int i=d; i<n; i++){ arr[i-d] = arr[i]; } for(int i=0; i<d; i++){ arr[n-d+i] = brr[i]; } } 0 darshananimus3 days ago More optimized approach n/2 = time complexity class Solution { static int[] reverseArray(int[] arr,int start,int end) { int temp=0; int mid = (start+end)/2; for(int i=start;i<=mid;i++) { temp=arr[i]; arr[i]=arr[end]; arr[end]=temp; end--; } // while(start<end) // { // temp=arr[start]; // arr[start]=arr[end]; // arr[end]=temp; // start++; // end--; // } return arr; } void leftRotate(int[] arr, int n, int d) { if(d>0)//corner case handling reverseArray(arr,0,d-1); reverseArray(arr,d,n-1); reverseArray(arr,0,n-1); } } 0 polamreddyn6 days ago class Solution { void leftRotate(int arr[], int n, int d) { // code here d%=n; rotation(arr, 0, d-1); rotation(arr, d, n-1); rotation(arr, 0, n-1);} void rotation(int array[], int start, int end) { int temp; while(start < end) { temp = array[start]; array[start] = array[end]; array[end] = temp; start++; end --; } } 0 div20 This comment was deleted. +1 surajpatil39412 weeks ago Simple One line approach in C++ rotate(arr, arr+d, arr+n); 0 akshayjamodkar3 weeks ago Using reversing 0 sahillather0023 weeks ago Simple way for rotation of array using RECURSIVE Calls: void reverse(int arr[],int low,int high){ int temp; while(low<high){ temp = arr[low]; arr[low]=arr[high]; arr[high]=temp; low++; high--; } } void leftRotate(int arr[], int n, int d) { // code here reverse(arr,d,n-1); reverse(arr,0,d-1); reverse(arr,0,n-1);} 0 dheerukd20023 weeks ago C++ Solution : Time=O(n) Space=O(1) void leftRotate(int arr[], int n, int d) { // For preserving the original element int M=*max_element(arr,arr+n)+1; //Now we contain both original(obtained by e%M) and required elements(obtained by e/M) in each array element. for(int i=0;i<n;i++){ arr[i]+=(arr[(i+d)%n]%M)*M; } for(int i=0;i<n;i++){ arr[i]/=M; } } 0 hasnainraza1998hr1 month ago C++, 0.1 void leftRotate(int arr[], int n, int d) { int brr[d]; int index = 0; for(int i=0;i<d;i++){ brr[i]=arr[i]; } for(;index<n-d;index++){ arr[index]=arr[index+d]; } for(int i=0;i<d;i++){ arr[index++]=brr[i]; }} +3 amiransarimy1 month ago One Line Solutions def leftRotate(self, arr, n, d): arr[:] = arr[d:]+arr[:d] We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 319, "s": 238, "text": "Given an array of size N. The task is to rotate array by D elements where D ≤ N." }, { "code": null, "e": 330, "s": 319, "text": "Example 1:" }, { "code": null, "e": 486, "s": 330, "text": "Input:\nN = 7\nArr[] = {1, 2, 3, 4, 5, 6, 7}\nD = 2\nOutput: 3 4 5 6 7 1 2\nExplanation: \nRotate by 1: [2, 3, 4, 5, 6, 7, 1]\nRotate by 2: [3, 4, 5, 6, 7, 1, 2]\n" }, { "code": null, "e": 498, "s": 486, "text": "\nExample 2:" }, { "code": null, "e": 556, "s": 498, "text": "Input:\nN = 4\nArr[] = {1, 3, 4, 2}\nD = 3\nOutput: 2 1 3 4\n\n" }, { "code": null, "e": 803, "s": 556, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function leftRotate() which takes the array of integers arr[], its size n and d as input parameters and rotates arr[] in-place without using any extra memory." }, { "code": null, "e": 866, "s": 803, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 920, "s": 866, "text": "\nConstraints:\n1 ≤ N ≤ 105\n1 ≤ Arr[i] ≤ 1000\n0 ≤ D ≤ N" }, { "code": null, "e": 924, "s": 922, "text": "0" }, { "code": null, "e": 950, "s": 924, "text": "arvind16yadav17 hours ago" }, { "code": null, "e": 964, "s": 950, "text": "/*JAVA CODE*/" }, { "code": null, "e": 1296, "s": 964, "text": "void leftRotate(int[] arr, int n, int d) { // code here int brr[] = new int[d]; for(int i=0; i<d; i++){ brr[i] = arr[i]; } for(int i=d; i<n; i++){ arr[i-d] = arr[i]; } for(int i=0; i<d; i++){ arr[n-d+i] = brr[i]; } }" }, { "code": null, "e": 1298, "s": 1296, "text": "0" }, { "code": null, "e": 1322, "s": 1298, "text": "darshananimus3 days ago" }, { "code": null, "e": 2079, "s": 1322, "text": "More optimized approach\nn/2 = time complexity\nclass Solution {\n static int[] reverseArray(int[] arr,int start,int end)\n {\n int temp=0;\n int mid = (start+end)/2;\n for(int i=start;i<=mid;i++)\n {\n temp=arr[i];\n arr[i]=arr[end];\n arr[end]=temp;\n end--;\n }\n // while(start<end)\n // {\n // temp=arr[start];\n // arr[start]=arr[end];\n // arr[end]=temp;\n // start++;\n // end--;\n // }\n return arr;\n }\n void leftRotate(int[] arr, int n, int d) {\n if(d>0)//corner case handling\n reverseArray(arr,0,d-1);\n reverseArray(arr,d,n-1);\n reverseArray(arr,0,n-1);\n }\n}" }, { "code": null, "e": 2081, "s": 2079, "text": "0" }, { "code": null, "e": 2103, "s": 2081, "text": "polamreddyn6 days ago" }, { "code": null, "e": 2272, "s": 2103, "text": "class Solution { void leftRotate(int arr[], int n, int d) { // code here d%=n; rotation(arr, 0, d-1); rotation(arr, d, n-1); rotation(arr, 0, n-1);}" }, { "code": null, "e": 2494, "s": 2272, "text": "void rotation(int array[], int start, int end) { int temp; while(start < end) { temp = array[start]; array[start] = array[end]; array[end] = temp; start++; end --; } }" }, { "code": null, "e": 2496, "s": 2494, "text": "0" }, { "code": null, "e": 2502, "s": 2496, "text": "div20" }, { "code": null, "e": 2528, "s": 2502, "text": "This comment was deleted." }, { "code": null, "e": 2531, "s": 2528, "text": "+1" }, { "code": null, "e": 2557, "s": 2531, "text": "surajpatil39412 weeks ago" }, { "code": null, "e": 2589, "s": 2557, "text": "Simple One line approach in C++" }, { "code": null, "e": 2618, "s": 2591, "text": "rotate(arr, arr+d, arr+n);" }, { "code": null, "e": 2620, "s": 2618, "text": "0" }, { "code": null, "e": 2646, "s": 2620, "text": "akshayjamodkar3 weeks ago" }, { "code": null, "e": 2663, "s": 2646, "text": "Using reversing " }, { "code": null, "e": 2665, "s": 2663, "text": "0" }, { "code": null, "e": 2691, "s": 2665, "text": "sahillather0023 weeks ago" }, { "code": null, "e": 2747, "s": 2691, "text": "Simple way for rotation of array using RECURSIVE Calls:" }, { "code": null, "e": 2965, "s": 2747, "text": "void reverse(int arr[],int low,int high){ int temp; while(low<high){ temp = arr[low]; arr[low]=arr[high]; arr[high]=temp; low++; high--; } }" }, { "code": null, "e": 3090, "s": 2965, "text": "void leftRotate(int arr[], int n, int d) { // code here reverse(arr,d,n-1); reverse(arr,0,d-1); reverse(arr,0,n-1);}" }, { "code": null, "e": 3092, "s": 3090, "text": "0" }, { "code": null, "e": 3116, "s": 3092, "text": "dheerukd20023 weeks ago" }, { "code": null, "e": 3152, "s": 3116, "text": "C++ Solution : Time=O(n) Space=O(1)" }, { "code": null, "e": 3537, "s": 3152, "text": "void leftRotate(int arr[], int n, int d) { // For preserving the original element int M=*max_element(arr,arr+n)+1; //Now we contain both original(obtained by e%M) and required elements(obtained by e/M) in each array element. for(int i=0;i<n;i++){ arr[i]+=(arr[(i+d)%n]%M)*M; } for(int i=0;i<n;i++){ arr[i]/=M; } }" }, { "code": null, "e": 3539, "s": 3537, "text": "0" }, { "code": null, "e": 3568, "s": 3539, "text": "hasnainraza1998hr1 month ago" }, { "code": null, "e": 3577, "s": 3568, "text": "C++, 0.1" }, { "code": null, "e": 3818, "s": 3577, "text": "void leftRotate(int arr[], int n, int d) { int brr[d]; int index = 0; for(int i=0;i<d;i++){ brr[i]=arr[i]; } for(;index<n-d;index++){ arr[index]=arr[index+d]; } for(int i=0;i<d;i++){ arr[index++]=brr[i]; }}" }, { "code": null, "e": 3821, "s": 3818, "text": "+3" }, { "code": null, "e": 3845, "s": 3821, "text": "amiransarimy1 month ago" }, { "code": null, "e": 3864, "s": 3845, "text": "One Line Solutions" }, { "code": null, "e": 3930, "s": 3866, "text": "def leftRotate(self, arr, n, d): arr[:] = arr[d:]+arr[:d]" }, { "code": null, "e": 4076, "s": 3930, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 4112, "s": 4076, "text": " Login to access your submissions. " }, { "code": null, "e": 4122, "s": 4112, "text": "\nProblem\n" }, { "code": null, "e": 4132, "s": 4122, "text": "\nContest\n" }, { "code": null, "e": 4195, "s": 4132, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4343, "s": 4195, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4551, "s": 4343, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4657, "s": 4551, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Google Maps - Events
The Google Maps JavaScript program can respond to various events generated by the user. This chapter provides examples demonstrating how to perform event handling while working with Google Maps. You can add an event listener using the method addListener(). It accepts parameters such as object name on which we want to add the listener, name of the event, and the handler event. The following example shows how to add an event listener to a marker object. The program raises the zoom value of the map by 5 each time we double-click on the marker. <!DOCTYPE html> <html> <head> <script src = "https://maps.googleapis.com/maps/api/js"></script> <script> var myCenter = new google.maps.LatLng(17.433053, 78.412172); function loadMap(){ var mapProp = { center: myCenter, zoom:5, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new google.maps.Marker({ position: myCenter, title:'Click to zoom' }); marker.setMap(map); //Zoom to 7 when clicked on marker google.maps.event.addListener(marker,'click',function() { map.setZoom(9); map.setCenter(marker.getPosition()); }); } </script> </head> <body onload = "loadMap()"> <div id = "googleMap" style = "width:580px; height:400px;"></div> </body> </html> It produces the following output − The following code opens an info window on clicking the marker − <!DOCTYPE html> <html> <head> <script src = "https://maps.googleapis.com/maps/api/js"></script> <script> var myCenter = new google.maps.LatLng(17.433053, 78.412172); function loadMap(){ var mapProp = { center:myCenter, zoom:4, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new google.maps.Marker({ position:myCenter, }); marker.setMap(map); var infowindow = new google.maps.InfoWindow({ content:"Hi" }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); } </script> </head> <body onload = "loadMap()"> <div id = "googleMap" style = "width:580px; height:400px;"></div> </body> </html> It produces the following output − You can remove an existing listener using the method removeListener(). This method accepts the listener object, therefore we have to assign the listener to a variable and pass it to this method. The following code shows how to remove a listener − <!DOCTYPE html> <html> <head> <script src = "https://maps.googleapis.com/maps/api/js"></script> <script> var myCenter = new google.maps.LatLng(17.433053, 78.412172); function loadMap(){ var mapProp = { center:myCenter, zoom:4, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap"),mapProp); var marker = new google.maps.Marker({ position:myCenter, }); marker.setMap(map); var infowindow = new google.maps.InfoWindow({ content:"Hi" }); var myListener = google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); google.maps.event.removeListener(myListener); } </script> </head> <body onload = "loadMap()"> <div id = "googleMap" style = "width:580px; height:400px;"></div> </body> </html> It produces the following output − 20 Lectures 2.5 hours Asif Hussain 7 Lectures 1 hours Aditya Kulkarni 33 Lectures 2.5 hours Sasha Miller 22 Lectures 1.5 hours Zach Miller 16 Lectures 1.5 hours Sasha Miller 23 Lectures 2.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2027, "s": 1832, "text": "The Google Maps JavaScript program can respond to various events generated by the user. This chapter provides examples demonstrating how to perform event handling while working with Google Maps." }, { "code": null, "e": 2211, "s": 2027, "text": "You can add an event listener using the method addListener(). It accepts parameters such as object name on which we want to add the listener, name of the event, and the handler event." }, { "code": null, "e": 2379, "s": 2211, "text": "The following example shows how to add an event listener to a marker object. The program raises the zoom value of the map by 5 each time we double-click on the marker." }, { "code": null, "e": 3470, "s": 2379, "text": "<!DOCTYPE html>\n<html>\n \n <head>\n <script src = \"https://maps.googleapis.com/maps/api/js\"></script>\n \n <script>\n var myCenter = new google.maps.LatLng(17.433053, 78.412172);\n function loadMap(){\n\t\t\t\n var mapProp = {\n center: myCenter,\n zoom:5,\n mapTypeId: google.maps.MapTypeId.ROADMAP\n };\n \n var map = new google.maps.Map(document.getElementById(\"googleMap\"),mapProp);\n \n var marker = new google.maps.Marker({\n position: myCenter,\n title:'Click to zoom'\n });\n \n marker.setMap(map);\n \n //Zoom to 7 when clicked on marker\n google.maps.event.addListener(marker,'click',function() {\n map.setZoom(9);\n map.setCenter(marker.getPosition());\n });\n }\n </script>\n \n </head>\n \n <body onload = \"loadMap()\">\n <div id = \"googleMap\" style = \"width:580px; height:400px;\"></div>\n </body>\n \n</html>" }, { "code": null, "e": 3505, "s": 3470, "text": "It produces the following output −" }, { "code": null, "e": 3570, "s": 3505, "text": "The following code opens an info window on clicking the marker −" }, { "code": null, "e": 4652, "s": 3570, "text": "<!DOCTYPE html>\n<html>\n \n <head>\n <script src = \"https://maps.googleapis.com/maps/api/js\"></script>\n \n <script>\n var myCenter = new google.maps.LatLng(17.433053, 78.412172);\n function loadMap(){\n\t\t\t\n var mapProp = {\n center:myCenter,\n zoom:4,\n mapTypeId:google.maps.MapTypeId.ROADMAP\n };\n \n var map = new google.maps.Map(document.getElementById(\"googleMap\"),mapProp);\n \n var marker = new google.maps.Marker({\n position:myCenter,\n });\n \n marker.setMap(map);\n \n var infowindow = new google.maps.InfoWindow({\n content:\"Hi\"\n });\n \n google.maps.event.addListener(marker, 'click', function() {\n infowindow.open(map,marker);\n });\n }\n </script>\n \n </head>\n \n <body onload = \"loadMap()\">\n <div id = \"googleMap\" style = \"width:580px; height:400px;\"></div>\n </body>\n \n</html>" }, { "code": null, "e": 4687, "s": 4652, "text": "It produces the following output −" }, { "code": null, "e": 4882, "s": 4687, "text": "You can remove an existing listener using the method removeListener(). This method accepts the listener object, therefore we have to assign the listener to a variable and pass it to this method." }, { "code": null, "e": 4934, "s": 4882, "text": "The following code shows how to remove a listener −" }, { "code": null, "e": 6096, "s": 4934, "text": "<!DOCTYPE html>\n<html>\n \n <head>\n <script src = \"https://maps.googleapis.com/maps/api/js\"></script>\n \n <script>\n var myCenter = new google.maps.LatLng(17.433053, 78.412172);\n function loadMap(){\n\t\t\t\n var mapProp = {\n center:myCenter,\n zoom:4,\n mapTypeId:google.maps.MapTypeId.ROADMAP\n };\n \n var map = new google.maps.Map(document.getElementById(\"googleMap\"),mapProp);\n \n var marker = new google.maps.Marker({\n position:myCenter,\n });\n \n marker.setMap(map);\n \n var infowindow = new google.maps.InfoWindow({\n content:\"Hi\"\n });\n \n var myListener = google.maps.event.addListener(marker, 'click', function() {\n infowindow.open(map,marker);\n });\n\t\t\t\t\n google.maps.event.removeListener(myListener);\n }\n </script>\n \n </head>\n \n <body onload = \"loadMap()\">\n <div id = \"googleMap\" style = \"width:580px; height:400px;\"></div>\n </body>\n \n</html>" }, { "code": null, "e": 6131, "s": 6096, "text": "It produces the following output −" }, { "code": null, "e": 6166, "s": 6131, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6180, "s": 6166, "text": " Asif Hussain" }, { "code": null, "e": 6212, "s": 6180, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 6229, "s": 6212, "text": " Aditya Kulkarni" }, { "code": null, "e": 6264, "s": 6229, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6278, "s": 6264, "text": " Sasha Miller" }, { "code": null, "e": 6313, "s": 6278, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6326, "s": 6313, "text": " Zach Miller" }, { "code": null, "e": 6361, "s": 6326, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6375, "s": 6361, "text": " Sasha Miller" }, { "code": null, "e": 6410, "s": 6375, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6424, "s": 6410, "text": " Sasha Miller" }, { "code": null, "e": 6431, "s": 6424, "text": " Print" }, { "code": null, "e": 6442, "s": 6431, "text": " Add Notes" } ]
JSP Mock Test
This section presents you various set of Mock Tests related to JSP Framework. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Q 1 - What is the correct signature of jspDestroy() method of HttpJspPage class? A - void jspDestroy(HTTPRequest request, HTTPResponse response) B - void jspDestroy(HTTPRequest request, HTTPResponse response) throws ServletException, IOException C - void jspDestroy() D - void jspDestroy() throws ServletException, IOException Correct Signature is void jspDestroy() Q 2 - What is the correct signature of jspInit() method of HttpJspPage class? A - void jspInit(HTTPRequest request, HTTPResponse response) B - void jspInit(HTTPRequest request, HTTPResponse response) throws ServletException, IOException C - void jspInit() D - void jspInit() throws ServletException, IOException Correct Signature is void jspInit() Q 3 - What is the correct signature of _jspService() method of HttpJspPage class? A - void _jspService(HTTPRequest request, HTTPResponse response) B - void _jspService(HTTPRequest request, HTTPResponse response) throws ServletException, IOException C - void _jspService() D - void _jspService() throws ServletException, IOException Correct Signature is void _jspService(HTTPRequest request, HTTPResponse response) throws ServletException, IOException Q 4 - _jspService() method of HttpJspPage class should not be overridden. A - True B - False JSP container creates _jspService() methods so it should not be overridden. Q 5 - _jspService() method of HttpJspPage class should not be overridden. A - True B - False JSP container creates _jspService() methods so it should not be overridden. Q 6 - jspInit() method of HttpJspPage class can be overridden. A - True B - False Yes, jspInit() method can be overridden. Q 7 - jspDestroy() method of HttpJspPage class can be overridden. A - True B - False Yes, jspDestroy() method can be overridden. Q 8 - Which of the following is not a implicit object? A - request B - response C - cookie D - session There is no cookie object in jsp. Q 9 - request is instance of which class? A - Request B - HttpRequest C - HttpServletRequest D - ServletRequest request is object of HttpServletRequest. Q 10 - response is instance of which class? A - Response B - HttpResponse C - HttpServletResponse D - ServletResponse request is object of HttpServletResponse. Q 11 - if isThreadSafe attribute of page directive is set as true, then generated servlet implements SingleThreadModel interface. A - True B - False If isThreadSafe attribute of page directive is set as false, then generated servlet implements SingleThreadModel interface. Q 12 - This object can be used to access other implicit objects in JSP. A - request B - page C - context D - pageContext pageContext can be used to retrieve other implicit objects using its methods like getPage(), getRequest() etc. Q 13 - What is default value of isThreadSafe? A - True B - False The isThreadSafe option marks a page as being thread-safe. By default, it is true and all JSPs are considered thread-safe. Q 14 - Setting isThreadSafe false can lead to poor performance. A - True B - False If you set the isThreadSafe option to false, the JSP engine makes sure that only one thread at a time is executing your JSP. Q 15 - session is instance of which class? A - Session B - HttpSession C - HttpServletSession D - ServletSession request is object of HttpSession. Q 16 - If a jsp is to generate a pdf page, what attribute of page directive it should use? A - contentType B - generatePdf C - typePDF B - contentPDF <%page contentType="application/pdf"> Above tag is used to generate PDF using JSP. Q 17 - If a jsp is to generate a xml page, what attribute of page directive it should use? A - contentXML B - generateXML C - typeXML D - contentType <%page contentType="text/xml"> Q 18 - Which of the following is not a directive? A - include B - page C - export D - useBean export is not a page directive. Q 19 - Which of the following is not a valid attribute of a page directives? A - language B - extend C - export D - import export is not a valid attribute of a page directive. Q 20 - Which of the following is a server side technology? A - html B - jsp C - javaScript D - css jsp is a server side technology. Q 21 - All jsp pages are required to be mapped and configured in web.xml. A - True B - False No, Jsp pages are not required to be mapped/configured in web.xml Q 22 - All servlet classes are required to be mapped and configured in web.xml. A - True B - False Yes, all servlets are required to be mapped/configured in web.xml Q 23 - Which of the following do not supports JSP directly? A - Weblogic Server B - WebSphere Server C - Tomcat Server D - Apache HTTP Server Apache HTTP Server do not supports JSP directly. Q 24 - What JSP stands for? A - Java Service Programming B - Java Server Programming C - Java Service Pages D - Java Server Pages JSP stands for Java Server Pages. Q 25 - Which is the methods of generated Servlet? A - jspInit() B - _jspService() C - jspDestroy() D - All of the above All of the above methods get generated in generated servlet. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2523, "s": 2239, "text": "This section presents you various set of Mock Tests related to JSP Framework. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself." }, { "code": null, "e": 2604, "s": 2523, "text": "Q 1 - What is the correct signature of jspDestroy() method of HttpJspPage class?" }, { "code": null, "e": 2668, "s": 2604, "text": "A - void jspDestroy(HTTPRequest request, HTTPResponse response)" }, { "code": null, "e": 2769, "s": 2668, "text": "B - void jspDestroy(HTTPRequest request, HTTPResponse response) throws ServletException, IOException" }, { "code": null, "e": 2791, "s": 2769, "text": "C - void jspDestroy()" }, { "code": null, "e": 2850, "s": 2791, "text": "D - void jspDestroy() throws ServletException, IOException" }, { "code": null, "e": 2871, "s": 2850, "text": "Correct Signature is" }, { "code": null, "e": 2889, "s": 2871, "text": "void jspDestroy()" }, { "code": null, "e": 2967, "s": 2889, "text": "Q 2 - What is the correct signature of jspInit() method of HttpJspPage class?" }, { "code": null, "e": 3028, "s": 2967, "text": "A - void jspInit(HTTPRequest request, HTTPResponse response)" }, { "code": null, "e": 3126, "s": 3028, "text": "B - void jspInit(HTTPRequest request, HTTPResponse response) throws ServletException, IOException" }, { "code": null, "e": 3145, "s": 3126, "text": "C - void jspInit()" }, { "code": null, "e": 3201, "s": 3145, "text": "D - void jspInit() throws ServletException, IOException" }, { "code": null, "e": 3237, "s": 3201, "text": "Correct Signature is\nvoid jspInit()" }, { "code": null, "e": 3319, "s": 3237, "text": "Q 3 - What is the correct signature of _jspService() method of HttpJspPage class?" }, { "code": null, "e": 3384, "s": 3319, "text": "A - void _jspService(HTTPRequest request, HTTPResponse response)" }, { "code": null, "e": 3486, "s": 3384, "text": "B - void _jspService(HTTPRequest request, HTTPResponse response) throws ServletException, IOException" }, { "code": null, "e": 3509, "s": 3486, "text": "C - void _jspService()" }, { "code": null, "e": 3569, "s": 3509, "text": "D - void _jspService() throws ServletException, IOException" }, { "code": null, "e": 3590, "s": 3569, "text": "Correct Signature is" }, { "code": null, "e": 3688, "s": 3590, "text": "void _jspService(HTTPRequest request, HTTPResponse response) throws ServletException, IOException" }, { "code": null, "e": 3762, "s": 3688, "text": "Q 4 - _jspService() method of HttpJspPage class should not be overridden." }, { "code": null, "e": 3771, "s": 3762, "text": "A - True" }, { "code": null, "e": 3781, "s": 3771, "text": "B - False" }, { "code": null, "e": 3857, "s": 3781, "text": "JSP container creates _jspService() methods so it should not be overridden." }, { "code": null, "e": 3931, "s": 3857, "text": "Q 5 - _jspService() method of HttpJspPage class should not be overridden." }, { "code": null, "e": 3940, "s": 3931, "text": "A - True" }, { "code": null, "e": 3950, "s": 3940, "text": "B - False" }, { "code": null, "e": 4026, "s": 3950, "text": "JSP container creates _jspService() methods so it should not be overridden." }, { "code": null, "e": 4089, "s": 4026, "text": "Q 6 - jspInit() method of HttpJspPage class can be overridden." }, { "code": null, "e": 4098, "s": 4089, "text": "A - True" }, { "code": null, "e": 4108, "s": 4098, "text": "B - False" }, { "code": null, "e": 4149, "s": 4108, "text": "Yes, jspInit() method can be overridden." }, { "code": null, "e": 4215, "s": 4149, "text": "Q 7 - jspDestroy() method of HttpJspPage class can be overridden." }, { "code": null, "e": 4224, "s": 4215, "text": "A - True" }, { "code": null, "e": 4234, "s": 4224, "text": "B - False" }, { "code": null, "e": 4278, "s": 4234, "text": "Yes, jspDestroy() method can be overridden." }, { "code": null, "e": 4333, "s": 4278, "text": "Q 8 - Which of the following is not a implicit object?" }, { "code": null, "e": 4345, "s": 4333, "text": "A - request" }, { "code": null, "e": 4358, "s": 4345, "text": "B - response" }, { "code": null, "e": 4369, "s": 4358, "text": "C - cookie" }, { "code": null, "e": 4381, "s": 4369, "text": "D - session" }, { "code": null, "e": 4415, "s": 4381, "text": "There is no cookie object in jsp." }, { "code": null, "e": 4457, "s": 4415, "text": "Q 9 - request is instance of which class?" }, { "code": null, "e": 4469, "s": 4457, "text": "A - Request" }, { "code": null, "e": 4485, "s": 4469, "text": "B - HttpRequest" }, { "code": null, "e": 4508, "s": 4485, "text": "C - HttpServletRequest" }, { "code": null, "e": 4527, "s": 4508, "text": "D - ServletRequest" }, { "code": null, "e": 4568, "s": 4527, "text": "request is object of HttpServletRequest." }, { "code": null, "e": 4612, "s": 4568, "text": "Q 10 - response is instance of which class?" }, { "code": null, "e": 4625, "s": 4612, "text": "A - Response" }, { "code": null, "e": 4642, "s": 4625, "text": "B - HttpResponse" }, { "code": null, "e": 4666, "s": 4642, "text": "C - HttpServletResponse" }, { "code": null, "e": 4686, "s": 4666, "text": "D - ServletResponse" }, { "code": null, "e": 4728, "s": 4686, "text": "request is object of HttpServletResponse." }, { "code": null, "e": 4858, "s": 4728, "text": "Q 11 - if isThreadSafe attribute of page directive is set as true, then generated servlet implements SingleThreadModel interface." }, { "code": null, "e": 4867, "s": 4858, "text": "A - True" }, { "code": null, "e": 4877, "s": 4867, "text": "B - False" }, { "code": null, "e": 5001, "s": 4877, "text": "If isThreadSafe attribute of page directive is set as false, then generated servlet implements SingleThreadModel interface." }, { "code": null, "e": 5073, "s": 5001, "text": "Q 12 - This object can be used to access other implicit objects in JSP." }, { "code": null, "e": 5085, "s": 5073, "text": "A - request" }, { "code": null, "e": 5094, "s": 5085, "text": "B - page" }, { "code": null, "e": 5106, "s": 5094, "text": "C - context" }, { "code": null, "e": 5122, "s": 5106, "text": "D - pageContext" }, { "code": null, "e": 5233, "s": 5122, "text": "pageContext can be used to retrieve other implicit objects using its methods like getPage(), getRequest() etc." }, { "code": null, "e": 5279, "s": 5233, "text": "Q 13 - What is default value of isThreadSafe?" }, { "code": null, "e": 5288, "s": 5279, "text": "A - True" }, { "code": null, "e": 5298, "s": 5288, "text": "B - False" }, { "code": null, "e": 5421, "s": 5298, "text": "The isThreadSafe option marks a page as being thread-safe. By default, it is true and all JSPs are considered thread-safe." }, { "code": null, "e": 5485, "s": 5421, "text": "Q 14 - Setting isThreadSafe false can lead to poor performance." }, { "code": null, "e": 5494, "s": 5485, "text": "A - True" }, { "code": null, "e": 5504, "s": 5494, "text": "B - False" }, { "code": null, "e": 5629, "s": 5504, "text": "If you set the isThreadSafe option to false, the JSP engine makes sure that only one thread at a time is executing your JSP." }, { "code": null, "e": 5672, "s": 5629, "text": "Q 15 - session is instance of which class?" }, { "code": null, "e": 5684, "s": 5672, "text": "A - Session" }, { "code": null, "e": 5700, "s": 5684, "text": "B - HttpSession" }, { "code": null, "e": 5723, "s": 5700, "text": "C - HttpServletSession" }, { "code": null, "e": 5742, "s": 5723, "text": "D - ServletSession" }, { "code": null, "e": 5776, "s": 5742, "text": "request is object of HttpSession." }, { "code": null, "e": 5867, "s": 5776, "text": "Q 16 - If a jsp is to generate a pdf page, what attribute of page directive it should use?" }, { "code": null, "e": 5883, "s": 5867, "text": "A - contentType" }, { "code": null, "e": 5899, "s": 5883, "text": "B - generatePdf" }, { "code": null, "e": 5911, "s": 5899, "text": "C - typePDF" }, { "code": null, "e": 5926, "s": 5911, "text": "B - contentPDF" }, { "code": null, "e": 5964, "s": 5926, "text": "<%page contentType=\"application/pdf\">" }, { "code": null, "e": 6009, "s": 5964, "text": "Above tag is used to generate PDF using JSP." }, { "code": null, "e": 6100, "s": 6009, "text": "Q 17 - If a jsp is to generate a xml page, what attribute of page directive it should use?" }, { "code": null, "e": 6115, "s": 6100, "text": "A - contentXML" }, { "code": null, "e": 6131, "s": 6115, "text": "B - generateXML" }, { "code": null, "e": 6143, "s": 6131, "text": "C - typeXML" }, { "code": null, "e": 6159, "s": 6143, "text": "D - contentType" }, { "code": null, "e": 6190, "s": 6159, "text": "<%page contentType=\"text/xml\">" }, { "code": null, "e": 6240, "s": 6190, "text": "Q 18 - Which of the following is not a directive?" }, { "code": null, "e": 6252, "s": 6240, "text": "A - include" }, { "code": null, "e": 6261, "s": 6252, "text": "B - page" }, { "code": null, "e": 6272, "s": 6261, "text": "C - export" }, { "code": null, "e": 6284, "s": 6272, "text": "D - useBean" }, { "code": null, "e": 6316, "s": 6284, "text": "export is not a page directive." }, { "code": null, "e": 6393, "s": 6316, "text": "Q 19 - Which of the following is not a valid attribute of a page directives?" }, { "code": null, "e": 6406, "s": 6393, "text": "A - language" }, { "code": null, "e": 6417, "s": 6406, "text": "B - extend" }, { "code": null, "e": 6428, "s": 6417, "text": "C - export" }, { "code": null, "e": 6439, "s": 6428, "text": "D - import" }, { "code": null, "e": 6492, "s": 6439, "text": "export is not a valid attribute of a page directive." }, { "code": null, "e": 6551, "s": 6492, "text": "Q 20 - Which of the following is a server side technology?" }, { "code": null, "e": 6560, "s": 6551, "text": "A - html" }, { "code": null, "e": 6568, "s": 6560, "text": "B - jsp" }, { "code": null, "e": 6583, "s": 6568, "text": "C - javaScript" }, { "code": null, "e": 6591, "s": 6583, "text": "D - css" }, { "code": null, "e": 6624, "s": 6591, "text": "jsp is a server side technology." }, { "code": null, "e": 6698, "s": 6624, "text": "Q 21 - All jsp pages are required to be mapped and configured in web.xml." }, { "code": null, "e": 6707, "s": 6698, "text": "A - True" }, { "code": null, "e": 6717, "s": 6707, "text": "B - False" }, { "code": null, "e": 6783, "s": 6717, "text": "No, Jsp pages are not required to be mapped/configured in web.xml" }, { "code": null, "e": 6863, "s": 6783, "text": "Q 22 - All servlet classes are required to be mapped and configured in web.xml." }, { "code": null, "e": 6872, "s": 6863, "text": "A - True" }, { "code": null, "e": 6882, "s": 6872, "text": "B - False" }, { "code": null, "e": 6948, "s": 6882, "text": "Yes, all servlets are required to be mapped/configured in web.xml" }, { "code": null, "e": 7008, "s": 6948, "text": "Q 23 - Which of the following do not supports JSP directly?" }, { "code": null, "e": 7028, "s": 7008, "text": "A - Weblogic Server" }, { "code": null, "e": 7049, "s": 7028, "text": "B - WebSphere Server" }, { "code": null, "e": 7067, "s": 7049, "text": "C - Tomcat Server" }, { "code": null, "e": 7090, "s": 7067, "text": "D - Apache HTTP Server" }, { "code": null, "e": 7139, "s": 7090, "text": "Apache HTTP Server do not supports JSP directly." }, { "code": null, "e": 7167, "s": 7139, "text": "Q 24 - What JSP stands for?" }, { "code": null, "e": 7196, "s": 7167, "text": "A - Java Service Programming" }, { "code": null, "e": 7224, "s": 7196, "text": "B - Java Server Programming" }, { "code": null, "e": 7247, "s": 7224, "text": "C - Java Service Pages" }, { "code": null, "e": 7269, "s": 7247, "text": "D - Java Server Pages" }, { "code": null, "e": 7303, "s": 7269, "text": "JSP stands for Java Server Pages." }, { "code": null, "e": 7353, "s": 7303, "text": "Q 25 - Which is the methods of generated Servlet?" }, { "code": null, "e": 7367, "s": 7353, "text": "A - jspInit()" }, { "code": null, "e": 7385, "s": 7367, "text": "B - _jspService()" }, { "code": null, "e": 7402, "s": 7385, "text": "C - jspDestroy()" }, { "code": null, "e": 7423, "s": 7402, "text": "D - All of the above" }, { "code": null, "e": 7484, "s": 7423, "text": "All of the above methods get generated in generated servlet." }, { "code": null, "e": 7519, "s": 7484, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 7534, "s": 7519, "text": " Chaand Sheikh" }, { "code": null, "e": 7569, "s": 7534, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 7584, "s": 7569, "text": " Chaand Sheikh" }, { "code": null, "e": 7619, "s": 7584, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7633, "s": 7619, "text": " Karthikeya T" }, { "code": null, "e": 7668, "s": 7633, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7684, "s": 7668, "text": " TELCOMA Global" }, { "code": null, "e": 7717, "s": 7684, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 7733, "s": 7717, "text": " TELCOMA Global" }, { "code": null, "e": 7767, "s": 7733, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 7775, "s": 7767, "text": " Uplatz" }, { "code": null, "e": 7782, "s": 7775, "text": " Print" }, { "code": null, "e": 7793, "s": 7782, "text": " Add Notes" } ]
degrees() and radians() in Python
The measurements of angles in mathematics are done using these two units of measurement called degree and radian. They are frequently used in math calculations involving angles and need conversion from one value to another. In python we can achieve these conversions using python functions. This function takes radian value as parameter and return the equivalent value in degrees. The return is a float value. Live Demo import math # Printing degree equivalent of radians. print("1 Radians in Degrees : ",math.degrees(1)) print("20 Radians in Degrees : ",math.degrees(20)) print("180 Radians in Degrees : ",math.degrees(180)) Running the above code gives us the following result − 1 Radians in Degrees : 57.29577951308232 20 Radians in Degrees : 1145.9155902616465 180 Radians in Degrees : 10313.240312354817 This function takes degree value as parameter and return the equivalent value in radians. The return is a float value. Live Demo import math # Printing radian equivalent of degrees. print("1 degrees in radian : ",math.radians(1)) print("60 degrees in radian : ",math.radians(60)) print("180 degrees in radian : ",math.radians(180)) Running the above code gives us the following result − 1 degrees in radian : 0.017453292519943295 60 degrees in radian : 1.0471975511965976 180 degrees in radian : 3.141592653589793 numpy package also has inbuilt functions which can directlyconver degrees to radian and vice versa. These functions are names deg2rad and rad2deg. Live Demo import numpy as np # Printing radian equivalent of degrees. print("1 degrees to radian : ",np.deg2rad(1)) print("1 radian to degree : ",np.rad2deg(1)) Running the above code gives us the following result^− 1 degrees to radian : 0.017453292519943295 1 radian to degree : 57.29577951308232
[ { "code": null, "e": 1353, "s": 1062, "text": "The measurements of angles in mathematics are done using these two units of measurement called degree and radian. They are frequently used in math calculations involving angles and need conversion from one value to another. In python we can achieve these conversions using python functions." }, { "code": null, "e": 1472, "s": 1353, "text": "This function takes radian value as parameter and return the equivalent value in degrees. The return is a float value." }, { "code": null, "e": 1483, "s": 1472, "text": " Live Demo" }, { "code": null, "e": 1689, "s": 1483, "text": "import math\n# Printing degree equivalent of radians.\nprint(\"1 Radians in Degrees : \",math.degrees(1))\nprint(\"20 Radians in Degrees : \",math.degrees(20))\nprint(\"180 Radians in Degrees : \",math.degrees(180))" }, { "code": null, "e": 1744, "s": 1689, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1872, "s": 1744, "text": "1 Radians in Degrees : 57.29577951308232\n20 Radians in Degrees : 1145.9155902616465\n180 Radians in Degrees : 10313.240312354817" }, { "code": null, "e": 1991, "s": 1872, "text": "This function takes degree value as parameter and return the equivalent value in radians. The return is a float value." }, { "code": null, "e": 2002, "s": 1991, "text": " Live Demo" }, { "code": null, "e": 2205, "s": 2002, "text": "import math\n# Printing radian equivalent of degrees.\nprint(\"1 degrees in radian : \",math.radians(1))\nprint(\"60 degrees in radian : \",math.radians(60))\nprint(\"180 degrees in radian : \",math.radians(180))" }, { "code": null, "e": 2260, "s": 2205, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2387, "s": 2260, "text": "1 degrees in radian : 0.017453292519943295\n60 degrees in radian : 1.0471975511965976\n180 degrees in radian : 3.141592653589793" }, { "code": null, "e": 2534, "s": 2387, "text": "numpy package also has inbuilt functions which can directlyconver degrees to radian and vice versa. These functions are names deg2rad and rad2deg." }, { "code": null, "e": 2545, "s": 2534, "text": " Live Demo" }, { "code": null, "e": 2696, "s": 2545, "text": "import numpy as np\n# Printing radian equivalent of degrees.\nprint(\"1 degrees to radian : \",np.deg2rad(1))\nprint(\"1 radian to degree : \",np.rad2deg(1))" }, { "code": null, "e": 2751, "s": 2696, "text": "Running the above code gives us the following result^−" }, { "code": null, "e": 2833, "s": 2751, "text": "1 degrees to radian : 0.017453292519943295\n1 radian to degree : 57.29577951308232" } ]
C# Program to Print the Employees Whose Name Started With Character 'S' Using LINQ - GeeksforGeeks
01 Nov, 2021 LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to print the details of employees whose name starts with letter ‘S’ using LINQ. So to do our task we use Where() method. This method filters the given sequence or array of values based on the predicate and to use this method you need to add System.Linq and System.Collections.Generic namespaces in your program. Syntax: Where<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>) Example: Input : List of Employees: {{id = 101, name = "Sravan", age = 12}, {id = 102, name = "deepu", age = 15}, {id = 103, name = "manoja", age = 13}, {id = 104, name = "Sathwik", age = 12}, {id = 105, name = "Saran", age = 15}} Output : {{id = 105, name = "sravan", age = 15}, {id = 104, name = "Sathwik",age = 12}, {id = 105, name = "Saran", age = 15}} Input : List of Employees: {{id = 102, name = "deepu", age = 15}, {id = 103, name = "manoja", age = 13}} Output : No Output Approach: To find the list of employees whose name starts with letter ‘S’ follow the following steps: Create a list of employees with three variables(Id, name, department, and salary).Iterate through the employee details by using Where() function and get the employee details by choosing employee whose name starts with’ S’ using s => s.name[0] == ‘S’.Now call the ToString() method.Display the employee details. Create a list of employees with three variables(Id, name, department, and salary). Iterate through the employee details by using Where() function and get the employee details by choosing employee whose name starts with’ S’ using s => s.name[0] == ‘S’. Now call the ToString() method. Display the employee details. Example: C# // C# program to display the details of those // employees whose name starts with character "S"using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; class Employee{ // Declare 4 variables - id, name, // department, and salaryint id; int salary;string name;string department; // Get the to string method that returns // id, name, department, and salarypublic override string ToString(){ return id + " " + name + " " + salary + " " + department;} // Driver codestatic void Main(string[] args){ // Declare a list variable List<Employee> emp = new List<Employee>() { // Create 5 Employee details new Employee{ id = 101, name = "Sravan", salary = 12000, department = "HR" }, new Employee{ id = 102, name = "deepu", salary = 15000, department = "Development" }, new Employee{ id = 103, name = "manoja", salary = 13000, department = "HR" }, new Employee{ id = 104, name = "Sathwik", salary = 12000, department = "Designing" }, new Employee{ id = 105, name = "Saran", salary = 15000, department = "Development" } }; // Iterate the Employee by selecting Employee // name starts with S IEnumerable<Employee> result = emp.Where(x => x.name[0] == 'S'); // Display employee details Console.WriteLine("ID Name Salary Department"); Console.WriteLine("++++++++++++++++++++++++++++"); foreach (Employee e in result) { // Call the to string method Console.WriteLine(e.ToString()); } }} Output: ID Name Salary Department ++++++++++++++++++++++++++++ 101 Sravan 12000 HR 104 Sathwik 12000 Designing 105 Saran 15000 Development CSharp LINQ CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | List Class C# | Inheritance Partial Classes in C# Convert String to Character Array in C# Lambda Expressions in C# Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n01 Nov, 2021" }, { "code": null, "e": 24987, "s": 24302, "text": "LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to print the details of employees whose name starts with letter ‘S’ using LINQ. So to do our task we use Where() method. This method filters the given sequence or array of values based on the predicate and to use this method you need to add System.Linq and System.Collections.Generic namespaces in your program." }, { "code": null, "e": 24995, "s": 24987, "text": "Syntax:" }, { "code": null, "e": 25056, "s": 24995, "text": "Where<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)" }, { "code": null, "e": 25065, "s": 25056, "text": "Example:" }, { "code": null, "e": 25626, "s": 25065, "text": "Input : List of Employees:\n {{id = 101, name = \"Sravan\", age = 12},\n {id = 102, name = \"deepu\", age = 15},\n {id = 103, name = \"manoja\", age = 13},\n {id = 104, name = \"Sathwik\", age = 12},\n {id = 105, name = \"Saran\", age = 15}}\nOutput : {{id = 105, name = \"sravan\", age = 15},\n {id = 104, name = \"Sathwik\",age = 12},\n {id = 105, name = \"Saran\", age = 15}}\n \nInput : List of Employees:\n {{id = 102, name = \"deepu\", age = 15},\n {id = 103, name = \"manoja\", age = 13}}\nOutput : No Output" }, { "code": null, "e": 25636, "s": 25626, "text": "Approach:" }, { "code": null, "e": 25728, "s": 25636, "text": "To find the list of employees whose name starts with letter ‘S’ follow the following steps:" }, { "code": null, "e": 26039, "s": 25728, "text": "Create a list of employees with three variables(Id, name, department, and salary).Iterate through the employee details by using Where() function and get the employee details by choosing employee whose name starts with’ S’ using s => s.name[0] == ‘S’.Now call the ToString() method.Display the employee details." }, { "code": null, "e": 26122, "s": 26039, "text": "Create a list of employees with three variables(Id, name, department, and salary)." }, { "code": null, "e": 26291, "s": 26122, "text": "Iterate through the employee details by using Where() function and get the employee details by choosing employee whose name starts with’ S’ using s => s.name[0] == ‘S’." }, { "code": null, "e": 26323, "s": 26291, "text": "Now call the ToString() method." }, { "code": null, "e": 26353, "s": 26323, "text": "Display the employee details." }, { "code": null, "e": 26362, "s": 26353, "text": "Example:" }, { "code": null, "e": 26365, "s": 26362, "text": "C#" }, { "code": "// C# program to display the details of those // employees whose name starts with character \"S\"using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; class Employee{ // Declare 4 variables - id, name, // department, and salaryint id; int salary;string name;string department; // Get the to string method that returns // id, name, department, and salarypublic override string ToString(){ return id + \" \" + name + \" \" + salary + \" \" + department;} // Driver codestatic void Main(string[] args){ // Declare a list variable List<Employee> emp = new List<Employee>() { // Create 5 Employee details new Employee{ id = 101, name = \"Sravan\", salary = 12000, department = \"HR\" }, new Employee{ id = 102, name = \"deepu\", salary = 15000, department = \"Development\" }, new Employee{ id = 103, name = \"manoja\", salary = 13000, department = \"HR\" }, new Employee{ id = 104, name = \"Sathwik\", salary = 12000, department = \"Designing\" }, new Employee{ id = 105, name = \"Saran\", salary = 15000, department = \"Development\" } }; // Iterate the Employee by selecting Employee // name starts with S IEnumerable<Employee> result = emp.Where(x => x.name[0] == 'S'); // Display employee details Console.WriteLine(\"ID Name Salary Department\"); Console.WriteLine(\"++++++++++++++++++++++++++++\"); foreach (Employee e in result) { // Call the to string method Console.WriteLine(e.ToString()); } }}", "e": 28060, "s": 26365, "text": null }, { "code": null, "e": 28068, "s": 28060, "text": "Output:" }, { "code": null, "e": 28202, "s": 28068, "text": "ID Name Salary Department\n++++++++++++++++++++++++++++\n101 Sravan 12000 HR\n104 Sathwik 12000 Designing\n105 Saran 15000 Development" }, { "code": null, "e": 28214, "s": 28202, "text": "CSharp LINQ" }, { "code": null, "e": 28230, "s": 28214, "text": "CSharp-programs" }, { "code": null, "e": 28237, "s": 28230, "text": "Picked" }, { "code": null, "e": 28240, "s": 28237, "text": "C#" }, { "code": null, "e": 28338, "s": 28240, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28361, "s": 28338, "text": "Extension Method in C#" }, { "code": null, "e": 28389, "s": 28361, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28429, "s": 28389, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28472, "s": 28429, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28488, "s": 28472, "text": "C# | List Class" }, { "code": null, "e": 28505, "s": 28488, "text": "C# | Inheritance" }, { "code": null, "e": 28527, "s": 28505, "text": "Partial Classes in C#" }, { "code": null, "e": 28567, "s": 28527, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 28592, "s": 28567, "text": "Lambda Expressions in C#" } ]
Demystifying Optimizations for machine learning | by Ravindra Parmar | Towards Data Science
Optimization is the most essential ingredient in the recipe of machine learning algorithms. It starts with defining some kind of loss function/cost function and ends with minimizing the it using one or the other optimization routine. The choice of optimization algorithm can make a difference between getting a good accuracy in hours or days. The applications of optimization are limitless and is widely researched topic in industry as well as academia. In this article we’ll walk through several optimization algorithms used in the realm of deep learning. (You can go through this article to understand the basics of loss functions) Stochastic gradient descent (SGD) is the simplest optimization algorithm used to find parameters which minimizes the given cost function. Apparently, for gradient descent to converge to optimal minimum, cost function should be convex. For the demonstration purpose, imagine following graphical representation for the cost function. We start with defining some random initial values for parameters. The goal for optimization algorithm is to find parameter values which correspond to minimum value of cost function. Specifically, gradient descent starts with calculating gradients (derivatives) for each of the parameter w.r.t cost function. Those gradients gives us numerical adjustment we need to make to each parameter so as to minimize the cost function. This process continues until we hit the local/global minimum (cost function is minimum w.r.t it’s surrounding values). Mathematically, for i in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) params -= learning_rate * param_gradients Learning rate defines how much parameters should change in each iteration. In other words it controls how fast or slow we should converge to minimum. On one hand, small learning rate can take iterations to converge a large learning rate can overshoot minimum as you can see in the figure above. Although easy enough to apply in practice, it has quite a few disadvantages when it comes to deep neural networks as these networks have large number of parameters to fit in. To illustrate issues with gradient descent let’s assume we have a cost function with two parameters only. Assume the cost function is very sensitive to changes in one of the parameter for example in vertical direction and less to other parameter i.e horizontal direction (This means cost function has high condition number). If we run stochastic gradient descent on this function, we get a kind of zigzag behavior. In essence, SGD is making slow progress towards less sensitive direction and more towards high sensitive one and hence does not align in the direction of minimum. In practice, deep neural network could have millions of parameters and hence millions of directions to accommodate for gradient adjustments and hence compounding the problem. Another issue with SGD is problem of local minimum or saddle points. Saddle points are points where gradient is zero in all directions. Consequently, our SGD will be stuck there only. On the other hand, local minimums are point which are minimum w.r.t surrounding however not minimum over all. As gradient will be zero at local minimum our gradient descent would report it as minimum value when global minimum is somewhere else. To rectify the issues with vanilla gradient descent several advanced optimization algorithms were developed in recent years. We will look through them one by one. In order to understand the dynamics behind advanced optimizations we first have to grasp the concept of exponentially weighted average. Let’s assume we are given data for temperatures per day of any particular city for all 365 days of a year. Plotting it, we get a graph at top left corner. Now, if we wish to calculate the local average temperature across the year we would proceed as follows. NOTE :- alpha = 0.9 is randomly chosen weight. t(i) is temperature at ith day. v(i) is average temperature for ith day averaged over 1/(1 - alpha) days.v(0) = 0v(1) = 0.9 * v(0) + 0.1 * t(1)v(2) = 0.9 * v(1) + 0.1 * t(2)...v(i) = alpha * v(i-1) + (1 - alpha) * t(i) At each day, we are calculating weighted average of previous day temperatures and current day temperature. Plot for above computation is shown at top right corner. This plot is averaging temperature over last 10 days (alpha = 0.9). Left bottom (green line) is showing the plot averaging data over last 50 days (alpha = 0.98). An important point to notice here is as we are averaging over more number of days the plot will become less sensitive to changes in temperature. In contrast, if we average over less number of days the plot will be more sensitive to changes in temperature and hence wriggly behavior. This increase in latency is due to the fact that we are giving more weight-age to previous day temperatures than current day temperature. So far so good, but the question is what all this buys us. Quite similarly, by averaging gradients over past few values, we tend to reduce the oscillations in more sensitive direction and hence make it converge faster. In practice, momentum based optimization algorithms are almost always faster then vanilla gradient descent. Mathematically, moment = 0for i in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) moment = gamma * moment + param_gradients params += learning_rate * moment (where moment is building moving average of gradients. gamma gives kind of friction = 0.9 or 0.99). The idea is, for each parameter, we store the sum of squares of all its historical gradients. This sum is later used to scale the learning rate. Notice that, in contrast to previous optimizations, here we have different learning rate for each of the parameter. squared_gradients = 0for i in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) squared_gradients += param_gradients * param_gradients params -= learning_rate * param_gradients/ (np.sqrt(squared_gradients) + 1e-8) {1e-8 is to avoid divide by zero} Now the question is how this scaling is helping us when we have very high condition number for our loss function? For parameters with high gradient values, the squared term will be large and hence dividing with large term would make gradient accelerate slowly in that direction. Similarly, parameters with low gradients will produce smaller squared terms and hence gradient will accelerate faster in that direction. However notice that, as gradient is squared at every step, the moving estimate will grow monotonically over the course of time and hence the step size our algorithm will take to converge to minimum would get smaller and smaller. And in a sense this is beneficial for convex problems as we are expected to slow down towards minimum in this case. However, the same gift becomes a curse in case of non-convex optimization problems as chance of getting stuck in saddle points increases. This is a slight variation of AdaGrad and works better in practice as it addresses the issues left open by it. Similar to AdaGrad, here as well we will keep the estimate of squared gradient but instead of letting that squared estimate accumulate over training we rather let that estimate decay gradually. To accomplish this, we multiply the current estimate of squared gradients with the decay rate. squared_gradients = 0for i in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) squared_gradients = decay_rate * squared_gradients + (1 - decay_rate) * param_gradients * param_gradients params -= learning_rate * param_gradients/ (np.sqrt(squared_gradients) + 1e-8) This incorporates all the nice features of RMSProp and Gradient descent with momentum. Specifically, this algorithm calculates an exponential moving average of gradients and the squared gradients whereas parameters beta_1 and beta_2 controls the decay rates of these moving averages. first_moment = 0second_moment = 0for step in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) first_moment = beta_1 * first_moment + (1 - beta_1) * param_gradients second_moment = beta_2 * second_moment + (1 - beta_2) * param_gradients * param_gradients params -= learning_rate * first_moment/(np.sqrt(second_moment) + 1e-8) Notice that we’ve initialized second_moment to zero. So, in the beginning, second_moment would be calculated as somewhere very close to zero. Consequently, we are updating parameters by dividing with a very small number and hence making large updates to parameter. That means initially, the algorithm would make larger steps. To rectify that we create an unbiased estimate of those first and second moment by incorporating current step. And then we make update to parameters based on these unbiased estimates rather than first and second moments. Mathematically, first_moment = 0second_moment = 0for step in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) first_moment = beta_1 * first_moment + (1 - beta_1) * param_gradients second_moment = beta_2 * second_moment + (1 - beta_2) * param_gradients * param_gradients first_bias_correction = first_moment/(1 - beta_1 ** step) second_bias_correction = second_moment/(1 - beta_2 ** step) params -= learning_rate * first_bias_correction/ (np.sqrt(second_bias_correction) + 1e-8) Figure below demonstrates the performance of each of the optimization algorithm as iterations pass by. Clearly adding momentum provides boost to accuracy. In practice, however, Adam is known to perform very well with large data sets and complex features. www.coursera.org You can find this for more mathematical background. Please let me know through your comments any modifications/improvements this article could accommodate.
[ { "code": null, "e": 805, "s": 171, "text": "Optimization is the most essential ingredient in the recipe of machine learning algorithms. It starts with defining some kind of loss function/cost function and ends with minimizing the it using one or the other optimization routine. The choice of optimization algorithm can make a difference between getting a good accuracy in hours or days. The applications of optimization are limitless and is widely researched topic in industry as well as academia. In this article we’ll walk through several optimization algorithms used in the realm of deep learning. (You can go through this article to understand the basics of loss functions)" }, { "code": null, "e": 1137, "s": 805, "text": "Stochastic gradient descent (SGD) is the simplest optimization algorithm used to find parameters which minimizes the given cost function. Apparently, for gradient descent to converge to optimal minimum, cost function should be convex. For the demonstration purpose, imagine following graphical representation for the cost function." }, { "code": null, "e": 1697, "s": 1137, "text": "We start with defining some random initial values for parameters. The goal for optimization algorithm is to find parameter values which correspond to minimum value of cost function. Specifically, gradient descent starts with calculating gradients (derivatives) for each of the parameter w.r.t cost function. Those gradients gives us numerical adjustment we need to make to each parameter so as to minimize the cost function. This process continues until we hit the local/global minimum (cost function is minimum w.r.t it’s surrounding values). Mathematically," }, { "code": null, "e": 1937, "s": 1697, "text": "for i in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) params -= learning_rate * param_gradients" }, { "code": null, "e": 2232, "s": 1937, "text": "Learning rate defines how much parameters should change in each iteration. In other words it controls how fast or slow we should converge to minimum. On one hand, small learning rate can take iterations to converge a large learning rate can overshoot minimum as you can see in the figure above." }, { "code": null, "e": 2732, "s": 2232, "text": "Although easy enough to apply in practice, it has quite a few disadvantages when it comes to deep neural networks as these networks have large number of parameters to fit in. To illustrate issues with gradient descent let’s assume we have a cost function with two parameters only. Assume the cost function is very sensitive to changes in one of the parameter for example in vertical direction and less to other parameter i.e horizontal direction (This means cost function has high condition number)." }, { "code": null, "e": 3160, "s": 2732, "text": "If we run stochastic gradient descent on this function, we get a kind of zigzag behavior. In essence, SGD is making slow progress towards less sensitive direction and more towards high sensitive one and hence does not align in the direction of minimum. In practice, deep neural network could have millions of parameters and hence millions of directions to accommodate for gradient adjustments and hence compounding the problem." }, { "code": null, "e": 3589, "s": 3160, "text": "Another issue with SGD is problem of local minimum or saddle points. Saddle points are points where gradient is zero in all directions. Consequently, our SGD will be stuck there only. On the other hand, local minimums are point which are minimum w.r.t surrounding however not minimum over all. As gradient will be zero at local minimum our gradient descent would report it as minimum value when global minimum is somewhere else." }, { "code": null, "e": 3752, "s": 3589, "text": "To rectify the issues with vanilla gradient descent several advanced optimization algorithms were developed in recent years. We will look through them one by one." }, { "code": null, "e": 4043, "s": 3752, "text": "In order to understand the dynamics behind advanced optimizations we first have to grasp the concept of exponentially weighted average. Let’s assume we are given data for temperatures per day of any particular city for all 365 days of a year. Plotting it, we get a graph at top left corner." }, { "code": null, "e": 4147, "s": 4043, "text": "Now, if we wish to calculate the local average temperature across the year we would proceed as follows." }, { "code": null, "e": 4435, "s": 4147, "text": "NOTE :- alpha = 0.9 is randomly chosen weight. t(i) is temperature at ith day. v(i) is average temperature for ith day averaged over 1/(1 - alpha) days.v(0) = 0v(1) = 0.9 * v(0) + 0.1 * t(1)v(2) = 0.9 * v(1) + 0.1 * t(2)...v(i) = alpha * v(i-1) + (1 - alpha) * t(i)" }, { "code": null, "e": 4761, "s": 4435, "text": "At each day, we are calculating weighted average of previous day temperatures and current day temperature. Plot for above computation is shown at top right corner. This plot is averaging temperature over last 10 days (alpha = 0.9). Left bottom (green line) is showing the plot averaging data over last 50 days (alpha = 0.98)." }, { "code": null, "e": 5044, "s": 4761, "text": "An important point to notice here is as we are averaging over more number of days the plot will become less sensitive to changes in temperature. In contrast, if we average over less number of days the plot will be more sensitive to changes in temperature and hence wriggly behavior." }, { "code": null, "e": 5182, "s": 5044, "text": "This increase in latency is due to the fact that we are giving more weight-age to previous day temperatures than current day temperature." }, { "code": null, "e": 5401, "s": 5182, "text": "So far so good, but the question is what all this buys us. Quite similarly, by averaging gradients over past few values, we tend to reduce the oscillations in more sensitive direction and hence make it converge faster." }, { "code": null, "e": 5525, "s": 5401, "text": "In practice, momentum based optimization algorithms are almost always faster then vanilla gradient descent. Mathematically," }, { "code": null, "e": 5937, "s": 5525, "text": "moment = 0for i in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) moment = gamma * moment + param_gradients params += learning_rate * moment (where moment is building moving average of gradients. gamma gives kind of friction = 0.9 or 0.99)." }, { "code": null, "e": 6082, "s": 5937, "text": "The idea is, for each parameter, we store the sum of squares of all its historical gradients. This sum is later used to scale the learning rate." }, { "code": null, "e": 6198, "s": 6082, "text": "Notice that, in contrast to previous optimizations, here we have different learning rate for each of the parameter." }, { "code": null, "e": 6638, "s": 6198, "text": "squared_gradients = 0for i in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) squared_gradients += param_gradients * param_gradients params -= learning_rate * param_gradients/ (np.sqrt(squared_gradients) + 1e-8) {1e-8 is to avoid divide by zero}" }, { "code": null, "e": 6752, "s": 6638, "text": "Now the question is how this scaling is helping us when we have very high condition number for our loss function?" }, { "code": null, "e": 7054, "s": 6752, "text": "For parameters with high gradient values, the squared term will be large and hence dividing with large term would make gradient accelerate slowly in that direction. Similarly, parameters with low gradients will produce smaller squared terms and hence gradient will accelerate faster in that direction." }, { "code": null, "e": 7283, "s": 7054, "text": "However notice that, as gradient is squared at every step, the moving estimate will grow monotonically over the course of time and hence the step size our algorithm will take to converge to minimum would get smaller and smaller." }, { "code": null, "e": 7537, "s": 7283, "text": "And in a sense this is beneficial for convex problems as we are expected to slow down towards minimum in this case. However, the same gift becomes a curse in case of non-convex optimization problems as chance of getting stuck in saddle points increases." }, { "code": null, "e": 7937, "s": 7537, "text": "This is a slight variation of AdaGrad and works better in practice as it addresses the issues left open by it. Similar to AdaGrad, here as well we will keep the estimate of squared gradient but instead of letting that squared estimate accumulate over training we rather let that estimate decay gradually. To accomplish this, we multiply the current estimate of squared gradients with the decay rate." }, { "code": null, "e": 8392, "s": 7937, "text": "squared_gradients = 0for i in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) squared_gradients = decay_rate * squared_gradients + (1 - decay_rate) * param_gradients * param_gradients params -= learning_rate * param_gradients/ (np.sqrt(squared_gradients) + 1e-8)" }, { "code": null, "e": 8479, "s": 8392, "text": "This incorporates all the nice features of RMSProp and Gradient descent with momentum." }, { "code": null, "e": 8676, "s": 8479, "text": "Specifically, this algorithm calculates an exponential moving average of gradients and the squared gradients whereas parameters beta_1 and beta_2 controls the decay rates of these moving averages." }, { "code": null, "e": 9293, "s": 8676, "text": "first_moment = 0second_moment = 0for step in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) first_moment = beta_1 * first_moment + (1 - beta_1) * param_gradients second_moment = beta_2 * second_moment + (1 - beta_2) * param_gradients * param_gradients params -= learning_rate * first_moment/(np.sqrt(second_moment) + 1e-8)" }, { "code": null, "e": 9856, "s": 9293, "text": "Notice that we’ve initialized second_moment to zero. So, in the beginning, second_moment would be calculated as somewhere very close to zero. Consequently, we are updating parameters by dividing with a very small number and hence making large updates to parameter. That means initially, the algorithm would make larger steps. To rectify that we create an unbiased estimate of those first and second moment by incorporating current step. And then we make update to parameters based on these unbiased estimates rather than first and second moments. Mathematically," }, { "code": null, "e": 10580, "s": 9856, "text": "first_moment = 0second_moment = 0for step in range(iterations_count): param_gradients = evaluate_gradients(loss_function, data, params) first_moment = beta_1 * first_moment + (1 - beta_1) * param_gradients second_moment = beta_2 * second_moment + (1 - beta_2) * param_gradients * param_gradients first_bias_correction = first_moment/(1 - beta_1 ** step) second_bias_correction = second_moment/(1 - beta_2 ** step) params -= learning_rate * first_bias_correction/ (np.sqrt(second_bias_correction) + 1e-8)" }, { "code": null, "e": 10835, "s": 10580, "text": "Figure below demonstrates the performance of each of the optimization algorithm as iterations pass by. Clearly adding momentum provides boost to accuracy. In practice, however, Adam is known to perform very well with large data sets and complex features." }, { "code": null, "e": 10852, "s": 10835, "text": "www.coursera.org" } ]
Probability Calibration for Imbalanced Dataset | by Kyosuke Morita | Towards Data Science
When we are trying to build a machine learning model for real-world problems, we are often faced with imbalanced datasets. Resampling method, especially undersampling is one of the most widely used methods to overcome the class imbalance (I also showed how those resampling methods worked on my Master dissertation in the other medium post). However, implementing this method tends to increase false positive due to the different class distribution in train and test set. This biases the classifier and increases false positive. [1] Pozzolo, et al., (2015) argues that we can correct the bias due to the undersampling by using Bayes Minimum Risk theory. This helps us to find the correct classification threshold. How does Probability Calibration work?ExperimentConclusion How does Probability Calibration work? Experiment Conclusion As briefly mentioned above, undersampling causes a bias in the posterior probabilities. This is due to the characteristic of random undersampling, which downsizes the majority class by removing them randomly until both classes have the same number of observations. This makes the class distribution of the training set different from the one in the test set. So how exactly probability calibration using Bayes Minimum Risk theory works on this problem? — the basic idea of this method is trying to reduce/remove the bias caused by random undersampling by taking into the undersampling ratio β account. Let’s have a look into some definitions: Let ps be the probability of the prediction being a positive class after random undersampling; , and p be the probability of the prediction given features (unbalanced). We can write ps as a function of p; , where β is a probability of selecting negative class with undersampling, which can be expressed below. , which can be written The equation above can be solved for p and expressed as below. So after applying undersampling ratio β, we can calculate for p, which is the unbiased probability. The threshold for this is can be; , which is a probability of a positive class in a dataset. This was a brief introduction of probability calibration by using Bayes Minimum Risk theory. Now we will go on to see how this works in an example with codes. In this section, we will see how the probability calibration technique the model performance on a binary classification problem on the famous credit card fraud dataset on Kaggle. This dataset consists of 28 PCA features (all of them are anonymous) plus the Amount feature. The target feature is binary, either fraud or not. The positive class is 0.17% of a whole dataset, which is severely imbalanced. Let’s go through the example with codes. First, import the packages. ## configimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport io, os, sys, types, gc, refrom sklearn import preprocessingfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import average_precision_score,confusion_matrix, precision_score, recall_score, precision_recall_curve, f1_score, log_lossfrom sklearn.decomposition import PCApca = PCA(n_components=1,random_state=42)from imblearn.under_sampling import RandomUnderSamplerrus = RandomUnderSampler(random_state=42)from imblearn.ensemble import BalancedBaggingClassifierfrom src.functionalscripts.BMR import *def make_prediction(model,X,threshold): y_pred = model.predict_proba(X) y_predicted = np.where(y_pred[:,1]>=threshold,1,0) return y_pred, y_predicteddef evaluation(true, pred): print('F1-score: ' + str(round(f1_score(true,pred),4)), '\n''Precision: ' + str(round(precision_score(true,pred),4)), '\n''Recall: ' + str(round(recall_score(true,pred),4)), '\n''Log loss: ' + str(round(log_loss(true,pred),4)), '\n''Cohen-Kappa: ' + str(round(cohen_kappa_score(true,pred),4)), '\n''Confusion matrix:' + '\n' + str(confusion_matrix(true,pred))) Now read the dataset. # read the datadf = pd.read_csv('src/resources/data/creditcard.csv') Here are the first few rows of the dataset. Class column is our target variable and Amount column is the transaction amount. Now see the ratio of the positive class. # The percentage of positive class in this datasetlen(df[df['Class']==1])/len(df) The positive class is as I mentioned above, 0.17%. Now we will move on to the model building. We will use logistic regression just to see. Let’s normalise the Amount column and split into train and test dataset. # Normalise the Amount featuredf['amt'] = preprocessing.normalize(np.array(df['Amount']).reshape(-1,1),norm='l2') Now, the data are ready, let’s split into train (80% of whole data) and test (20% of whole data) dataset and implement random undersampling. # Split the dataset into train and test, and drop unnecessary featurestr, te = train_test_split(df.drop(['Amount','Time'],1), test_size=.2,random_state=42)# Rundom Under Sampling (RUS)tr_x_rus, tr_y_rus = rus.fit_resample(tr.drop(['Class'],1),tr.Class) We can check the distribution of classes in train, test and train set after random undersampling. # See the class distribution with featuresfeats_distribution_rus = pd.DataFrame(pca.fit_transform(tr_x_rus),columns=['after']).reset_index(drop=True)feats_distribution_rus['Class'] = tr_y_russns.regplot(x='after',y='Class',data=feats_distribution_rus,logistic=True, n_boot=500, y_jitter=.03)plt.title('Class distribution of training set after undersampling')plt.show() We have the distribution of train set in the left upper corner, distribution after random undersampling in the left down corner and right-hand side are both test set (for comparison). y-axis shows the class and 1 means the transaction was a fraud and otherwise not a fraud. We can see similar distributions in train and test set as they were created by random sampling. On the other hand, in the train set after random undersampling demonstrates quite different distribution from others. Let’s see how this difference impact on the classifiers. Now build models. For the comparison, let’s see the performance of RUS bagging (Random Undersampling + bagging) as well. # Logistic regressionlogit = LogisticRegression(random_state=42,solver='lbfgs',max_iter=1000)# Rundom Under Sampling (RUS)tr_x_rus, tr_y_rus = rus.fit_resample(tr.drop(['Class'],1),tr.Class)logit_rus = logit.fit(tr_x_rus,tr_y_rus)# RUS baggingbc = BalancedBaggingClassifier(base_estimator=logit,random_state=42)logit_bc = bc.fit(tr.drop(['Class'],1),tr.Class) Now we implement the probability calibration method using Bayes Minimum Risk. Here we create beta (minority selection ratio), tau (threshold) and calibration functions. # BMR (Bayes Minimum Risk) implementation# Pozzolo et al., 2015, Calibrating Probability with Undersamplingclass BMR: def beta(binary_target): return binary_target.sum()/len(binary_target) def tau(binary_target, beta): return binary_target.sum()/len(binary_target) def calibration(prob, beta): return prob/(prob+(1-prob)/beta) Apply those calibration techniques to both predicted probabilities by RUS and RUS Bagging. # Calibrationbeta = BMR.beta(tr.Class)tau = BMR.tau(tr.Class,beta)# with RUSy_pred_calib_rus = BMR.calibration(prob=logit_rus.predict_proba(te.drop(['Class'],1))[:,1],beta=beta)y_predicted_calib_rus = np.where(y_pred_calib_rus>=tau,1,0)# wtih RUS baggingy_pred_calib_bc = BMR.calibration(prob=logit_bc.predict_proba(te.drop(['Class'],1))[:,1],beta=beta)y_predicted_calib_bc = np.where(y_pred_calib_bc>=tau,1,0) Now we have all the predictions, let’s evaluate them and see how are their performance. I set the thresholds for RUS and RUS bagging model as 0.5. # Evaluation## Random Under Sampling (RUS)y_pred_rus, y_predicted_rus = make_prediction(model=logit_rus, X=te.drop(['Class'],1), threshold=.5)evaluation(te.Class, y_predicted_rus)## RUS + Baggingy_pred_bc, y_predicted_bc = make_prediction(model=logit_bc, X=te.drop(['Class'],1), threshold=.5)evaluation(te.Class, y_predicted_bc)## Calibration with Rundom undersamplingevaluation(te.Class, y_predicted_calib_rus)## Calibration with RUS baggingevaluation(te.Class, y_predicted_calib_bc) Here are the results. As we expected, there are so many false positives, which we can see from the precision scores. Oh wait, probability calibration didn’t change anything at all? There must be something wrong. Let’s see the prediction distributions of predicted probability of RUS Bagging with calibration. The blue verticle line is the mean of predicted probability by RUS Bagging with calibration and red verticle line is the mean of predicted probability by RUS Bagging model. Obviously their means are quite far away, for calibrated probability mean is 0.0021 and before calibration is 0.5. Considering the positive class exists 0.17% in a whole dataset, the calibrated probability seems quite close to the actual distribution. So if we modify the threshold, it should work better and here we can see the results with modified thresholds. Thresholds before calibration and after calibration on RUS model are set at 0.99 and calibration with RUS Bagging is set at 0.8. As we can see, after calibration those scores improved, especially the difference between before and after calibration on the random undersampling model are significant. So by correcting the biased probability by using probability calibration, we could see the performance improvement. 3. Conclusion and thoughts In this blog post, we went through Pozzolo, et al. (2015). This answers our experience that having more false positive after applying random undersampling. It was quite interesting to see how the resampling method biases the distribution. This would be causing a similar problem in time-series problems as the target variable we are predicting can be quite different from when we trained the model. Would be interesting to see if this sort of method works for different types of classifiers like tree-based or neural network and also different types of resampling methods. The codes for this post is available on my GitHub page. Introduced the resampling causes a bias in a posterior distribution Introduced probability calibration method by using Bayes Minimum Risk theory (Pozzoli, et al. 2015) Showed the example of this method Confirmed that this method corrects the bias and improve the model results [1] Pozzolo, et al., Calibrating Probability with Undersampling for Unbalanced Classification (2015), 2015 IEEE Symposium Series on Computational Intelligence
[ { "code": null, "e": 886, "s": 172, "text": "When we are trying to build a machine learning model for real-world problems, we are often faced with imbalanced datasets. Resampling method, especially undersampling is one of the most widely used methods to overcome the class imbalance (I also showed how those resampling methods worked on my Master dissertation in the other medium post). However, implementing this method tends to increase false positive due to the different class distribution in train and test set. This biases the classifier and increases false positive. [1] Pozzolo, et al., (2015) argues that we can correct the bias due to the undersampling by using Bayes Minimum Risk theory. This helps us to find the correct classification threshold." }, { "code": null, "e": 945, "s": 886, "text": "How does Probability Calibration work?ExperimentConclusion" }, { "code": null, "e": 984, "s": 945, "text": "How does Probability Calibration work?" }, { "code": null, "e": 995, "s": 984, "text": "Experiment" }, { "code": null, "e": 1006, "s": 995, "text": "Conclusion" }, { "code": null, "e": 1649, "s": 1006, "text": "As briefly mentioned above, undersampling causes a bias in the posterior probabilities. This is due to the characteristic of random undersampling, which downsizes the majority class by removing them randomly until both classes have the same number of observations. This makes the class distribution of the training set different from the one in the test set. So how exactly probability calibration using Bayes Minimum Risk theory works on this problem? — the basic idea of this method is trying to reduce/remove the bias caused by random undersampling by taking into the undersampling ratio β account. Let’s have a look into some definitions:" }, { "code": null, "e": 1744, "s": 1649, "text": "Let ps be the probability of the prediction being a positive class after random undersampling;" }, { "code": null, "e": 1854, "s": 1744, "text": ", and p be the probability of the prediction given features (unbalanced). We can write ps as a function of p;" }, { "code": null, "e": 1959, "s": 1854, "text": ", where β is a probability of selecting negative class with undersampling, which can be expressed below." }, { "code": null, "e": 1982, "s": 1959, "text": ", which can be written" }, { "code": null, "e": 2045, "s": 1982, "text": "The equation above can be solved for p and expressed as below." }, { "code": null, "e": 2145, "s": 2045, "text": "So after applying undersampling ratio β, we can calculate for p, which is the unbiased probability." }, { "code": null, "e": 2179, "s": 2145, "text": "The threshold for this is can be;" }, { "code": null, "e": 2238, "s": 2179, "text": ", which is a probability of a positive class in a dataset." }, { "code": null, "e": 2397, "s": 2238, "text": "This was a brief introduction of probability calibration by using Bayes Minimum Risk theory. Now we will go on to see how this works in an example with codes." }, { "code": null, "e": 2840, "s": 2397, "text": "In this section, we will see how the probability calibration technique the model performance on a binary classification problem on the famous credit card fraud dataset on Kaggle. This dataset consists of 28 PCA features (all of them are anonymous) plus the Amount feature. The target feature is binary, either fraud or not. The positive class is 0.17% of a whole dataset, which is severely imbalanced. Let’s go through the example with codes." }, { "code": null, "e": 2868, "s": 2840, "text": "First, import the packages." }, { "code": null, "e": 4099, "s": 2868, "text": "## configimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport io, os, sys, types, gc, refrom sklearn import preprocessingfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import average_precision_score,confusion_matrix, precision_score, recall_score, precision_recall_curve, f1_score, log_lossfrom sklearn.decomposition import PCApca = PCA(n_components=1,random_state=42)from imblearn.under_sampling import RandomUnderSamplerrus = RandomUnderSampler(random_state=42)from imblearn.ensemble import BalancedBaggingClassifierfrom src.functionalscripts.BMR import *def make_prediction(model,X,threshold): y_pred = model.predict_proba(X) y_predicted = np.where(y_pred[:,1]>=threshold,1,0) return y_pred, y_predicteddef evaluation(true, pred): print('F1-score: ' + str(round(f1_score(true,pred),4)), '\\n''Precision: ' + str(round(precision_score(true,pred),4)), '\\n''Recall: ' + str(round(recall_score(true,pred),4)), '\\n''Log loss: ' + str(round(log_loss(true,pred),4)), '\\n''Cohen-Kappa: ' + str(round(cohen_kappa_score(true,pred),4)), '\\n''Confusion matrix:' + '\\n' + str(confusion_matrix(true,pred)))" }, { "code": null, "e": 4121, "s": 4099, "text": "Now read the dataset." }, { "code": null, "e": 4190, "s": 4121, "text": "# read the datadf = pd.read_csv('src/resources/data/creditcard.csv')" }, { "code": null, "e": 4234, "s": 4190, "text": "Here are the first few rows of the dataset." }, { "code": null, "e": 4356, "s": 4234, "text": "Class column is our target variable and Amount column is the transaction amount. Now see the ratio of the positive class." }, { "code": null, "e": 4438, "s": 4356, "text": "# The percentage of positive class in this datasetlen(df[df['Class']==1])/len(df)" }, { "code": null, "e": 4650, "s": 4438, "text": "The positive class is as I mentioned above, 0.17%. Now we will move on to the model building. We will use logistic regression just to see. Let’s normalise the Amount column and split into train and test dataset." }, { "code": null, "e": 4764, "s": 4650, "text": "# Normalise the Amount featuredf['amt'] = preprocessing.normalize(np.array(df['Amount']).reshape(-1,1),norm='l2')" }, { "code": null, "e": 4905, "s": 4764, "text": "Now, the data are ready, let’s split into train (80% of whole data) and test (20% of whole data) dataset and implement random undersampling." }, { "code": null, "e": 5158, "s": 4905, "text": "# Split the dataset into train and test, and drop unnecessary featurestr, te = train_test_split(df.drop(['Amount','Time'],1), test_size=.2,random_state=42)# Rundom Under Sampling (RUS)tr_x_rus, tr_y_rus = rus.fit_resample(tr.drop(['Class'],1),tr.Class)" }, { "code": null, "e": 5256, "s": 5158, "text": "We can check the distribution of classes in train, test and train set after random undersampling." }, { "code": null, "e": 5625, "s": 5256, "text": "# See the class distribution with featuresfeats_distribution_rus = pd.DataFrame(pca.fit_transform(tr_x_rus),columns=['after']).reset_index(drop=True)feats_distribution_rus['Class'] = tr_y_russns.regplot(x='after',y='Class',data=feats_distribution_rus,logistic=True, n_boot=500, y_jitter=.03)plt.title('Class distribution of training set after undersampling')plt.show()" }, { "code": null, "e": 6170, "s": 5625, "text": "We have the distribution of train set in the left upper corner, distribution after random undersampling in the left down corner and right-hand side are both test set (for comparison). y-axis shows the class and 1 means the transaction was a fraud and otherwise not a fraud. We can see similar distributions in train and test set as they were created by random sampling. On the other hand, in the train set after random undersampling demonstrates quite different distribution from others. Let’s see how this difference impact on the classifiers." }, { "code": null, "e": 6291, "s": 6170, "text": "Now build models. For the comparison, let’s see the performance of RUS bagging (Random Undersampling + bagging) as well." }, { "code": null, "e": 6651, "s": 6291, "text": "# Logistic regressionlogit = LogisticRegression(random_state=42,solver='lbfgs',max_iter=1000)# Rundom Under Sampling (RUS)tr_x_rus, tr_y_rus = rus.fit_resample(tr.drop(['Class'],1),tr.Class)logit_rus = logit.fit(tr_x_rus,tr_y_rus)# RUS baggingbc = BalancedBaggingClassifier(base_estimator=logit,random_state=42)logit_bc = bc.fit(tr.drop(['Class'],1),tr.Class)" }, { "code": null, "e": 6820, "s": 6651, "text": "Now we implement the probability calibration method using Bayes Minimum Risk. Here we create beta (minority selection ratio), tau (threshold) and calibration functions." }, { "code": null, "e": 7177, "s": 6820, "text": "# BMR (Bayes Minimum Risk) implementation# Pozzolo et al., 2015, Calibrating Probability with Undersamplingclass BMR: def beta(binary_target): return binary_target.sum()/len(binary_target) def tau(binary_target, beta): return binary_target.sum()/len(binary_target) def calibration(prob, beta): return prob/(prob+(1-prob)/beta)" }, { "code": null, "e": 7268, "s": 7177, "text": "Apply those calibration techniques to both predicted probabilities by RUS and RUS Bagging." }, { "code": null, "e": 7679, "s": 7268, "text": "# Calibrationbeta = BMR.beta(tr.Class)tau = BMR.tau(tr.Class,beta)# with RUSy_pred_calib_rus = BMR.calibration(prob=logit_rus.predict_proba(te.drop(['Class'],1))[:,1],beta=beta)y_predicted_calib_rus = np.where(y_pred_calib_rus>=tau,1,0)# wtih RUS baggingy_pred_calib_bc = BMR.calibration(prob=logit_bc.predict_proba(te.drop(['Class'],1))[:,1],beta=beta)y_predicted_calib_bc = np.where(y_pred_calib_bc>=tau,1,0)" }, { "code": null, "e": 7826, "s": 7679, "text": "Now we have all the predictions, let’s evaluate them and see how are their performance. I set the thresholds for RUS and RUS bagging model as 0.5." }, { "code": null, "e": 8311, "s": 7826, "text": "# Evaluation## Random Under Sampling (RUS)y_pred_rus, y_predicted_rus = make_prediction(model=logit_rus, X=te.drop(['Class'],1), threshold=.5)evaluation(te.Class, y_predicted_rus)## RUS + Baggingy_pred_bc, y_predicted_bc = make_prediction(model=logit_bc, X=te.drop(['Class'],1), threshold=.5)evaluation(te.Class, y_predicted_bc)## Calibration with Rundom undersamplingevaluation(te.Class, y_predicted_calib_rus)## Calibration with RUS baggingevaluation(te.Class, y_predicted_calib_bc)" }, { "code": null, "e": 8428, "s": 8311, "text": "Here are the results. As we expected, there are so many false positives, which we can see from the precision scores." }, { "code": null, "e": 9045, "s": 8428, "text": "Oh wait, probability calibration didn’t change anything at all? There must be something wrong. Let’s see the prediction distributions of predicted probability of RUS Bagging with calibration. The blue verticle line is the mean of predicted probability by RUS Bagging with calibration and red verticle line is the mean of predicted probability by RUS Bagging model. Obviously their means are quite far away, for calibrated probability mean is 0.0021 and before calibration is 0.5. Considering the positive class exists 0.17% in a whole dataset, the calibrated probability seems quite close to the actual distribution." }, { "code": null, "e": 9285, "s": 9045, "text": "So if we modify the threshold, it should work better and here we can see the results with modified thresholds. Thresholds before calibration and after calibration on RUS model are set at 0.99 and calibration with RUS Bagging is set at 0.8." }, { "code": null, "e": 9455, "s": 9285, "text": "As we can see, after calibration those scores improved, especially the difference between before and after calibration on the random undersampling model are significant." }, { "code": null, "e": 9571, "s": 9455, "text": "So by correcting the biased probability by using probability calibration, we could see the performance improvement." }, { "code": null, "e": 9598, "s": 9571, "text": "3. Conclusion and thoughts" }, { "code": null, "e": 9997, "s": 9598, "text": "In this blog post, we went through Pozzolo, et al. (2015). This answers our experience that having more false positive after applying random undersampling. It was quite interesting to see how the resampling method biases the distribution. This would be causing a similar problem in time-series problems as the target variable we are predicting can be quite different from when we trained the model." }, { "code": null, "e": 10171, "s": 9997, "text": "Would be interesting to see if this sort of method works for different types of classifiers like tree-based or neural network and also different types of resampling methods." }, { "code": null, "e": 10227, "s": 10171, "text": "The codes for this post is available on my GitHub page." }, { "code": null, "e": 10295, "s": 10227, "text": "Introduced the resampling causes a bias in a posterior distribution" }, { "code": null, "e": 10395, "s": 10295, "text": "Introduced probability calibration method by using Bayes Minimum Risk theory (Pozzoli, et al. 2015)" }, { "code": null, "e": 10429, "s": 10395, "text": "Showed the example of this method" }, { "code": null, "e": 10504, "s": 10429, "text": "Confirmed that this method corrects the bias and improve the model results" } ]
Monte Carlo Method Explained. In this post I will introduce, explain... | by Vatsal | Towards Data Science
In this post, I will introduce, explain and implement the Monte Carlo method to you. This method of simulation is one of my favourites because of its simplicity and yet it’s a refined method to resolve complex problems. It was invented by Stanislaw Ulam, a polish mathematician in the 1940s. It was named after a gambling town in Monaco because the principles of randomness mimic a game of roulette. Monte Carlo simulations are a very common concept to quantify risk in various areas like stock prices, sales forecasting, predictive modelling, etc. Monte Carlo simulations are a method of simulating statistical systems. The method uses randomness in a defined system to evolve and approximate quantities without the need to solve the system analytically. The main concept implied in this method is that a point in a moving system will eventually visit all parts of the space that the system moves in, in a uniform and random sense. This is known as ergodicity. The model predicts by using a range of values in the domain of the problem rather than a specific input. This method leverages distributions of probability (normal, gaussian, uniform, etc.) for any variable which has uncertainty. Based on the number of trials specified, this process of using random values in a domain is repeated numerous times. Generally, the more number of trials, the higher likelihood the outcome will converge to a value. Commonly used in time series analysis for long term predictive modelling. Once all the simulations are complete, you will have a range of possible outcomes with the associated probability of each result occurring. Of the many ways to explain this method, the most common example to explain Monte Carlo simulations is called the Buffon Needle Experiment to approximate the value of π. The experiment is as follows, we randomly drop N number of needles of size L onto a piece of paper which is divided by parallel strips of length 2L. After randomly dropping these needles, identify number of needles which touch the lines dividing the paper and the total number of needles dropped (N). π ≈ N / number of needles crossed lineNote : 1) A large amount of needles must be dropped to have a close approximation of π.2) This formulation strictly works because we initially stated that the distance between the lines was 2 * L (where L is the length of the needle) An excellent in-depth explanation of the mathematics behind this can be found here and you can run the experiment for free here. Be cautious, this example is just to explain the Monte Carlo method. Monte Carlo method can be used in many different situations but is not always advised. Although this approach works, in actuality this is a poor use case of the Monte Carlo method. There are many other ways one can approximate the value of π and most of them are a lot more computationally efficient. The situations when you should use this method is when you need to estimate an outcome where there is a high level of uncertainty in the result. This methodology is commonly used in the finance industry for stock forecasting due to the level of randomness and uncertainty in the stock market. Due to these constraints, a model like this is favoured and often out performs a common regression based approach. In situations of uncertainty, this method is quite effective. Identify the independent and dependent variables and define their domain of possible inputs.Determine a probability distribution to randomly generate inputs over the domainCompute the output for the problem based on the randomly generated inputsRepeat the experiment N number of times and aggregate the results Identify the independent and dependent variables and define their domain of possible inputs. Determine a probability distribution to randomly generate inputs over the domain Compute the output for the problem based on the randomly generated inputs Repeat the experiment N number of times and aggregate the results It’s common practice to calculate the variance and standard deviation when conducting this experiment. Generally, the smaller the variance, the better I will outline few of the most notable advantages and disadvantages of using this method. Advantages Strong way of estimating uncertainty Given the correct boundaries, this model can survey the parameter space of problem Simple & intuitive, this approach is quite easy to understand Disadvantages Computationally inefficient — when you have a large amount of variables bounded to different constraints, it requires a lot of time and a lot of computations to approximate a solution using this method If poor parameters and constraints are input into the model then poor results will be given as outputs In summary, this article outlines that the Monte Carlo simulations are a method of simulating statistical systems. They utilize randomness in a defined system to evolve and approximate quantities without the need to solve for it analytically. This method is best used when there are high levels of uncertainty. Although it is quite computationally inefficient, it is very intuitive to understand, can survey a large sample of the constraints of the problem and can effectively approximate uncertainty. Due to these reasonings, it is commonly used in the finance industry. https://en.wikipedia.org/wiki/Ergodic_hypothesis https://mathworld.wolfram.com/BuffonsNeedleProblem.html https://jameshoward.us/2019/09/07/monte-carlo-simulation-advantages-and-disadvantages/ If you enjoyed this read then check out my other works as well.
[ { "code": null, "e": 721, "s": 172, "text": "In this post, I will introduce, explain and implement the Monte Carlo method to you. This method of simulation is one of my favourites because of its simplicity and yet it’s a refined method to resolve complex problems. It was invented by Stanislaw Ulam, a polish mathematician in the 1940s. It was named after a gambling town in Monaco because the principles of randomness mimic a game of roulette. Monte Carlo simulations are a very common concept to quantify risk in various areas like stock prices, sales forecasting, predictive modelling, etc." }, { "code": null, "e": 1134, "s": 721, "text": "Monte Carlo simulations are a method of simulating statistical systems. The method uses randomness in a defined system to evolve and approximate quantities without the need to solve the system analytically. The main concept implied in this method is that a point in a moving system will eventually visit all parts of the space that the system moves in, in a uniform and random sense. This is known as ergodicity." }, { "code": null, "e": 1793, "s": 1134, "text": "The model predicts by using a range of values in the domain of the problem rather than a specific input. This method leverages distributions of probability (normal, gaussian, uniform, etc.) for any variable which has uncertainty. Based on the number of trials specified, this process of using random values in a domain is repeated numerous times. Generally, the more number of trials, the higher likelihood the outcome will converge to a value. Commonly used in time series analysis for long term predictive modelling. Once all the simulations are complete, you will have a range of possible outcomes with the associated probability of each result occurring." }, { "code": null, "e": 2112, "s": 1793, "text": "Of the many ways to explain this method, the most common example to explain Monte Carlo simulations is called the Buffon Needle Experiment to approximate the value of π. The experiment is as follows, we randomly drop N number of needles of size L onto a piece of paper which is divided by parallel strips of length 2L." }, { "code": null, "e": 2264, "s": 2112, "text": "After randomly dropping these needles, identify number of needles which touch the lines dividing the paper and the total number of needles dropped (N)." }, { "code": null, "e": 2536, "s": 2264, "text": "π ≈ N / number of needles crossed lineNote : 1) A large amount of needles must be dropped to have a close approximation of π.2) This formulation strictly works because we initially stated that the distance between the lines was 2 * L (where L is the length of the needle)" }, { "code": null, "e": 2665, "s": 2536, "text": "An excellent in-depth explanation of the mathematics behind this can be found here and you can run the experiment for free here." }, { "code": null, "e": 3035, "s": 2665, "text": "Be cautious, this example is just to explain the Monte Carlo method. Monte Carlo method can be used in many different situations but is not always advised. Although this approach works, in actuality this is a poor use case of the Monte Carlo method. There are many other ways one can approximate the value of π and most of them are a lot more computationally efficient." }, { "code": null, "e": 3505, "s": 3035, "text": "The situations when you should use this method is when you need to estimate an outcome where there is a high level of uncertainty in the result. This methodology is commonly used in the finance industry for stock forecasting due to the level of randomness and uncertainty in the stock market. Due to these constraints, a model like this is favoured and often out performs a common regression based approach. In situations of uncertainty, this method is quite effective." }, { "code": null, "e": 3816, "s": 3505, "text": "Identify the independent and dependent variables and define their domain of possible inputs.Determine a probability distribution to randomly generate inputs over the domainCompute the output for the problem based on the randomly generated inputsRepeat the experiment N number of times and aggregate the results" }, { "code": null, "e": 3909, "s": 3816, "text": "Identify the independent and dependent variables and define their domain of possible inputs." }, { "code": null, "e": 3990, "s": 3909, "text": "Determine a probability distribution to randomly generate inputs over the domain" }, { "code": null, "e": 4064, "s": 3990, "text": "Compute the output for the problem based on the randomly generated inputs" }, { "code": null, "e": 4130, "s": 4064, "text": "Repeat the experiment N number of times and aggregate the results" }, { "code": null, "e": 4281, "s": 4130, "text": "It’s common practice to calculate the variance and standard deviation when conducting this experiment. Generally, the smaller the variance, the better" }, { "code": null, "e": 4371, "s": 4281, "text": "I will outline few of the most notable advantages and disadvantages of using this method." }, { "code": null, "e": 4382, "s": 4371, "text": "Advantages" }, { "code": null, "e": 4419, "s": 4382, "text": "Strong way of estimating uncertainty" }, { "code": null, "e": 4502, "s": 4419, "text": "Given the correct boundaries, this model can survey the parameter space of problem" }, { "code": null, "e": 4564, "s": 4502, "text": "Simple & intuitive, this approach is quite easy to understand" }, { "code": null, "e": 4578, "s": 4564, "text": "Disadvantages" }, { "code": null, "e": 4780, "s": 4578, "text": "Computationally inefficient — when you have a large amount of variables bounded to different constraints, it requires a lot of time and a lot of computations to approximate a solution using this method" }, { "code": null, "e": 4883, "s": 4780, "text": "If poor parameters and constraints are input into the model then poor results will be given as outputs" }, { "code": null, "e": 5455, "s": 4883, "text": "In summary, this article outlines that the Monte Carlo simulations are a method of simulating statistical systems. They utilize randomness in a defined system to evolve and approximate quantities without the need to solve for it analytically. This method is best used when there are high levels of uncertainty. Although it is quite computationally inefficient, it is very intuitive to understand, can survey a large sample of the constraints of the problem and can effectively approximate uncertainty. Due to these reasonings, it is commonly used in the finance industry." }, { "code": null, "e": 5504, "s": 5455, "text": "https://en.wikipedia.org/wiki/Ergodic_hypothesis" }, { "code": null, "e": 5560, "s": 5504, "text": "https://mathworld.wolfram.com/BuffonsNeedleProblem.html" }, { "code": null, "e": 5647, "s": 5560, "text": "https://jameshoward.us/2019/09/07/monte-carlo-simulation-advantages-and-disadvantages/" } ]
set count() function in C++ STL - GeeksforGeeks
08 Jun, 2021 The set::count() is a built-in function in C++ STL which returns the number of times an element occurs in the set. It can only return 1 or 0 as the set container contains unique elements only. Syntax: set_name.count(element) Parameters: The function accepts one mandatory parameter element which specifies the element whose count is to be returned. Return Value: The function returns 1 or 0 as the set contains unique elements only. It returns 1 if the value is present in the set container. It returns 0 if it is not present in the container. Time Complexity : Time Complexity for count function is O(log N) where N is the number of elements present in the set Difference between count and find function in a set is count returns 0 or 1 depending upon whether element is not present or present respectively whereas find function returns a iterator pointing to the value if present else next to the last value in the set.Below is the illustration of the above function. CPP // CPP program to demonstrate the// set::count() function#include <bits/stdc++.h>using namespace std;int main(){ int arr[] = { 14, 12, 15, 11, 10 }; // initializes the set from an array set<int> s(arr, arr + 5); // check if 11 is present or not if (s.count(11)) cout << "11 is present in the set\n"; else cout << "11 is not present in the set\n"; // checks if 18 is present or not if (s.count(18)) cout << "18 is present in the set\n"; else cout << "18 is not present in the set\n"; return 0;} 11 is present in the set 18 is not present in the set noah28 CPP-Functions cpp-set STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Constructors in C++ Socket Programming in C/C++ Virtual Function in C++ Multidimensional Arrays in C / C++ Templates in C++ with Examples Copy Constructor in C++ rand() and srand() in C/C++ Polymorphism in C++ C++ Data Types
[ { "code": null, "e": 24510, "s": 24482, "text": "\n08 Jun, 2021" }, { "code": null, "e": 24713, "s": 24510, "text": "The set::count() is a built-in function in C++ STL which returns the number of times an element occurs in the set. It can only return 1 or 0 as the set container contains unique elements only. Syntax: " }, { "code": null, "e": 24738, "s": 24713, "text": "set_name.count(element) " }, { "code": null, "e": 25058, "s": 24738, "text": "Parameters: The function accepts one mandatory parameter element which specifies the element whose count is to be returned. Return Value: The function returns 1 or 0 as the set contains unique elements only. It returns 1 if the value is present in the set container. It returns 0 if it is not present in the container. " }, { "code": null, "e": 25176, "s": 25058, "text": "Time Complexity : Time Complexity for count function is O(log N) where N is the number of elements present in the set" }, { "code": null, "e": 25485, "s": 25176, "text": "Difference between count and find function in a set is count returns 0 or 1 depending upon whether element is not present or present respectively whereas find function returns a iterator pointing to the value if present else next to the last value in the set.Below is the illustration of the above function. " }, { "code": null, "e": 25489, "s": 25485, "text": "CPP" }, { "code": "// CPP program to demonstrate the// set::count() function#include <bits/stdc++.h>using namespace std;int main(){ int arr[] = { 14, 12, 15, 11, 10 }; // initializes the set from an array set<int> s(arr, arr + 5); // check if 11 is present or not if (s.count(11)) cout << \"11 is present in the set\\n\"; else cout << \"11 is not present in the set\\n\"; // checks if 18 is present or not if (s.count(18)) cout << \"18 is present in the set\\n\"; else cout << \"18 is not present in the set\\n\"; return 0;}", "e": 26046, "s": 25489, "text": null }, { "code": null, "e": 26100, "s": 26046, "text": "11 is present in the set\n18 is not present in the set" }, { "code": null, "e": 26109, "s": 26102, "text": "noah28" }, { "code": null, "e": 26123, "s": 26109, "text": "CPP-Functions" }, { "code": null, "e": 26131, "s": 26123, "text": "cpp-set" }, { "code": null, "e": 26135, "s": 26131, "text": "STL" }, { "code": null, "e": 26139, "s": 26135, "text": "C++" }, { "code": null, "e": 26143, "s": 26139, "text": "STL" }, { "code": null, "e": 26147, "s": 26143, "text": "CPP" }, { "code": null, "e": 26245, "s": 26147, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26273, "s": 26245, "text": "Operator Overloading in C++" }, { "code": null, "e": 26293, "s": 26273, "text": "Constructors in C++" }, { "code": null, "e": 26321, "s": 26293, "text": "Socket Programming in C/C++" }, { "code": null, "e": 26345, "s": 26321, "text": "Virtual Function in C++" }, { "code": null, "e": 26380, "s": 26345, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26411, "s": 26380, "text": "Templates in C++ with Examples" }, { "code": null, "e": 26435, "s": 26411, "text": "Copy Constructor in C++" }, { "code": null, "e": 26463, "s": 26435, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 26483, "s": 26463, "text": "Polymorphism in C++" } ]
HTML5 | MathML Introduction - GeeksforGeeks
19 May, 2020 The MathML comes in the HTML5 the current MathML version is 3 it was introduced in the year of 2015. The MathML stands for Mathematics Markup Language. It is used to represent the mathematical equation or expression in web browsers like other HTML elements. The 1st version of MathML released in the year of 1998 and after that in the 2nd version was released. Basically MathML is a complex mathematical formula or equation visual representation made easy. The MathML is supported in the HTML5, all the MathML tag must be used inside the <math> and </math> tags. The MathML is used to describing mathematics as a basis for the machine to machine communication, it is intended handling by specialized authoring tools such as equation editors and it is meaningful to other applications also. MathML is not-capable: The MathML is not a calculator to calculate or solve complex equation it is just a way to show the equation. It is not a programming language it is a Mathematics Markup Language. MathML is capable: The MathML can be used to represent the Matrix form. The MathML can be used to represent the Partial Differential Equation. The MathML can be used to represent the Chemical Reaction Equation. Below example gives you a brief idea about MathML:Example: <!DOCTYPE html><html> <head> <title>HTML5 MathML</title></head> <body style="text-align:center;"> <h1 style="color:green"> GeeksforGeeks </h1> <h3>HTML5 MathML</h3> <!--start tag of the whole representation--> <math> <!-- Creating Matrix --> <mrow> <mi>A</mi> <mo>=</mo> <mfenced open="[" close="]"> <mtable> <mtr> <mtd> <mi>a</mi> </mtd> <mtd> <mi>b</mi> </mtd> </mtr> <mtr> <mtd> <mi>x</mi> </mtd> <mtd> <mi>y</mi> </mtd> </mtr> </mtable> </mfenced> </mrow> <!-- Creating equation --> <br><br> <msub> <mi>Geeks</mi> <mn>4</mn> </msub> <mo>+</mo> <mn>Geeks</mn> <mo>=</mo> <msub> <mi>G</mi> </msub> <mo>→</mo> <msub> <mi>e</mi> <mn>2</mn> </msub> <mo>→</mo> <mi>k</mi> <mi>s</mi> <mn>4 </mn> <msub> <mi>G</mi> </msub> <mo>→</mo> <msub> <mi>e</mi> <mn>2</mn> </msub> <mo>→</mo> <mi>k</mi> <mi>s</mi> </math></body> </html> Output:Note: There are almost 30+ MathML tags available. All the tags aew lised below in table format: Supported Browsers: The browsers supported by HTML5 MathML tags are listed below: Firefox Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-MathML HTML5 HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 30376, "s": 30348, "text": "\n19 May, 2020" }, { "code": null, "e": 30939, "s": 30376, "text": "The MathML comes in the HTML5 the current MathML version is 3 it was introduced in the year of 2015. The MathML stands for Mathematics Markup Language. It is used to represent the mathematical equation or expression in web browsers like other HTML elements. The 1st version of MathML released in the year of 1998 and after that in the 2nd version was released. Basically MathML is a complex mathematical formula or equation visual representation made easy. The MathML is supported in the HTML5, all the MathML tag must be used inside the <math> and </math> tags." }, { "code": null, "e": 31166, "s": 30939, "text": "The MathML is used to describing mathematics as a basis for the machine to machine communication, it is intended handling by specialized authoring tools such as equation editors and it is meaningful to other applications also." }, { "code": null, "e": 31189, "s": 31166, "text": "MathML is not-capable:" }, { "code": null, "e": 31298, "s": 31189, "text": "The MathML is not a calculator to calculate or solve complex equation it is just a way to show the equation." }, { "code": null, "e": 31368, "s": 31298, "text": "It is not a programming language it is a Mathematics Markup Language." }, { "code": null, "e": 31387, "s": 31368, "text": "MathML is capable:" }, { "code": null, "e": 31440, "s": 31387, "text": "The MathML can be used to represent the Matrix form." }, { "code": null, "e": 31511, "s": 31440, "text": "The MathML can be used to represent the Partial Differential Equation." }, { "code": null, "e": 31579, "s": 31511, "text": "The MathML can be used to represent the Chemical Reaction Equation." }, { "code": null, "e": 31638, "s": 31579, "text": "Below example gives you a brief idea about MathML:Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML5 MathML</title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h3>HTML5 MathML</h3> <!--start tag of the whole representation--> <math> <!-- Creating Matrix --> <mrow> <mi>A</mi> <mo>=</mo> <mfenced open=\"[\" close=\"]\"> <mtable> <mtr> <mtd> <mi>a</mi> </mtd> <mtd> <mi>b</mi> </mtd> </mtr> <mtr> <mtd> <mi>x</mi> </mtd> <mtd> <mi>y</mi> </mtd> </mtr> </mtable> </mfenced> </mrow> <!-- Creating equation --> <br><br> <msub> <mi>Geeks</mi> <mn>4</mn> </msub> <mo>+</mo> <mn>Geeks</mn> <mo>=</mo> <msub> <mi>G</mi> </msub> <mo>→</mo> <msub> <mi>e</mi> <mn>2</mn> </msub> <mo>→</mo> <mi>k</mi> <mi>s</mi> <mn>4 </mn> <msub> <mi>G</mi> </msub> <mo>→</mo> <msub> <mi>e</mi> <mn>2</mn> </msub> <mo>→</mo> <mi>k</mi> <mi>s</mi> </math></body> </html>", "e": 33254, "s": 31638, "text": null }, { "code": null, "e": 33357, "s": 33254, "text": "Output:Note: There are almost 30+ MathML tags available. All the tags aew lised below in table format:" }, { "code": null, "e": 33439, "s": 33357, "text": "Supported Browsers: The browsers supported by HTML5 MathML tags are listed below:" }, { "code": null, "e": 33447, "s": 33439, "text": "Firefox" }, { "code": null, "e": 33584, "s": 33447, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 33596, "s": 33584, "text": "HTML-MathML" }, { "code": null, "e": 33602, "s": 33596, "text": "HTML5" }, { "code": null, "e": 33607, "s": 33602, "text": "HTML" }, { "code": null, "e": 33624, "s": 33607, "text": "Web Technologies" }, { "code": null, "e": 33629, "s": 33624, "text": "HTML" }, { "code": null, "e": 33727, "s": 33629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33736, "s": 33727, "text": "Comments" }, { "code": null, "e": 33749, "s": 33736, "text": "Old Comments" }, { "code": null, "e": 33811, "s": 33749, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33861, "s": 33811, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33909, "s": 33861, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33969, "s": 33909, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34030, "s": 33969, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 34072, "s": 34030, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 34105, "s": 34072, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34167, "s": 34105, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34210, "s": 34167, "text": "How to fetch data from an API in ReactJS ?" } ]
Program to Count number of binary strings without consecutive 1’s in C/C++?
Here we will see one interesting problem. Suppose one value of n is given. We have to find all strings of length n, such that there are no consecutive 1s. If n = 2, then the numbers are {00, 01, 10}, So output is 3. We can solve it using dynamic programming. Suppose we have a tables ‘a’ and ‘b’. Where arr[i] is storing the number of binary strings of length i, where no consecutive 1s are present, and ending with 0. Similarly, b is holding the same but numbers ending with 1. We can append 0 or 1 where last one is 0, but add only 0 if the last one is 1. Let us see the algorithm to get this idea. noConsecutiveOnes(n) − Begin define array a and b of size n a[0] := 1 b[0] := 1 for i in range 1 to n, do a[i] := a[i-1] + b[i - 1] b[i] := a[i - 1] done return a[n-1] + b[n-1] End #include <iostream> using namespace std; int noConsecutiveOnes(int n) { int a[n], b[n]; a[0] = 1; b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i-1] + b[i-1]; b[i] = a[i-1]; } return a[n-1] + b[n-1]; } int main() { cout << noConsecutiveOnes(4) << endl; } 8
[ { "code": null, "e": 1278, "s": 1062, "text": "Here we will see one interesting problem. Suppose one value of n is given. We have to find all strings of length n, such that there are no consecutive 1s. If n = 2, then the numbers are {00, 01, 10}, So output is 3." }, { "code": null, "e": 1620, "s": 1278, "text": "We can solve it using dynamic programming. Suppose we have a tables ‘a’ and ‘b’. Where arr[i] is storing the number of binary strings of length i, where no consecutive 1s are present, and ending with 0. Similarly, b is holding the same but numbers ending with 1. We can append 0 or 1 where last one is 0, but add only 0 if the last one is 1." }, { "code": null, "e": 1663, "s": 1620, "text": "Let us see the algorithm to get this idea." }, { "code": null, "e": 1686, "s": 1663, "text": "noConsecutiveOnes(n) −" }, { "code": null, "e": 1874, "s": 1686, "text": "Begin\n define array a and b of size n\n a[0] := 1\n b[0] := 1\n for i in range 1 to n, do\n a[i] := a[i-1] + b[i - 1]\n b[i] := a[i - 1]\n done\n return a[n-1] + b[n-1]\nEnd" }, { "code": null, "e": 2165, "s": 1874, "text": "#include <iostream>\nusing namespace std;\nint noConsecutiveOnes(int n) {\n int a[n], b[n];\n a[0] = 1;\n b[0] = 1;\n for (int i = 1; i < n; i++) {\n a[i] = a[i-1] + b[i-1];\n b[i] = a[i-1];\n }\n return a[n-1] + b[n-1];\n}\nint main() {\n cout << noConsecutiveOnes(4) << endl;\n}" }, { "code": null, "e": 2167, "s": 2165, "text": "8" } ]
How to send data from one activity to another in Android without intent?
This example demonstrate about How to send data from one activity to another in Android without intent. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".MainActivity"> <EditText android:id = "@+id/edit_text" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:hint = "Enter something to pass" android:inputType = "text" /> <Button android:id = "@+id/button" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_gravity = "center" android:layout_marginTop = "16dp" android:text = "Next" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { private static String value; public static String getValue() { return value; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText editText = findViewById(R.id.edit_text); Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { value = editText.getText().toString().trim(); Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } }); } } Step 4 − Add the following code to res/layout/activity_second.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".SecondActivity"> <TextView android:id = "@+id/text_view" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" /> </LinearLayout> Step 5 − Add the following code to src/SecondActivity.java package com.example.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); TextView textView = findViewById(R.id.text_view); textView.setText(MainActivity.getValue()); } } Step 6 − Add the following code to androidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name = ".SecondActivity"></activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – This example demonstrate about How to send data from one activity to another in Android using sharedPreferences. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".MainActivity"> <EditText android:id = "@+id/edit_text" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:hint = "Enter something to pass" android:inputType = "text" /> <Button android:id = "@+id/button" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_gravity = "center" android:layout_marginTop = "16dp" android:text = "Next" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText editText = findViewById(R.id.edit_text); Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String value = editText.getText().toString().trim(); SharedPreferences sharedPref = getSharedPreferences("myKey", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString("value", value); editor.apply(); Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } }); } } Step 4 − Add the following code to res/layout/activity_second.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".SecondActivity"> <TextView android:id = "@+id/text_view" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" /> </LinearLayout> Step 5 − Add the following code to src/SecondActivity.java package com.example.myapplication; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); TextView textView = findViewById(R.id.text_view); SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE); String value = sharedPreferences.getString("value",""); textView.setText(value); } } Step 6 − Add the following code to androidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name = ".SecondActivity"></activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code Click here to download the project code Click here to download the project code Click here to download the project code
[ { "code": null, "e": 1166, "s": 1062, "text": "This example demonstrate about How to send data from one activity to another in Android without intent." }, { "code": null, "e": 1295, "s": 1166, "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": 1360, "s": 1295, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2240, "s": 1360, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".MainActivity\">\n <EditText\n android:id = \"@+id/edit_text\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:hint = \"Enter something to pass\"\n android:inputType = \"text\" />\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:layout_marginTop = \"16dp\"\n android:text = \"Next\" />\n</LinearLayout>" }, { "code": null, "e": 2297, "s": 2240, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3264, "s": 2297, "text": "package com.example.myapplication;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\n\npublic class MainActivity extends AppCompatActivity {\n private static String value;\n public static String getValue() {\n return value;\n }\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final EditText editText = findViewById(R.id.edit_text);\n Button button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n value = editText.getText().toString().trim();\n Intent intent = new Intent(MainActivity.this, SecondActivity.class);\n startActivity(intent);\n }\n });\n }\n}" }, { "code": null, "e": 3331, "s": 3264, "text": "Step 4 − Add the following code to res/layout/activity_second.xml." }, { "code": null, "e": 3889, "s": 3331, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".SecondActivity\">\n <TextView\n android:id = \"@+id/text_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\" />\n</LinearLayout>" }, { "code": null, "e": 3948, "s": 3889, "text": "Step 5 − Add the following code to src/SecondActivity.java" }, { "code": null, "e": 4418, "s": 3948, "text": "package com.example.myapplication;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\n\npublic class SecondActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n TextView textView = findViewById(R.id.text_view);\n textView.setText(MainActivity.getValue());\n }\n}" }, { "code": null, "e": 4473, "s": 4418, "text": "Step 6 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5244, "s": 4473, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <activity android:name = \".SecondActivity\"></activity>\n </application>\n</manifest>" }, { "code": null, "e": 5593, "s": 5244, "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": 5706, "s": 5593, "text": "This example demonstrate about How to send data from one activity to another in Android using sharedPreferences." }, { "code": null, "e": 5835, "s": 5706, "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": 5900, "s": 5835, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 6780, "s": 5900, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".MainActivity\">\n <EditText\n android:id = \"@+id/edit_text\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:hint = \"Enter something to pass\"\n android:inputType = \"text\" />\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:layout_marginTop = \"16dp\"\n android:text = \"Next\" />\n</LinearLayout>" }, { "code": null, "e": 6837, "s": 6780, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 7986, "s": 6837, "text": "package com.example.myapplication;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final EditText editText = findViewById(R.id.edit_text);\n Button button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String value = editText.getText().toString().trim();\n SharedPreferences sharedPref = getSharedPreferences(\"myKey\", MODE_PRIVATE);\n SharedPreferences.Editor editor = sharedPref.edit();\n editor.putString(\"value\", value);\n editor.apply();\n Intent intent = new Intent(MainActivity.this, SecondActivity.class);\n startActivity(intent);\n }\n });\n }\n}" }, { "code": null, "e": 8053, "s": 7986, "text": "Step 4 − Add the following code to res/layout/activity_second.xml." }, { "code": null, "e": 8611, "s": 8053, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".SecondActivity\">\n <TextView\n android:id = \"@+id/text_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\" />\n</LinearLayout>" }, { "code": null, "e": 8670, "s": 8611, "text": "Step 5 − Add the following code to src/SecondActivity.java" }, { "code": null, "e": 9315, "s": 8670, "text": "package com.example.myapplication;\nimport android.content.SharedPreferences;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\n\npublic class SecondActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n TextView textView = findViewById(R.id.text_view);\n SharedPreferences sharedPreferences = getSharedPreferences(\"myKey\", MODE_PRIVATE);\n String value = sharedPreferences.getString(\"value\",\"\");\n textView.setText(value);\n }\n}" }, { "code": null, "e": 9370, "s": 9315, "text": "Step 6 − Add the following code to androidManifest.xml" }, { "code": null, "e": 10141, "s": 9370, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <activity android:name = \".SecondActivity\"></activity>\n </application>\n</manifest>" }, { "code": null, "e": 10488, "s": 10141, "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": 10528, "s": 10488, "text": "Click here to download the project code" }, { "code": null, "e": 10568, "s": 10528, "text": "Click here to download the project code" }, { "code": null, "e": 10608, "s": 10568, "text": "Click here to download the project code" }, { "code": null, "e": 10648, "s": 10608, "text": "Click here to download the project code" } ]
VBA - Concatenation Operators
Following Concatenation operators are supported by VBA. Assume variable A holds 5 and variable B holds 10 then − Try the following example to understand the Concatenation operator available in VBScript − Private Sub Constant_demo_Click() Dim a as Integer : a = 5 Dim b as Integer : b = 10 Dim c as Integer c = a + b msgbox ("Concatenated value:1 is " &c) 'Numeric addition c = a & b msgbox ("Concatenated value:2 is " &c) 'Concatenate two numbers End Sub Try the following example to understand all the Logical operators available in VBA by creating a button and adding the following function. Concatenated value:1 is 15 Concatenated value:2 is 510 Concatenation can also be used for concatenating two strings. Assume variable A = "Microsoft" and variable B = "VBScript" then − Try the following example to understand all the Logical operators available in VBA by creating a button and adding the following function. Private Sub Constant_demo_Click() Dim a as String : a = "Microsoft" Dim b as String : b = "VBScript" Dim c as String c = a + b msgbox("Concatenated value:1 is " &c) 'addition of two Strings c = a & b msgbox("Concatenated value:2 is " &c) 'Concatenate two String End Sub When you save it as .html and execute it in the Internet Explorer, then the above script will produce the following result. Concatenated value:1 is MicrosoftVBScript Concatenated value:2 is MicrosoftVBScript 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 1991, "s": 1935, "text": "Following Concatenation operators are supported by VBA." }, { "code": null, "e": 2048, "s": 1991, "text": "Assume variable A holds 5 and variable B holds 10 then −" }, { "code": null, "e": 2139, "s": 2048, "text": "Try the following example to understand the Concatenation operator available in VBScript −" }, { "code": null, "e": 2421, "s": 2139, "text": "Private Sub Constant_demo_Click()\n Dim a as Integer : a = 5\n Dim b as Integer : b = 10\n Dim c as Integer\n\n c = a + b \n msgbox (\"Concatenated value:1 is \" &c) 'Numeric addition \n \n c = a & b \n msgbox (\"Concatenated value:2 is \" &c) 'Concatenate two numbers \nEnd Sub" }, { "code": null, "e": 2560, "s": 2421, "text": "Try the following example to understand all the Logical operators available in VBA by creating a button and adding the following function." }, { "code": null, "e": 2617, "s": 2560, "text": "Concatenated value:1 is 15\n\nConcatenated value:2 is 510\n" }, { "code": null, "e": 2746, "s": 2617, "text": "Concatenation can also be used for concatenating two strings. Assume variable A = \"Microsoft\" and variable B = \"VBScript\" then −" }, { "code": null, "e": 2885, "s": 2746, "text": "Try the following example to understand all the Logical operators available in VBA by creating a button and adding the following function." }, { "code": null, "e": 3183, "s": 2885, "text": "Private Sub Constant_demo_Click()\n Dim a as String : a = \"Microsoft\"\n Dim b as String : b = \"VBScript\"\n Dim c as String\n\n c = a + b \n msgbox(\"Concatenated value:1 is \" &c) 'addition of two Strings\n \n c = a & b \n msgbox(\"Concatenated value:2 is \" &c) 'Concatenate two String\nEnd Sub" }, { "code": null, "e": 3307, "s": 3183, "text": "When you save it as .html and execute it in the Internet Explorer, then the above script will produce the following result." }, { "code": null, "e": 3393, "s": 3307, "text": "Concatenated value:1 is MicrosoftVBScript\n\nConcatenated value:2 is MicrosoftVBScript\n" }, { "code": null, "e": 3427, "s": 3393, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 3442, "s": 3427, "text": " Pavan Lalwani" }, { "code": null, "e": 3475, "s": 3442, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 3490, "s": 3475, "text": " Arnold Higuit" }, { "code": null, "e": 3525, "s": 3490, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3543, "s": 3525, "text": " Prashant Panchal" }, { "code": null, "e": 3576, "s": 3543, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 3594, "s": 3576, "text": " Prashant Panchal" }, { "code": null, "e": 3627, "s": 3594, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 3642, "s": 3627, "text": " Arnold Higuit" }, { "code": null, "e": 3678, "s": 3642, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 3706, "s": 3678, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 3713, "s": 3706, "text": " Print" }, { "code": null, "e": 3724, "s": 3713, "text": " Add Notes" } ]
What is the difference between a python module and a python package?
Any Python file is a module, its name being the file's base name/module's __name__ property without the .py extension. A package is a collection of Python modules, i.e., a package is a directory of Python modules containing an additional __init__.py file. The __init__.py distinguishes a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file. When you import a module or a package, the corresponding object created by Python is always of type module. This means that the distinction between module and package is just at the file system level. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules. For example, in the datetime module, there is a submodule called date. When you import datetime, it won't be imported. You'll need to import it separately. >>> import datetime >>> date.today() Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'date' is not defined >>> from datetime import date >>> date.today() datetime.date(2017, 9, 1)
[ { "code": null, "e": 1548, "s": 1062, "text": "Any Python file is a module, its name being the file's base name/module's __name__ property without the .py extension. A package is a collection of Python modules, i.e., a package is a directory of Python modules containing an additional __init__.py file. The __init__.py distinguishes a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file." }, { "code": null, "e": 1915, "s": 1548, "text": "When you import a module or a package, the corresponding object created by Python is always of type module. This means that the distinction between module and package is just at the file system level. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules." }, { "code": null, "e": 2071, "s": 1915, "text": "For example, in the datetime module, there is a submodule called date. When you import datetime, it won't be imported. You'll need to import it separately." }, { "code": null, "e": 2292, "s": 2071, "text": ">>> import datetime\n>>> date.today()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'date' is not defined\n>>> from datetime import date\n>>> date.today()\ndatetime.date(2017, 9, 1)" } ]
Java Examples - Exception with overloaded Methods
How to handle the exception with overloaded methods ? This example shows how to handle the exception with overloaded methods. You need to have a try catch block in each method or where the are used. public class Main { double method(int i) throws Exception { return i/0; } boolean method(boolean b) { return !b; } static double method(int x, double y) throws Exception { return x + y ; } static double method(double x, double y) { return x + y - 3; } public static void main(String[] args) { Main mn = new Main(); try { System.out.println(method(10, 20.0)); System.out.println(method(10.0, 20)); System.out.println(method(10.0, 20.0)); System.out.println(mn.method(10)); } catch (Exception ex) { System.out.println("exception occoure: "+ ex); } } } The above code sample will produce the following result. 30.0 27.0 27.0 exception occoure: java.lang.ArithmeticException: / by zero The following is an another example to handle the exception with overloaded methods in Java class NewClass1 { void msg()throws Exception{System.out.println("this is parent");} } public class NewClass extends NewClass1 { NewClass() { } void msg()throws ArithmeticException{System.out.println("This is child");} public static void main(String args[]) { NewClass1 n = new NewClass(); try { n.msg(); } catch(Exception e){} } } The above code sample will produce the following result. This is child Print Add Notes Bookmark this page
[ { "code": null, "e": 2122, "s": 2068, "text": "How to handle the exception with overloaded methods ?" }, { "code": null, "e": 2267, "s": 2122, "text": "This example shows how to handle the exception with overloaded methods. You need to have a try catch block in each method or where the are used." }, { "code": null, "e": 2943, "s": 2267, "text": "public class Main {\n double method(int i) throws Exception {\n return i/0;\n }\n boolean method(boolean b) {\n return !b;\n }\n static double method(int x, double y) throws Exception {\n return x + y ;\n }\n static double method(double x, double y) {\n return x + y - 3;\n } \n public static void main(String[] args) {\n Main mn = new Main();\n try {\n System.out.println(method(10, 20.0));\n System.out.println(method(10.0, 20));\n System.out.println(method(10.0, 20.0));\n System.out.println(mn.method(10));\n } catch (Exception ex) {\n System.out.println(\"exception occoure: \"+ ex);\n }\n }\n}" }, { "code": null, "e": 3000, "s": 2943, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3076, "s": 3000, "text": "30.0\n27.0\n27.0\nexception occoure: java.lang.ArithmeticException: / by zero\n" }, { "code": null, "e": 3168, "s": 3076, "text": "The following is an another example to handle the exception with overloaded methods in Java" }, { "code": null, "e": 3547, "s": 3168, "text": "class NewClass1 { \n void msg()throws Exception{System.out.println(\"this is parent\");}\n}\npublic class NewClass extends NewClass1 {\n NewClass() {\n }\n void msg()throws ArithmeticException{System.out.println(\"This is child\");}\n public static void main(String args[]) {\n NewClass1 n = new NewClass();\n try {\n n.msg();\n } catch(Exception e){}\n } \n}" }, { "code": null, "e": 3604, "s": 3547, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3619, "s": 3604, "text": "This is child\n" }, { "code": null, "e": 3626, "s": 3619, "text": " Print" }, { "code": null, "e": 3637, "s": 3626, "text": " Add Notes" } ]
Passing and Returning Objects in Java
As we know it is core concept that in Java there is always pass by value and not by pass by reference.So in this post we will focus on that how this concept get validated in case of passing primitive and passing reference to a method. In case when a primitive type is passed to a method as argument then the value assigned to this primitive is get passed to the method and that value becomes local to that method,which means that any change to that value by the method would not change the value of primitive that you have passed to the method. While in case of passing reference to a method again Java follow the same rule of pass by value now let understand how it happens. As we know that a reference in Java holds the memory location of object created if it is assigned to that reference otherwise it is initiated as null.Now the point to remember here is that the value of the reference is the memory location of the assigned object,so whenever we pass the reference to any method as argument then we actually pass the memory location of that object which is assigned to that particular reference.This technically means that the target method has memory location of our created object and can access it to.So in case if target method access our object and make changes to any of property of it than we would encounter with the changed value in our original object. Live Demo public class PassByValue { static int k =10; static void passPrimitive(int j) { System.out.println("the value of passed primitive is " + j); j = j + 1; } static void passReference(EmployeeTest emp) { EmployeeTest reference = emp; System.out.println("the value of name property of our object is "+ emp.getName()); reference.setName("Bond"); } public static void main(String[] args) { EmployeeTest ref = new EmployeeTest(); ref.setName("James"); passPrimitive(k); System.out.println("Value of primitive after get passed to method is "+ k); passReference(ref); System.out.println("Value of property of object after reference get passed to method is "+ ref.getName()); } } class EmployeeTest { String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } the value of passed primitive is 10 Value of primitive after get passed to method is 10 the value of name property of our object is James Value of property of object after reference get passed to method is Bond
[ { "code": null, "e": 1297, "s": 1062, "text": "As we know it is core concept that in Java there is always pass by value and not by pass by reference.So in this post we will focus on that how this concept get validated in case of passing primitive and passing reference to a method." }, { "code": null, "e": 1607, "s": 1297, "text": "In case when a primitive type is passed to a method as argument then the value assigned to this primitive is get passed to the method and that value becomes local to that method,which means that any change to that value by the method would not change the value of primitive that you have passed to the method." }, { "code": null, "e": 1738, "s": 1607, "text": "While in case of passing reference to a method again Java follow the same rule of pass by value now let understand how it happens." }, { "code": null, "e": 2432, "s": 1738, "text": "As we know that a reference in Java holds the memory location of object created if it is assigned to that reference otherwise it is initiated as null.Now the point to remember here is that the value of the reference is the memory location of the assigned object,so whenever we pass the reference to any method as argument then we actually pass the memory location of that object which is assigned to that particular reference.This technically means that the target method has memory location of our created object and can access it to.So in case if target method access our object and make changes to any of property of it than we would encounter with the changed value in our original object." }, { "code": null, "e": 2443, "s": 2432, "text": " Live Demo" }, { "code": null, "e": 3367, "s": 2443, "text": "public class PassByValue {\n static int k =10;\n static void passPrimitive(int j) {\n System.out.println(\"the value of passed primitive is \" + j);\n j = j + 1;\n }\n static void passReference(EmployeeTest emp) {\n EmployeeTest reference = emp;\n System.out.println(\"the value of name property of our object is \"+ emp.getName());\n reference.setName(\"Bond\");\n }\n public static void main(String[] args) {\n EmployeeTest ref = new EmployeeTest();\n ref.setName(\"James\");\n passPrimitive(k);\n System.out.println(\"Value of primitive after get passed to method is \"+ k);\n passReference(ref);\n System.out.println(\"Value of property of object after reference get passed to method is \"+ ref.getName());\n }\n}\nclass EmployeeTest {\n String name;\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 3578, "s": 3367, "text": "the value of passed primitive is 10\nValue of primitive after get passed to method is 10\nthe value of name property of our object is James\nValue of property of object after reference get passed to method is Bond" } ]
SQL | UNION Operator
28 Aug, 2020 The UNION operator could be used to find the result-set or combination of two or more tables. Terms and Condition for using UNION : Each table used within UNION must have the same number of columns. The columns must have same data types. The columns in each table must be in the same order. 1. UNION Syntax : SELECT columnnames FROM table1 UNION SELECT columnnames FROM table2; UNION operator provides only unique values by default. To find duplicate values, use UNION ALL : 2. UNION ALL Syntax : SELECT columnnames FROM table1 UNION ALL SELECT columnnames FROM table2; Let’s assume we have two tables “Geeks1” and “Geeks2”; Select * from Geeks1; Select * from Geeks2; SQL UNION Example –The below SQL statement finds the cities (only unique values) from both the “Geeks1” and the “Geeks2” table : Example – SELECT City FROM Geeks1 UNION SELECT City FROM Geeks2 ORDER BY City; Output – SQL UNION ALL Example –The below SQL statement finds the cities (duplicate values also) from both the “Geeks1” and the “Geeks2” table : Example – SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER BY City; Output – DBMS-SQL DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Difference between OLAP and OLTP in DBMS MySQL | Regular expressions (Regexp) What is Temporary Table in SQL? SQL | DDL, DML, TCL and DCL SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? SQL | Sub queries in From Clause
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Aug, 2020" }, { "code": null, "e": 147, "s": 53, "text": "The UNION operator could be used to find the result-set or combination of two or more tables." }, { "code": null, "e": 185, "s": 147, "text": "Terms and Condition for using UNION :" }, { "code": null, "e": 252, "s": 185, "text": "Each table used within UNION must have the same number of columns." }, { "code": null, "e": 291, "s": 252, "text": "The columns must have same data types." }, { "code": null, "e": 344, "s": 291, "text": "The columns in each table must be in the same order." }, { "code": null, "e": 362, "s": 344, "text": "1. UNION Syntax :" }, { "code": null, "e": 432, "s": 362, "text": "SELECT columnnames FROM table1\nUNION\nSELECT columnnames FROM table2;\n" }, { "code": null, "e": 529, "s": 432, "text": "UNION operator provides only unique values by default. To find duplicate values, use UNION ALL :" }, { "code": null, "e": 551, "s": 529, "text": "2. UNION ALL Syntax :" }, { "code": null, "e": 625, "s": 551, "text": "SELECT columnnames FROM table1\nUNION ALL\nSELECT columnnames FROM table2;\n" }, { "code": null, "e": 680, "s": 625, "text": "Let’s assume we have two tables “Geeks1” and “Geeks2”;" }, { "code": null, "e": 704, "s": 680, "text": "Select * \nfrom Geeks1; " }, { "code": null, "e": 728, "s": 704, "text": "Select * \nfrom Geeks2; " }, { "code": null, "e": 857, "s": 728, "text": "SQL UNION Example –The below SQL statement finds the cities (only unique values) from both the “Geeks1” and the “Geeks2” table :" }, { "code": null, "e": 867, "s": 857, "text": "Example –" }, { "code": null, "e": 941, "s": 867, "text": "SELECT City \nFROM Geeks1\n\nUNION\n\nSELECT City \nFROM Geeks2\nORDER BY City; " }, { "code": null, "e": 950, "s": 941, "text": "Output –" }, { "code": null, "e": 1086, "s": 950, "text": "SQL UNION ALL Example –The below SQL statement finds the cities (duplicate values also) from both the “Geeks1” and the “Geeks2” table :" }, { "code": null, "e": 1096, "s": 1086, "text": "Example –" }, { "code": null, "e": 1180, "s": 1096, "text": "SELECT City \nFROM Customers\n\nUNION ALL\n\nSELECT City \nFROM Suppliers\nORDER BY City; " }, { "code": null, "e": 1189, "s": 1180, "text": "Output –" }, { "code": null, "e": 1198, "s": 1189, "text": "DBMS-SQL" }, { "code": null, "e": 1203, "s": 1198, "text": "DBMS" }, { "code": null, "e": 1207, "s": 1203, "text": "SQL" }, { "code": null, "e": 1212, "s": 1207, "text": "DBMS" }, { "code": null, "e": 1216, "s": 1212, "text": "SQL" }, { "code": null, "e": 1314, "s": 1216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1355, "s": 1314, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 1396, "s": 1355, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 1433, "s": 1396, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 1465, "s": 1433, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1493, "s": 1465, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 1535, "s": 1493, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 1579, "s": 1535, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 1600, "s": 1579, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 1666, "s": 1600, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
Stack.Contains() Method in C#
04 Feb, 2019 This method(comes under System.Collections namespace) is used to check whether a specified element is present is Stack or not. Internally this method checks for equality by calling the Object.Equals method. Also, it performs a linear search, therefore, this method is an O(n) operation, where n is Count. Syntax: public virtual bool Contains (object obj); Here, obj is the object to locate in the Stack. The value can be null. Return Value: It returns true, if obj is found in the Stack otherwise returns false. Below programs illustrate the use of above-discussed method: Example 1: // C# code to illustrate the// Stack.Contains() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("Geeks"); myStack.Push("Geeks Classes"); myStack.Push("Noida"); myStack.Push("Data Structures"); myStack.Push("GeeksforGeeks"); // Checking whether the element is // present in the Stack or not // The function returns True if the // element is present in the Stack, // else returns False Console.WriteLine(myStack.Contains("GeeksforGeeks")); }} True Example 2: // C# code to illustrate the// Stack.Contains() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements // into the Stack myStack.Push(5); myStack.Push(10); myStack.Push(15); myStack.Push(20); myStack.Push(25); // Checking whether the element is // present in the Stack or not // The function returns True if the // element is present in the Stack, else // returns False Console.WriteLine(myStack.Contains(7)); }} False Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.contains?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Collections-Stack CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Feb, 2019" }, { "code": null, "e": 333, "s": 28, "text": "This method(comes under System.Collections namespace) is used to check whether a specified element is present is Stack or not. Internally this method checks for equality by calling the Object.Equals method. Also, it performs a linear search, therefore, this method is an O(n) operation, where n is Count." }, { "code": null, "e": 341, "s": 333, "text": "Syntax:" }, { "code": null, "e": 384, "s": 341, "text": "public virtual bool Contains (object obj);" }, { "code": null, "e": 455, "s": 384, "text": "Here, obj is the object to locate in the Stack. The value can be null." }, { "code": null, "e": 540, "s": 455, "text": "Return Value: It returns true, if obj is found in the Stack otherwise returns false." }, { "code": null, "e": 601, "s": 540, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 612, "s": 601, "text": "Example 1:" }, { "code": "// C# code to illustrate the// Stack.Contains() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"Geeks\"); myStack.Push(\"Geeks Classes\"); myStack.Push(\"Noida\"); myStack.Push(\"Data Structures\"); myStack.Push(\"GeeksforGeeks\"); // Checking whether the element is // present in the Stack or not // The function returns True if the // element is present in the Stack, // else returns False Console.WriteLine(myStack.Contains(\"GeeksforGeeks\")); }}", "e": 1328, "s": 612, "text": null }, { "code": null, "e": 1334, "s": 1328, "text": "True\n" }, { "code": null, "e": 1345, "s": 1334, "text": "Example 2:" }, { "code": "// C# code to illustrate the// Stack.Contains() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements // into the Stack myStack.Push(5); myStack.Push(10); myStack.Push(15); myStack.Push(20); myStack.Push(25); // Checking whether the element is // present in the Stack or not // The function returns True if the // element is present in the Stack, else // returns False Console.WriteLine(myStack.Contains(7)); }}", "e": 2005, "s": 1345, "text": null }, { "code": null, "e": 2012, "s": 2005, "text": "False\n" }, { "code": null, "e": 2023, "s": 2012, "text": "Reference:" }, { "code": null, "e": 2125, "s": 2023, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.contains?view=netframework-4.7.2" }, { "code": null, "e": 2154, "s": 2125, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 2179, "s": 2154, "text": "CSharp-Collections-Stack" }, { "code": null, "e": 2193, "s": 2179, "text": "CSharp-method" }, { "code": null, "e": 2196, "s": 2193, "text": "C#" } ]
HTML <ul> Tag
09 Dec, 2021 In this article, we will know the HTML <ul> Tag & its implementation. The <ul> tag in HTML is used to define the unordered list item in an HTML document. It contains the list items <li> element. The <ul> tag requires an opening and closing tag. By using CSS style you can easily design an unordered list. Syntax: <ul> list of items </ul> Accepted attribute: This tag contains two attributes which are listed below: HTML <ul> compact Attribute: It will render the list smaller. HTML <ul> type Attribute: It specifies which kind of marker is used in the list. Note: The <ul> attributes are not supported by HTML 5. Example: In this example, we have created an unordered list of computer parts using the <ul> tag. HTML <!DOCTYPE html><html> <body> <h2>Welcome To GeekforGeeks</h2> <ul> <li>Mouse</li> <li>Keyboard</li> <li>Speaker</li> <li>Monitor</li> </ul></body> </html> Output: HTML Unordered List Example 1: This example describes the Unordered List in HTML. HTML <!DOCTYPE html><html> <head> <title>HTML ul tag</title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML ul tag</h2> <p>GeeksforGeeks courses List:</p> <ul> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html> Output: HTML Unordered List Example 2: Nested unordered list, a list inside other lists is known as a nested list. HTML <!DOCTYPE html><html> <head> <title>Nested unordered list</title></head> <body> <h2>Welcome To GeeksforGeeks</h2> <ul> <li>Hardware</li> <li> Software <ul> <li>System Software</li> <li>Application Software</li> </ul> </li> <li>MacBook</li> </ul></body> </html> Output: Nested Unordered List Example 3: Complex nested unordered list. HTML <!DOCTYPE html><html> <head> <title>Nested unordered list</title></head> <body> <h2>Welcome To GeeksforGeeks</h2> <ul> <li>Hardware</li> <li> Software <ul> <li>System Software</li> <li>Application Software</li> <ul> <li>Skype</li> <li>Slack</li> </ul> <li>Microsoft suite of products</li> <ul> <li>Office</li> <li>Excel</li> <li>Word</li> <li>Powerpoint</li> </ul> </ul> </li> <li>MacBook</li> </ul></body> </html> Output: Complex Nested Unordered List Supported Browsers: Google Chrome Internet Explorer Microsoft Edge Firefox Safari Opera arorakashish0911 shubhamyadav4 bhaskargeeksforgeeks HTML-Tags 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": "\n09 Dec, 2021" }, { "code": null, "e": 333, "s": 28, "text": "In this article, we will know the HTML <ul> Tag & its implementation. The <ul> tag in HTML is used to define the unordered list item in an HTML document. It contains the list items <li> element. The <ul> tag requires an opening and closing tag. By using CSS style you can easily design an unordered list." }, { "code": null, "e": 342, "s": 333, "text": "Syntax: " }, { "code": null, "e": 367, "s": 342, "text": "<ul> list of items </ul>" }, { "code": null, "e": 445, "s": 367, "text": "Accepted attribute: This tag contains two attributes which are listed below: " }, { "code": null, "e": 507, "s": 445, "text": "HTML <ul> compact Attribute: It will render the list smaller." }, { "code": null, "e": 588, "s": 507, "text": "HTML <ul> type Attribute: It specifies which kind of marker is used in the list." }, { "code": null, "e": 643, "s": 588, "text": "Note: The <ul> attributes are not supported by HTML 5." }, { "code": null, "e": 741, "s": 643, "text": "Example: In this example, we have created an unordered list of computer parts using the <ul> tag." }, { "code": null, "e": 746, "s": 741, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h2>Welcome To GeekforGeeks</h2> <ul> <li>Mouse</li> <li>Keyboard</li> <li>Speaker</li> <li>Monitor</li> </ul></body> </html>", "e": 918, "s": 746, "text": null }, { "code": null, "e": 926, "s": 918, "text": "Output:" }, { "code": null, "e": 946, "s": 926, "text": "HTML Unordered List" }, { "code": null, "e": 1008, "s": 946, "text": "Example 1: This example describes the Unordered List in HTML." }, { "code": null, "e": 1013, "s": 1008, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML ul tag</title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML ul tag</h2> <p>GeeksforGeeks courses List:</p> <ul> <li>Geeks</li> <li>Sudo</li> <li>Gfg</li> <li>Gate</li> <li>Placement</li> </ul></body> </html>", "e": 1287, "s": 1013, "text": null }, { "code": null, "e": 1295, "s": 1287, "text": "Output:" }, { "code": null, "e": 1315, "s": 1295, "text": "HTML Unordered List" }, { "code": null, "e": 1402, "s": 1315, "text": "Example 2: Nested unordered list, a list inside other lists is known as a nested list." }, { "code": null, "e": 1407, "s": 1402, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Nested unordered list</title></head> <body> <h2>Welcome To GeeksforGeeks</h2> <ul> <li>Hardware</li> <li> Software <ul> <li>System Software</li> <li>Application Software</li> </ul> </li> <li>MacBook</li> </ul></body> </html>", "e": 1716, "s": 1407, "text": null }, { "code": null, "e": 1724, "s": 1716, "text": "Output:" }, { "code": null, "e": 1746, "s": 1724, "text": "Nested Unordered List" }, { "code": null, "e": 1788, "s": 1746, "text": "Example 3: Complex nested unordered list." }, { "code": null, "e": 1793, "s": 1788, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Nested unordered list</title></head> <body> <h2>Welcome To GeeksforGeeks</h2> <ul> <li>Hardware</li> <li> Software <ul> <li>System Software</li> <li>Application Software</li> <ul> <li>Skype</li> <li>Slack</li> </ul> <li>Microsoft suite of products</li> <ul> <li>Office</li> <li>Excel</li> <li>Word</li> <li>Powerpoint</li> </ul> </ul> </li> <li>MacBook</li> </ul></body> </html>", "e": 2345, "s": 1793, "text": null }, { "code": null, "e": 2353, "s": 2345, "text": "Output:" }, { "code": null, "e": 2383, "s": 2353, "text": "Complex Nested Unordered List" }, { "code": null, "e": 2404, "s": 2383, "text": "Supported Browsers: " }, { "code": null, "e": 2418, "s": 2404, "text": "Google Chrome" }, { "code": null, "e": 2436, "s": 2418, "text": "Internet Explorer" }, { "code": null, "e": 2451, "s": 2436, "text": "Microsoft Edge" }, { "code": null, "e": 2459, "s": 2451, "text": "Firefox" }, { "code": null, "e": 2466, "s": 2459, "text": "Safari" }, { "code": null, "e": 2472, "s": 2466, "text": "Opera" }, { "code": null, "e": 2489, "s": 2472, "text": "arorakashish0911" }, { "code": null, "e": 2503, "s": 2489, "text": "shubhamyadav4" }, { "code": null, "e": 2524, "s": 2503, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 2534, "s": 2524, "text": "HTML-Tags" }, { "code": null, "e": 2539, "s": 2534, "text": "HTML" }, { "code": null, "e": 2556, "s": 2539, "text": "Web Technologies" }, { "code": null, "e": 2561, "s": 2556, "text": "HTML" } ]
Swapping two array elements in a single line using JavaScript
15 Mar, 2021 In JavaScript, there exist many ways using by which one can swap two array elements. In this article, we will discuss a way in which one can swap two array elements in JavaScript in a single line. The input and output would be as follows. Input: arr = { 10, 20, 40, 30 } Output: arr = { 10, 20, 30, 40 } // Swapped 30 and 40 This swapping can be done by writing the 2 array elements we want to reverse in order and in square brackets on the left-hand side. On the right-hand side we will write the same array elements but this time in reverse order. Syntax: [a[m], a[n]] = [a[n], a[m]] // where m and n are the index numbers to swap Example 1: Javascript <script> let arr = [1, 2, 3, 5, 4]; // Swapping element at index 3 with index 4 [arr[3], arr[4]] = [arr[4], arr[3]] // Print the array console.log(arr)</script> Output: [1, 2, 3, 4, 5] Example 2: Javascript <script> let arr = ["e", "b", "c", "d", "a"]; // Swapping element at index 0 with index 4 [arr[0], arr[4]] = [arr[4], arr[0]]; // Print the array console.log(arr);</script> Output: ['a','b','c','d','e'] javascript-array JavaScript-Questions 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": "\n15 Mar, 2021" }, { "code": null, "e": 267, "s": 28, "text": "In JavaScript, there exist many ways using by which one can swap two array elements. In this article, we will discuss a way in which one can swap two array elements in JavaScript in a single line. The input and output would be as follows." }, { "code": null, "e": 354, "s": 267, "text": "Input: arr = { 10, 20, 40, 30 }\nOutput: arr = { 10, 20, 30, 40 } \n// Swapped 30 and 40" }, { "code": null, "e": 579, "s": 354, "text": "This swapping can be done by writing the 2 array elements we want to reverse in order and in square brackets on the left-hand side. On the right-hand side we will write the same array elements but this time in reverse order." }, { "code": null, "e": 587, "s": 579, "text": "Syntax:" }, { "code": null, "e": 665, "s": 587, "text": "[a[m], a[n]] = [a[n], a[m]] \n \n// where m and n are the index numbers to swap" }, { "code": null, "e": 676, "s": 665, "text": "Example 1:" }, { "code": null, "e": 687, "s": 676, "text": "Javascript" }, { "code": "<script> let arr = [1, 2, 3, 5, 4]; // Swapping element at index 3 with index 4 [arr[3], arr[4]] = [arr[4], arr[3]] // Print the array console.log(arr)</script>", "e": 857, "s": 687, "text": null }, { "code": null, "e": 865, "s": 857, "text": "Output:" }, { "code": null, "e": 881, "s": 865, "text": "[1, 2, 3, 4, 5]" }, { "code": null, "e": 892, "s": 881, "text": "Example 2:" }, { "code": null, "e": 903, "s": 892, "text": "Javascript" }, { "code": "<script> let arr = [\"e\", \"b\", \"c\", \"d\", \"a\"]; // Swapping element at index 0 with index 4 [arr[0], arr[4]] = [arr[4], arr[0]]; // Print the array console.log(arr);</script>", "e": 1085, "s": 903, "text": null }, { "code": null, "e": 1093, "s": 1085, "text": "Output:" }, { "code": null, "e": 1115, "s": 1093, "text": "['a','b','c','d','e']" }, { "code": null, "e": 1132, "s": 1115, "text": "javascript-array" }, { "code": null, "e": 1153, "s": 1132, "text": "JavaScript-Questions" }, { "code": null, "e": 1164, "s": 1153, "text": "JavaScript" }, { "code": null, "e": 1181, "s": 1164, "text": "Web Technologies" } ]
Positive elements at even and negative at odd positions (Relative order not maintained)
09 Jun, 2022 You have been given an array and you have to make a program to convert that array such that positive elements occur at even numbered places in the array and negative elements occur at odd numbered places in the array. We have to do it in place.There can be unequal number of positive and negative values and the extra values have to left as it is. Examples: Input : arr[] = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10} Output : arr[] = {1, -3, 5, -3, 6, 6, 7, -4, 9, 10} Input : arr[] = {-1, 3, -5, 6, 3, 6, -7, -4, -9, 10} Output : arr[] = {3, -1, 6, -5, 3, -7, 6, -4, 10, -9} The idea is to use Hoare’s partition process of Quick Sort. We take two pointers positive and negative. We set the positive pointer at start of the array and the negative pointer at 1st position of the array. We move positive pointer two steps forward till it finds a negative element. Similarly, we move negative pointer forward by two places till it finds a positive value at its position. If the positive and negative pointers are in the array then we will swap the values at these indexes otherwise we will stop executing the process. C++ Java Python3 C# PHP Javascript // C++ program to rearrange positive and negative// numbers#include <bits/stdc++.h>using namespace std; void rearrange(int a[], int size){ int positive = 0, negative = 1; while (true) { /* Move forward the positive pointer till negative number number not encountered */ while (positive < size && a[positive] >= 0) positive += 2; /* Move forward the negative pointer till positive number number not encountered */ while (negative < size && a[negative] <= 0) negative += 2; // Swap array elements to fix their position. if (positive < size && negative < size) swap(a[positive], a[negative]); /* Break from the while loop when any index exceeds the size of the array */ else break; }} // Driver codeint main(){ int arr[] = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; int n = (sizeof(arr) / sizeof(arr[0])); rearrange(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program to rearrange positive// and negative numbersimport java.io.*; class GFG { static void rearrange(int a[], int size){ int positive = 0, negative = 1, temp; while (true) { /* Move forward the positive pointer till negative number number not encountered */ while (positive < size && a[positive] >= 0) positive += 2; /* Move forward the negative pointer till positive number number not encountered */ while (negative < size && a[negative] <= 0) negative += 2; // Swap array elements to fix their position. if (positive < size && negative < size) { temp = a[positive]; a[positive] = a[negative]; a[negative] = temp; } /* Break from the while loop when any index exceeds the size of the array */ else break; }} // Driver codepublic static void main(String args[]) { int arr[] = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10}; int n = arr.length; rearrange(arr, n); for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");}} /*This code is contributed by Nikita Tiwari.*/ # Python 3 program to rearrange# positive and negative numbers def rearrange(a, size) : positive = 0 negative = 1 while (True) : # Move forward the positive # pointer till negative number # number not encountered while (positive < size and a[positive] >= 0) : positive = positive + 2 # Move forward the negative # pointer till positive number # number not encountered while (negative < size and a[negative] <= 0) : negative = negative + 2 # Swap array elements to fix # their position. if (positive < size and negative < size) : temp = a[positive] a[positive] = a[negative] a[negative] = temp # Break from the while loop when # any index exceeds the size of # the array else : break # Driver codearr =[ 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 ]n = len(arr) rearrange(arr, n)for i in range(0, n) : print(arr[i], end = " ") # This code is contributed by Nikita Tiwari. // C# program to rearrange positive// and negative numbersusing System; class GFG { // Function to rearrangestatic void rearrange(int []a, int size){int positive = 0, negative = 1, temp; while (true) { // Move forward the positive pointer till // negative number number not encountered while (positive < size && a[positive] >= 0) positive += 2; // Move forward the negative pointer till // positive number number not encountered while (negative < size && a[negative] <= 0) negative += 2; // Swap array elements to fix their position. if (positive < size && negative < size) { temp = a[positive]; a[positive] = a[negative]; a[negative] = temp; } // Break from the while loop when any // index exceeds the size of the array else break; }} // Driver Codepublic static void Main(String []args) { int []arr = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10}; int n = arr.Length; rearrange(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + " ");}} // This code is contributed by Nitin Mittal. <?php// PHP program to rearrange positive// and negative numbers function rearrange(&$a, $size){ $positive = 0; $negative = 1; while (true) { /* Move forward the positive pointer till negative number number not encountered */ while ($positive < $size && $a[$positive] >= 0) $positive += 2; /* Move forward the negative pointer till positive number number not encountered */ while ($negative < $size && $a[$negative] <= 0) $negative += 2; // Swap array elements to fix // their position. if ($positive < $size && $negative < $size) { $temp = $a[$positive]; $a[$positive] = $a[$negative]; $a[$negative] = $temp; } /* Break from the while loop when any index exceeds the size of the array */ else break; }} // Driver code$arr = array( 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 );$n = sizeof($arr); rearrange($arr, $n);for ($i = 0; $i < $n; $i++) echo $arr[$i] ." "; // This code is contributed by ChitraNayal?> <script> // Javascript program to rearrange positive// and negative numbersfunction rearrange(a, size){ let positive = 0; let negative = 1; let temp; while (true) { // Move forward the positive // pointer till negative number // number not encountered while (positive < size && a[positive] >= 0) positive += 2; // Move forward the negative pointer // till positive number number not encountered while (negative < size && a[negative] <= 0) negative += 2; // Swap array elements to fix their position. if (positive < size && negative < size) { temp = a[positive]; a[positive] = a[negative]; a[negative] = temp; } // Break from the while loop when any index // exceeds the size of the array else break; }} // Driver codelet arr = [ 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 ];let n = arr.length; rearrange(arr, n); for(let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by sravan kumar G </script> Output: 1 -3 5 -3 6 6 7 -4 9 10 Time Complexity: O(n2), Auxiliary Space: O(1) Lets explain the working of the code on the first example arr[] = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10} We declare two variables positive and negative positive points to zeroth position and negative points to first position positive = 0 negative = 1 In the first iteration positive will move 4 places to fifth position as a[4] is less than zero and positive = 4. Negative will move 2 places and will point to fourth position as a[3]>0 we will swap positive and negative position values as they are less than size of array. After first iteration the array becomes arr[] = {1, -3, 5, -3, 6, 6, 7, -4, 9, 10}Now positive points at fourth position and negative points at third position In second iteration the positive value will move 6 places and its value will more than the size of the array. The negative pointer will move two steps forward and it will point to 5th position As the positive pointer value becomes greater than the array size we will not perform any swap operation and break out of the while loop. The final output will be arr[] = {1, -3, 5, -3, 6, 6, 7, -4, 9, 10} An example where relative order is not maintained: { -1, -2, -3, -4, -5, 6, 7, 8 }; Another Approach :- The idea is to find a positive/negative element which is in incorrect place(i.e. positive at odd and negative at even place) and the then find the element of opposite sign which is also in incorrect position in the remaining array and then swap these two elements. Here is the implementation of the above idea. C++ Java Python3 C# Javascript // C++ program to rearrange positive// and negative numbers#include<iostream>using namespace std; // Swap functionvoid swap(int* a, int i , int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp; return ;} // Print array functionvoid printArray(int* a, int n){ for(int i = 0; i < n; i++) cout << a[i] << " "; cout << endl; return ;} // Driver codeint main(){ int arr[] = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; int n = sizeof(arr)/sizeof(arr[0]); //before modification printArray(arr, n); for(int i = 0; i < n; i++) { if(arr[i] >= 0 && i % 2 == 1) { // out of order positive element for(int j = i + 1; j < n; j++) { if(arr[j] < 0 && j % 2 == 0) { // find out of order negative // element in remaining array swap(arr, i, j); break ; } } } else if(arr[i] < 0 && i % 2 == 0) { // out of order negative element for(int j = i + 1; j < n; j++) { if(arr[j] >= 0 && j % 2 == 1) { // find out of order positive // element in remaining array swap(arr, i, j); break; } } } } //after modification printArray(arr, n); return 0;} // This code is contributed by AnitAggarwal // Java program to rearrange positive// and negative numbersimport java.io.*;import java.util.*; class GFG{ // Swap function static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } // Print array function static void printArray(int[] a, int n) { for (int i = 0; i < n; i++) System.out.print(a[i] + " "); System.out.println(); } // Driver code public static void main(String args[]) { int[] arr = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; int n = arr.length; //before modification printArray(arr, n); for (int i = 0; i < n; i++) { if (arr[i] >= 0 && i % 2 == 1) { // out of order positive element for (int j = i + 1; j < n; j++) { if (arr[j] < 0 && j % 2 == 0) { // find out of order negative // element in remaining array swap(arr, i, j); break ; } } } else if (arr[i] < 0 && i % 2 == 0) { // out of order negative element for (int j = i + 1; j < n; j++) { if (arr[j] >= 0 && j % 2 == 1) { // find out of order positive // element in remaining array swap(arr, i, j); break; } } } } //after modification printArray(arr, n); }} // This code is contributed by rachana soma # Python3 program to rearrange positive# and negative numbers # Print array functiondef printArray(a, n): for i in a: print(i, end = " ") print() # Driver codearr = [1, -3, 5, 6, -3, 6, 7, -4, 9, 10]n = len(arr) # before modificationprintArray(arr, n) for i in range(n): if(arr[i] >= 0 and i % 2 == 1): # out of order positive element for j in range(i + 1, n): if(arr[j] < 0 and j % 2 == 0): # find out of order negative # element in remaining array arr[i], arr[j] = arr[j], arr[i] break elif (arr[i] < 0 and i % 2 == 0): # out of order negative element for j in range(i + 1, n): if(arr[j] >= 0 and j % 2 == 1): # find out of order positive # element in remaining array arr[i], arr[j] = arr[j], arr[i] break # after modificationprintArray(arr, n); # This code is contributed# by mohit kumar // C# program to rearrange positive// and negative numbersusing System; class GFG{ // Swap function static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } // Print array function static void printArray(int[] a, int n) { for (int i = 0; i < n; i++) Console.Write(a[i] + " "); Console.WriteLine(); } // Driver code public static void Main() { int[] arr = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; int n = arr.Length; //before modification printArray(arr, n); for (int i = 0; i < n; i++) { if (arr[i] >= 0 && i % 2 == 1) { // out of order positive element for (int j = i + 1; j < n; j++) { if (arr[j] < 0 && j % 2 == 0) { // find out of order negative // element in remaining array swap(arr, i, j); break ; } } } else if (arr[i] < 0 && i % 2 == 0) { // out of order negative element for (int j = i + 1; j < n; j++) { if (arr[j] >= 0 && j % 2 == 1) { // find out of order positive // element in remaining array swap(arr, i, j); break; } } } } // after modification printArray(arr, n); }} // This code is contributed by Akanksha Rai <script> // Javascript program to rearrange positive// and negative numbers // Swap function function swap(a,i,j) { let temp = a[i]; a[i] = a[j]; a[j] = temp; } // Print array function function printArray(a,n) { for (let i = 0; i < n; i++) document.write(a[i] + " "); document.write("<br>"); } // Driver code let arr=[1, -3, 5, 6, -3, 6, 7, -4, 9, 10]; let n = arr.length; //before modification printArray(arr, n); for (let i = 0; i < n; i++) { if (arr[i] >= 0 && i % 2 == 1) { // out of order positive element for (let j = i + 1; j < n; j++) { if (arr[j] < 0 && j % 2 == 0) { // find out of order negative // element in remaining array swap(arr, i, j); break ; } } } else if (arr[i] < 0 && i % 2 == 0) { // out of order negative element for (let j = i + 1; j < n; j++) { if (arr[j] >= 0 && j % 2 == 1) { // find out of order positive // element in remaining array swap(arr, i, j); break; } } } } //after modification printArray(arr, n); // This code is contributed by avanitrachhadiya2155 </script> Output: 1 -3 5 6 -3 6 7 -4 9 10 1 -3 5 -3 6 6 7 -4 9 10 Time Complexity: O(n2), Auxiliary Space: O(1)This article is contributed by Ashish Madaan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal ukasp theInjuredLion mohit kumar 29 rachana soma Akanksha_Rai sravankumar8128 avanitrachhadiya2155 codewithmini array-rearrange Quick Sort Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2022" }, { "code": null, "e": 402, "s": 54, "text": "You have been given an array and you have to make a program to convert that array such that positive elements occur at even numbered places in the array and negative elements occur at odd numbered places in the array. We have to do it in place.There can be unequal number of positive and negative values and the extra values have to left as it is." }, { "code": null, "e": 414, "s": 402, "text": "Examples: " }, { "code": null, "e": 625, "s": 414, "text": "Input : arr[] = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10}\nOutput : arr[] = {1, -3, 5, -3, 6, 6, 7, -4, 9, 10}\n\nInput : arr[] = {-1, 3, -5, 6, 3, 6, -7, -4, -9, 10}\nOutput : arr[] = {3, -1, 6, -5, 3, -7, 6, -4, 10, -9}" }, { "code": null, "e": 835, "s": 625, "text": "The idea is to use Hoare’s partition process of Quick Sort. We take two pointers positive and negative. We set the positive pointer at start of the array and the negative pointer at 1st position of the array. " }, { "code": null, "e": 1019, "s": 835, "text": "We move positive pointer two steps forward till it finds a negative element. Similarly, we move negative pointer forward by two places till it finds a positive value at its position. " }, { "code": null, "e": 1166, "s": 1019, "text": "If the positive and negative pointers are in the array then we will swap the values at these indexes otherwise we will stop executing the process." }, { "code": null, "e": 1170, "s": 1166, "text": "C++" }, { "code": null, "e": 1175, "s": 1170, "text": "Java" }, { "code": null, "e": 1183, "s": 1175, "text": "Python3" }, { "code": null, "e": 1186, "s": 1183, "text": "C#" }, { "code": null, "e": 1190, "s": 1186, "text": "PHP" }, { "code": null, "e": 1201, "s": 1190, "text": "Javascript" }, { "code": "// C++ program to rearrange positive and negative// numbers#include <bits/stdc++.h>using namespace std; void rearrange(int a[], int size){ int positive = 0, negative = 1; while (true) { /* Move forward the positive pointer till negative number number not encountered */ while (positive < size && a[positive] >= 0) positive += 2; /* Move forward the negative pointer till positive number number not encountered */ while (negative < size && a[negative] <= 0) negative += 2; // Swap array elements to fix their position. if (positive < size && negative < size) swap(a[positive], a[negative]); /* Break from the while loop when any index exceeds the size of the array */ else break; }} // Driver codeint main(){ int arr[] = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; int n = (sizeof(arr) / sizeof(arr[0])); rearrange(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 2247, "s": 1201, "text": null }, { "code": "// Java program to rearrange positive// and negative numbersimport java.io.*; class GFG { static void rearrange(int a[], int size){ int positive = 0, negative = 1, temp; while (true) { /* Move forward the positive pointer till negative number number not encountered */ while (positive < size && a[positive] >= 0) positive += 2; /* Move forward the negative pointer till positive number number not encountered */ while (negative < size && a[negative] <= 0) negative += 2; // Swap array elements to fix their position. if (positive < size && negative < size) { temp = a[positive]; a[positive] = a[negative]; a[negative] = temp; } /* Break from the while loop when any index exceeds the size of the array */ else break; }} // Driver codepublic static void main(String args[]) { int arr[] = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10}; int n = arr.length; rearrange(arr, n); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \");}} /*This code is contributed by Nikita Tiwari.*/", "e": 3328, "s": 2247, "text": null }, { "code": "# Python 3 program to rearrange# positive and negative numbers def rearrange(a, size) : positive = 0 negative = 1 while (True) : # Move forward the positive # pointer till negative number # number not encountered while (positive < size and a[positive] >= 0) : positive = positive + 2 # Move forward the negative # pointer till positive number # number not encountered while (negative < size and a[negative] <= 0) : negative = negative + 2 # Swap array elements to fix # their position. if (positive < size and negative < size) : temp = a[positive] a[positive] = a[negative] a[negative] = temp # Break from the while loop when # any index exceeds the size of # the array else : break # Driver codearr =[ 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 ]n = len(arr) rearrange(arr, n)for i in range(0, n) : print(arr[i], end = \" \") # This code is contributed by Nikita Tiwari.", "e": 4397, "s": 3328, "text": null }, { "code": "// C# program to rearrange positive// and negative numbersusing System; class GFG { // Function to rearrangestatic void rearrange(int []a, int size){int positive = 0, negative = 1, temp; while (true) { // Move forward the positive pointer till // negative number number not encountered while (positive < size && a[positive] >= 0) positive += 2; // Move forward the negative pointer till // positive number number not encountered while (negative < size && a[negative] <= 0) negative += 2; // Swap array elements to fix their position. if (positive < size && negative < size) { temp = a[positive]; a[positive] = a[negative]; a[negative] = temp; } // Break from the while loop when any // index exceeds the size of the array else break; }} // Driver Codepublic static void Main(String []args) { int []arr = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10}; int n = arr.Length; rearrange(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \");}} // This code is contributed by Nitin Mittal.", "e": 5485, "s": 4397, "text": null }, { "code": "<?php// PHP program to rearrange positive// and negative numbers function rearrange(&$a, $size){ $positive = 0; $negative = 1; while (true) { /* Move forward the positive pointer till negative number number not encountered */ while ($positive < $size && $a[$positive] >= 0) $positive += 2; /* Move forward the negative pointer till positive number number not encountered */ while ($negative < $size && $a[$negative] <= 0) $negative += 2; // Swap array elements to fix // their position. if ($positive < $size && $negative < $size) { $temp = $a[$positive]; $a[$positive] = $a[$negative]; $a[$negative] = $temp; } /* Break from the while loop when any index exceeds the size of the array */ else break; }} // Driver code$arr = array( 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 );$n = sizeof($arr); rearrange($arr, $n);for ($i = 0; $i < $n; $i++) echo $arr[$i] .\" \"; // This code is contributed by ChitraNayal?>", "e": 6657, "s": 5485, "text": null }, { "code": "<script> // Javascript program to rearrange positive// and negative numbersfunction rearrange(a, size){ let positive = 0; let negative = 1; let temp; while (true) { // Move forward the positive // pointer till negative number // number not encountered while (positive < size && a[positive] >= 0) positive += 2; // Move forward the negative pointer // till positive number number not encountered while (negative < size && a[negative] <= 0) negative += 2; // Swap array elements to fix their position. if (positive < size && negative < size) { temp = a[positive]; a[positive] = a[negative]; a[negative] = temp; } // Break from the while loop when any index // exceeds the size of the array else break; }} // Driver codelet arr = [ 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 ];let n = arr.length; rearrange(arr, n); for(let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by sravan kumar G </script>", "e": 7788, "s": 6657, "text": null }, { "code": null, "e": 7797, "s": 7788, "text": "Output: " }, { "code": null, "e": 7822, "s": 7797, "text": "1 -3 5 -3 6 6 7 -4 9 10 " }, { "code": null, "e": 7847, "s": 7822, "text": "Time Complexity: O(n2), " }, { "code": null, "e": 7869, "s": 7847, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 8659, "s": 7869, "text": "Lets explain the working of the code on the first example arr[] = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10} We declare two variables positive and negative positive points to zeroth position and negative points to first position positive = 0 negative = 1 In the first iteration positive will move 4 places to fifth position as a[4] is less than zero and positive = 4. Negative will move 2 places and will point to fourth position as a[3]>0 we will swap positive and negative position values as they are less than size of array. After first iteration the array becomes arr[] = {1, -3, 5, -3, 6, 6, 7, -4, 9, 10}Now positive points at fourth position and negative points at third position In second iteration the positive value will move 6 places and its value will more than the size of the array. " }, { "code": null, "e": 8948, "s": 8659, "text": "The negative pointer will move two steps forward and it will point to 5th position As the positive pointer value becomes greater than the array size we will not perform any swap operation and break out of the while loop. The final output will be arr[] = {1, -3, 5, -3, 6, 6, 7, -4, 9, 10}" }, { "code": null, "e": 9033, "s": 8948, "text": "An example where relative order is not maintained: { -1, -2, -3, -4, -5, 6, 7, 8 }; " }, { "code": null, "e": 9319, "s": 9033, "text": "Another Approach :- The idea is to find a positive/negative element which is in incorrect place(i.e. positive at odd and negative at even place) and the then find the element of opposite sign which is also in incorrect position in the remaining array and then swap these two elements. " }, { "code": null, "e": 9367, "s": 9319, "text": "Here is the implementation of the above idea. " }, { "code": null, "e": 9371, "s": 9367, "text": "C++" }, { "code": null, "e": 9376, "s": 9371, "text": "Java" }, { "code": null, "e": 9384, "s": 9376, "text": "Python3" }, { "code": null, "e": 9387, "s": 9384, "text": "C#" }, { "code": null, "e": 9398, "s": 9387, "text": "Javascript" }, { "code": "// C++ program to rearrange positive// and negative numbers#include<iostream>using namespace std; // Swap functionvoid swap(int* a, int i , int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp; return ;} // Print array functionvoid printArray(int* a, int n){ for(int i = 0; i < n; i++) cout << a[i] << \" \"; cout << endl; return ;} // Driver codeint main(){ int arr[] = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; int n = sizeof(arr)/sizeof(arr[0]); //before modification printArray(arr, n); for(int i = 0; i < n; i++) { if(arr[i] >= 0 && i % 2 == 1) { // out of order positive element for(int j = i + 1; j < n; j++) { if(arr[j] < 0 && j % 2 == 0) { // find out of order negative // element in remaining array swap(arr, i, j); break ; } } } else if(arr[i] < 0 && i % 2 == 0) { // out of order negative element for(int j = i + 1; j < n; j++) { if(arr[j] >= 0 && j % 2 == 1) { // find out of order positive // element in remaining array swap(arr, i, j); break; } } } } //after modification printArray(arr, n); return 0;} // This code is contributed by AnitAggarwal", "e": 10892, "s": 9398, "text": null }, { "code": "// Java program to rearrange positive// and negative numbersimport java.io.*;import java.util.*; class GFG{ // Swap function static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } // Print array function static void printArray(int[] a, int n) { for (int i = 0; i < n; i++) System.out.print(a[i] + \" \"); System.out.println(); } // Driver code public static void main(String args[]) { int[] arr = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; int n = arr.length; //before modification printArray(arr, n); for (int i = 0; i < n; i++) { if (arr[i] >= 0 && i % 2 == 1) { // out of order positive element for (int j = i + 1; j < n; j++) { if (arr[j] < 0 && j % 2 == 0) { // find out of order negative // element in remaining array swap(arr, i, j); break ; } } } else if (arr[i] < 0 && i % 2 == 0) { // out of order negative element for (int j = i + 1; j < n; j++) { if (arr[j] >= 0 && j % 2 == 1) { // find out of order positive // element in remaining array swap(arr, i, j); break; } } } } //after modification printArray(arr, n); }} // This code is contributed by rachana soma", "e": 12637, "s": 10892, "text": null }, { "code": "# Python3 program to rearrange positive# and negative numbers # Print array functiondef printArray(a, n): for i in a: print(i, end = \" \") print() # Driver codearr = [1, -3, 5, 6, -3, 6, 7, -4, 9, 10]n = len(arr) # before modificationprintArray(arr, n) for i in range(n): if(arr[i] >= 0 and i % 2 == 1): # out of order positive element for j in range(i + 1, n): if(arr[j] < 0 and j % 2 == 0): # find out of order negative # element in remaining array arr[i], arr[j] = arr[j], arr[i] break elif (arr[i] < 0 and i % 2 == 0): # out of order negative element for j in range(i + 1, n): if(arr[j] >= 0 and j % 2 == 1): # find out of order positive # element in remaining array arr[i], arr[j] = arr[j], arr[i] break # after modificationprintArray(arr, n); # This code is contributed# by mohit kumar", "e": 13678, "s": 12637, "text": null }, { "code": "// C# program to rearrange positive// and negative numbersusing System; class GFG{ // Swap function static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } // Print array function static void printArray(int[] a, int n) { for (int i = 0; i < n; i++) Console.Write(a[i] + \" \"); Console.WriteLine(); } // Driver code public static void Main() { int[] arr = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; int n = arr.Length; //before modification printArray(arr, n); for (int i = 0; i < n; i++) { if (arr[i] >= 0 && i % 2 == 1) { // out of order positive element for (int j = i + 1; j < n; j++) { if (arr[j] < 0 && j % 2 == 0) { // find out of order negative // element in remaining array swap(arr, i, j); break ; } } } else if (arr[i] < 0 && i % 2 == 0) { // out of order negative element for (int j = i + 1; j < n; j++) { if (arr[j] >= 0 && j % 2 == 1) { // find out of order positive // element in remaining array swap(arr, i, j); break; } } } } // after modification printArray(arr, n); }} // This code is contributed by Akanksha Rai", "e": 15382, "s": 13678, "text": null }, { "code": "<script> // Javascript program to rearrange positive// and negative numbers // Swap function function swap(a,i,j) { let temp = a[i]; a[i] = a[j]; a[j] = temp; } // Print array function function printArray(a,n) { for (let i = 0; i < n; i++) document.write(a[i] + \" \"); document.write(\"<br>\"); } // Driver code let arr=[1, -3, 5, 6, -3, 6, 7, -4, 9, 10]; let n = arr.length; //before modification printArray(arr, n); for (let i = 0; i < n; i++) { if (arr[i] >= 0 && i % 2 == 1) { // out of order positive element for (let j = i + 1; j < n; j++) { if (arr[j] < 0 && j % 2 == 0) { // find out of order negative // element in remaining array swap(arr, i, j); break ; } } } else if (arr[i] < 0 && i % 2 == 0) { // out of order negative element for (let j = i + 1; j < n; j++) { if (arr[j] >= 0 && j % 2 == 1) { // find out of order positive // element in remaining array swap(arr, i, j); break; } } } } //after modification printArray(arr, n); // This code is contributed by avanitrachhadiya2155 </script>", "e": 17057, "s": 15382, "text": null }, { "code": null, "e": 17066, "s": 17057, "text": "Output: " }, { "code": null, "e": 17116, "s": 17066, "text": "1 -3 5 6 -3 6 7 -4 9 10 \n1 -3 5 -3 6 6 7 -4 9 10 " }, { "code": null, "e": 17140, "s": 17116, "text": "Time Complexity: O(n2)," }, { "code": null, "e": 17583, "s": 17140, "text": "Auxiliary Space: O(1)This article is contributed by Ashish Madaan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 17596, "s": 17583, "text": "nitin mittal" }, { "code": null, "e": 17602, "s": 17596, "text": "ukasp" }, { "code": null, "e": 17617, "s": 17602, "text": "theInjuredLion" }, { "code": null, "e": 17632, "s": 17617, "text": "mohit kumar 29" }, { "code": null, "e": 17645, "s": 17632, "text": "rachana soma" }, { "code": null, "e": 17658, "s": 17645, "text": "Akanksha_Rai" }, { "code": null, "e": 17674, "s": 17658, "text": "sravankumar8128" }, { "code": null, "e": 17695, "s": 17674, "text": "avanitrachhadiya2155" }, { "code": null, "e": 17708, "s": 17695, "text": "codewithmini" }, { "code": null, "e": 17724, "s": 17708, "text": "array-rearrange" }, { "code": null, "e": 17735, "s": 17724, "text": "Quick Sort" }, { "code": null, "e": 17742, "s": 17735, "text": "Arrays" }, { "code": null, "e": 17749, "s": 17742, "text": "Arrays" } ]
Java String startsWith() and endsWith() Methods With Examples
30 Sep, 2021 The String class in Java is an immutable and non-primitive data type that is used to store the characters of the sequence. The string is non-primitive datatype because, during the initialization of the string variable, it refers to an object that contains methods that can perform several different kinds of operations, but according to the definition of the primitive datatype, they are not considered as the object and store the data in the stack memory. In this article, we will discuss the endWith() method and the startsWith() method of the String class in java. Let us discuss both the methods individually: enWith() Method in javastartWith() Method enWith() Method in java startWith() Method Method 1: endsWith() method This method of the String class checks whether the given string ends with the specified string suffix or not. Syntax: endsWith(String suffix) Parameter: This method takes one parameter that is of string type.. Return type: This method returns a boolean value true or false. the i.e string ends with a specified suffix or not. Example: Java // Java Program to illustrate endWith() Method // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Given String String first = "Geeks for Geeks"; // Suffix to be matched String suffix = "kse"; // Given String does not end with // the above suffix hence return false System.out.println(first.endsWith(suffix)); // Changing the suffix say // it be customly 's' suffix = "s"; // Given String ends with the given suffix hence // returns true System.out.println(first.endsWith(suffix)); }} false true Method 2: startsWith() method This method of the String class checks whether the given string starts with the specified string prefix or not. Syntax: startsWith(String prefix) Parameter: This method takes one parameter that is of string type.. Return type: This method returns a boolean value true or false. the i.e string ends with a specified prefix or not. Examples: Java // Java Program to illustrate startWith() Method // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Given String String first = "Geeks for Geeks"; // Prefix to be matched String prefix = "se"; // Given String does not start with the above prefix // hence return false System.out.println(first.startsWith(prefix)); // Changing the prefix prefix = "Gee"; // Given String starts with the given prefix hence // returns true System.out.println(first.startsWith(prefix)); }} false true varshagumber28 saurabh1990aror Java-Strings Picked Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Sep, 2021" }, { "code": null, "e": 596, "s": 28, "text": "The String class in Java is an immutable and non-primitive data type that is used to store the characters of the sequence. The string is non-primitive datatype because, during the initialization of the string variable, it refers to an object that contains methods that can perform several different kinds of operations, but according to the definition of the primitive datatype, they are not considered as the object and store the data in the stack memory. In this article, we will discuss the endWith() method and the startsWith() method of the String class in java." }, { "code": null, "e": 642, "s": 596, "text": "Let us discuss both the methods individually:" }, { "code": null, "e": 684, "s": 642, "text": "enWith() Method in javastartWith() Method" }, { "code": null, "e": 708, "s": 684, "text": "enWith() Method in java" }, { "code": null, "e": 727, "s": 708, "text": "startWith() Method" }, { "code": null, "e": 756, "s": 727, "text": "Method 1: endsWith() method " }, { "code": null, "e": 866, "s": 756, "text": "This method of the String class checks whether the given string ends with the specified string suffix or not." }, { "code": null, "e": 874, "s": 866, "text": "Syntax:" }, { "code": null, "e": 903, "s": 874, "text": "endsWith(String suffix) " }, { "code": null, "e": 971, "s": 903, "text": "Parameter: This method takes one parameter that is of string type.." }, { "code": null, "e": 1087, "s": 971, "text": "Return type: This method returns a boolean value true or false. the i.e string ends with a specified suffix or not." }, { "code": null, "e": 1096, "s": 1087, "text": "Example:" }, { "code": null, "e": 1101, "s": 1096, "text": "Java" }, { "code": "// Java Program to illustrate endWith() Method // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Given String String first = \"Geeks for Geeks\"; // Suffix to be matched String suffix = \"kse\"; // Given String does not end with // the above suffix hence return false System.out.println(first.endsWith(suffix)); // Changing the suffix say // it be customly 's' suffix = \"s\"; // Given String ends with the given suffix hence // returns true System.out.println(first.endsWith(suffix)); }}", "e": 1781, "s": 1101, "text": null }, { "code": null, "e": 1792, "s": 1781, "text": "false\ntrue" }, { "code": null, "e": 1822, "s": 1792, "text": "Method 2: startsWith() method" }, { "code": null, "e": 1934, "s": 1822, "text": "This method of the String class checks whether the given string starts with the specified string prefix or not." }, { "code": null, "e": 1943, "s": 1934, "text": "Syntax: " }, { "code": null, "e": 1974, "s": 1943, "text": "startsWith(String prefix) " }, { "code": null, "e": 2042, "s": 1974, "text": "Parameter: This method takes one parameter that is of string type.." }, { "code": null, "e": 2158, "s": 2042, "text": "Return type: This method returns a boolean value true or false. the i.e string ends with a specified prefix or not." }, { "code": null, "e": 2169, "s": 2158, "text": "Examples: " }, { "code": null, "e": 2174, "s": 2169, "text": "Java" }, { "code": "// Java Program to illustrate startWith() Method // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Given String String first = \"Geeks for Geeks\"; // Prefix to be matched String prefix = \"se\"; // Given String does not start with the above prefix // hence return false System.out.println(first.startsWith(prefix)); // Changing the prefix prefix = \"Gee\"; // Given String starts with the given prefix hence // returns true System.out.println(first.startsWith(prefix)); }}", "e": 2831, "s": 2174, "text": null }, { "code": null, "e": 2842, "s": 2831, "text": "false\ntrue" }, { "code": null, "e": 2859, "s": 2844, "text": "varshagumber28" }, { "code": null, "e": 2875, "s": 2859, "text": "saurabh1990aror" }, { "code": null, "e": 2888, "s": 2875, "text": "Java-Strings" }, { "code": null, "e": 2895, "s": 2888, "text": "Picked" }, { "code": null, "e": 2900, "s": 2895, "text": "Java" }, { "code": null, "e": 2913, "s": 2900, "text": "Java-Strings" }, { "code": null, "e": 2918, "s": 2913, "text": "Java" } ]
How to set the Text Mask Format of the MaskedTextBox in C#?
26 Jul, 2019 In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask which differentiates between proper and improper user input. In MaskedTextBox control, you set a value which indicates that the literals and the prompt characters are included in the formatted string present in the MaskedTextBox using TextMaskFormat Property provided by the MaskedTextBox control. This property has four values and these values are defined under MaskFormat enum and the values are: The ExcludePromptAndLiterals value returns the text input, which is provided by the user. The IncludeLiterals value returns the text input, which is provided by the user and the literal characters that are defined in the mask. The IncludePrompt value returns the text input, which is provided by the user and the instances of the prompt character. The IncludePromptAndLiterals value provides the text input, which is given by the user, the literal characters that are defined in the mask and the instances of the prompt character. The default value of this property is IncludeLiterals. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the value of TextMaskFormat property of MaskedTextBox control as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the MaskedTextBox control from the toolbox on the form. As shown in the below image: Step 3: After drag and drop you will go to the properties of the MaskedTextBox and set the value of TextMaskFormat property of MaskedTextBox control as shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the value of TextMaskFormat property of the MaskedTextBox control programmatically with the help of given syntax: public System.Windows.Forms.MaskFormat TextMaskFormat { get; set; } Here, MaskFormat holds the values of the TextMaskFormat property. If the value of this property does not belong to the MaskFormat enum, then it will throw an InvalidEnumArgumentException. The following steps show how to set the value of the TextMaskFormat property of the MaskedTextBox control dynamically: Step 1: Create a MaskedTextBox using the MaskedTextBox() constructor is provided by the MaskedTextBox class.// Creating a MaskedTextBox MaskedTextBox m = new MaskedTextBox(); // Creating a MaskedTextBox MaskedTextBox m = new MaskedTextBox(); Step 2: After creating MaskedTextBox, set the TextMaskFormat property of the MaskedTextBox provided by the MaskedTextBox class.// Setting the TextMaskFormat property m.TextMaskFormat = MaskFormat.IncludeLiterals; // Setting the TextMaskFormat property m.TextMaskFormat = MaskFormat.IncludeLiterals; Step 3: And last add this MaskedTextBox control to the form using the following statement:// Adding MaskedTextBox control on the form this.Controls.Add(m); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = " Example"; l1.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = "Phone number:"; l2.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = "000000000"; m.Size = new Size(176, 20); m.Name = "MyBox"; m.BorderStyle = BorderStyle.Fixed3D; m.TextMaskFormat = MaskFormat.IncludeLiterals; m.Font = new Font("Bell MT", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}}Output: // Adding MaskedTextBox control on the form this.Controls.Add(m); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = " Example"; l1.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = "Phone number:"; l2.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = "000000000"; m.Size = new Size(176, 20); m.Name = "MyBox"; m.BorderStyle = BorderStyle.Fixed3D; m.TextMaskFormat = MaskFormat.IncludeLiterals; m.Font = new Font("Bell MT", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 595, "s": 28, "text": "In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask which differentiates between proper and improper user input. In MaskedTextBox control, you set a value which indicates that the literals and the prompt characters are included in the formatted string present in the MaskedTextBox using TextMaskFormat Property provided by the MaskedTextBox control. This property has four values and these values are defined under MaskFormat enum and the values are:" }, { "code": null, "e": 685, "s": 595, "text": "The ExcludePromptAndLiterals value returns the text input, which is provided by the user." }, { "code": null, "e": 822, "s": 685, "text": "The IncludeLiterals value returns the text input, which is provided by the user and the literal characters that are defined in the mask." }, { "code": null, "e": 943, "s": 822, "text": "The IncludePrompt value returns the text input, which is provided by the user and the instances of the prompt character." }, { "code": null, "e": 1126, "s": 943, "text": "The IncludePromptAndLiterals value provides the text input, which is given by the user, the literal characters that are defined in the mask and the instances of the prompt character." }, { "code": null, "e": 1230, "s": 1126, "text": "The default value of this property is IncludeLiterals. You can set this property in two different ways:" }, { "code": null, "e": 1370, "s": 1230, "text": "1. Design-Time: It is the easiest way to set the value of TextMaskFormat property of MaskedTextBox control as shown in the following steps:" }, { "code": null, "e": 1486, "s": 1370, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 1544, "s": 1486, "text": "Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 1657, "s": 1544, "text": "Step 2: Next, drag and drop the MaskedTextBox control from the toolbox on the form. As shown in the below image:" }, { "code": null, "e": 1842, "s": 1657, "text": "Step 3: After drag and drop you will go to the properties of the MaskedTextBox and set the value of TextMaskFormat property of MaskedTextBox control as shown in the below image:Output:" }, { "code": null, "e": 1850, "s": 1842, "text": "Output:" }, { "code": null, "e": 2056, "s": 1850, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the value of TextMaskFormat property of the MaskedTextBox control programmatically with the help of given syntax:" }, { "code": null, "e": 2124, "s": 2056, "text": "public System.Windows.Forms.MaskFormat TextMaskFormat { get; set; }" }, { "code": null, "e": 2431, "s": 2124, "text": "Here, MaskFormat holds the values of the TextMaskFormat property. If the value of this property does not belong to the MaskFormat enum, then it will throw an InvalidEnumArgumentException. The following steps show how to set the value of the TextMaskFormat property of the MaskedTextBox control dynamically:" }, { "code": null, "e": 2607, "s": 2431, "text": "Step 1: Create a MaskedTextBox using the MaskedTextBox() constructor is provided by the MaskedTextBox class.// Creating a MaskedTextBox\nMaskedTextBox m = new MaskedTextBox();\n" }, { "code": null, "e": 2675, "s": 2607, "text": "// Creating a MaskedTextBox\nMaskedTextBox m = new MaskedTextBox();\n" }, { "code": null, "e": 2889, "s": 2675, "text": "Step 2: After creating MaskedTextBox, set the TextMaskFormat property of the MaskedTextBox provided by the MaskedTextBox class.// Setting the TextMaskFormat property\nm.TextMaskFormat = MaskFormat.IncludeLiterals;\n" }, { "code": null, "e": 2976, "s": 2889, "text": "// Setting the TextMaskFormat property\nm.TextMaskFormat = MaskFormat.IncludeLiterals;\n" }, { "code": null, "e": 4670, "s": 2976, "text": "Step 3: And last add this MaskedTextBox control to the form using the following statement:// Adding MaskedTextBox control on the form\nthis.Controls.Add(m);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = \" Example\"; l1.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = \"Phone number:\"; l2.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = \"000000000\"; m.Size = new Size(176, 20); m.Name = \"MyBox\"; m.BorderStyle = BorderStyle.Fixed3D; m.TextMaskFormat = MaskFormat.IncludeLiterals; m.Font = new Font(\"Bell MT\", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}}Output:" }, { "code": null, "e": 4737, "s": 4670, "text": "// Adding MaskedTextBox control on the form\nthis.Controls.Add(m);\n" }, { "code": null, "e": 4746, "s": 4737, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = \" Example\"; l1.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = \"Phone number:\"; l2.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = \"000000000\"; m.Size = new Size(176, 20); m.Name = \"MyBox\"; m.BorderStyle = BorderStyle.Fixed3D; m.TextMaskFormat = MaskFormat.IncludeLiterals; m.Font = new Font(\"Bell MT\", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}}", "e": 6269, "s": 4746, "text": null }, { "code": null, "e": 6277, "s": 6269, "text": "Output:" }, { "code": null, "e": 6308, "s": 6277, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 6311, "s": 6308, "text": "C#" } ]
Python – Get the indices of all occurrences of an element in a list
28 Nov, 2021 Given a list, the task is to write a Python Program to get the indices of all occurrences of an element in a list. This is a simple method to get the indices of all occurrences of an element in a list. Here we use a for-loop to iterate through each element in the original list. Syntax : for iterator_name in range(length) where iterator_name is the name of the iterator length is the size of the list Example : Python3 # initialize a listmy_list = [1, 2, 3, 1, 5, 4] # find length of the listlist_size = len(my_list) # declare for loopfor itr in range(list_size): # check the condition if(my_list[itr] == 1): # print the indices print(itr) Output: 0 3 Instead of using for-loop we can use enumerate function. This function adds a counter to an iterable and returns the enumerate object. Syntax: [expression for element_name in enumerate(list_name) if condition] where Element_name is the name of the element list_name is the name of the list Condition is the condition that needs to be true For this, we will create list and then we will create enumerate function to get indices of all occurrences of an element in a list Example : Python3 # initialize a listmy_list = [1, 2, 3, 1, 5, 4] indices = [ind for ind, ele in enumerate(my_list) if ele == 1] # print the indicesprint(indices) Output: [0, 3] Itertools is memory-efficient tools that are useful by themselves or in combination, so for this we will use count() methods from this module which will return an iterator of evenly spaced values from the start value. Syntax: [expression for element_name in zip(count(), list_name) if condition] element_name is the name of the element list_name is the name of the list Condition is the condition that needs to be true For this, we will create a list and then using comprehension with zip() we will get indices of all occurrences of an element in a list. Example: Python3 # import count method from itertoolsfrom itertools import count # initialize a listmy_list = [1, 2, 3, 1, 5, 4] indices = [ind for ind, ele in zip(count(), my_list) if ele == 1] # print the indicesprint(indices) Output: [0, 3] NumPy is general-purpose array-processing package, it provides convenient ways to use arrays in Python. Syntax: numpy.where(list_name,value)[index] where list_name is the name of the list Value is the value to be searched for Index is the starting index of array (usually it will be “0”) For this, we will create an array using numpy.array() and then get all the indices of elements in an input array when the condition is satisfied using numpy.where() methods. Example : Python3 # import numpy moduleimport numpy # initialize a arraymy_list = numpy.array([1, 2, 3, 1, 5, 4]) indices = numpy.where(my_list == 1)[0] # display resultprint(indices) Output : [0, 3] Picked Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Nov, 2021" }, { "code": null, "e": 168, "s": 53, "text": "Given a list, the task is to write a Python Program to get the indices of all occurrences of an element in a list." }, { "code": null, "e": 332, "s": 168, "text": "This is a simple method to get the indices of all occurrences of an element in a list. Here we use a for-loop to iterate through each element in the original list." }, { "code": null, "e": 376, "s": 332, "text": "Syntax : for iterator_name in range(length)" }, { "code": null, "e": 382, "s": 376, "text": "where" }, { "code": null, "e": 424, "s": 382, "text": "iterator_name is the name of the iterator" }, { "code": null, "e": 455, "s": 424, "text": "length is the size of the list" }, { "code": null, "e": 466, "s": 455, "text": "Example : " }, { "code": null, "e": 474, "s": 466, "text": "Python3" }, { "code": "# initialize a listmy_list = [1, 2, 3, 1, 5, 4] # find length of the listlist_size = len(my_list) # declare for loopfor itr in range(list_size): # check the condition if(my_list[itr] == 1): # print the indices print(itr) ", "e": 741, "s": 474, "text": null }, { "code": null, "e": 749, "s": 741, "text": "Output:" }, { "code": null, "e": 753, "s": 749, "text": "0\n3" }, { "code": null, "e": 888, "s": 753, "text": "Instead of using for-loop we can use enumerate function. This function adds a counter to an iterable and returns the enumerate object." }, { "code": null, "e": 963, "s": 888, "text": "Syntax: [expression for element_name in enumerate(list_name) if condition]" }, { "code": null, "e": 969, "s": 963, "text": "where" }, { "code": null, "e": 1009, "s": 969, "text": "Element_name is the name of the element" }, { "code": null, "e": 1043, "s": 1009, "text": "list_name is the name of the list" }, { "code": null, "e": 1092, "s": 1043, "text": "Condition is the condition that needs to be true" }, { "code": null, "e": 1223, "s": 1092, "text": "For this, we will create list and then we will create enumerate function to get indices of all occurrences of an element in a list" }, { "code": null, "e": 1233, "s": 1223, "text": "Example :" }, { "code": null, "e": 1241, "s": 1233, "text": "Python3" }, { "code": "# initialize a listmy_list = [1, 2, 3, 1, 5, 4] indices = [ind for ind, ele in enumerate(my_list) if ele == 1] # print the indicesprint(indices) ", "e": 1390, "s": 1241, "text": null }, { "code": null, "e": 1398, "s": 1390, "text": "Output:" }, { "code": null, "e": 1405, "s": 1398, "text": "[0, 3]" }, { "code": null, "e": 1623, "s": 1405, "text": "Itertools is memory-efficient tools that are useful by themselves or in combination, so for this we will use count() methods from this module which will return an iterator of evenly spaced values from the start value." }, { "code": null, "e": 1701, "s": 1623, "text": "Syntax: [expression for element_name in zip(count(), list_name) if condition]" }, { "code": null, "e": 1741, "s": 1701, "text": "element_name is the name of the element" }, { "code": null, "e": 1775, "s": 1741, "text": "list_name is the name of the list" }, { "code": null, "e": 1824, "s": 1775, "text": "Condition is the condition that needs to be true" }, { "code": null, "e": 1961, "s": 1824, "text": "For this, we will create a list and then using comprehension with zip() we will get indices of all occurrences of an element in a list. " }, { "code": null, "e": 1971, "s": 1961, "text": "Example: " }, { "code": null, "e": 1979, "s": 1971, "text": "Python3" }, { "code": "# import count method from itertoolsfrom itertools import count # initialize a listmy_list = [1, 2, 3, 1, 5, 4] indices = [ind for ind, ele in zip(count(), my_list) if ele == 1] # print the indicesprint(indices) ", "e": 2229, "s": 1979, "text": null }, { "code": null, "e": 2237, "s": 2229, "text": "Output:" }, { "code": null, "e": 2244, "s": 2237, "text": "[0, 3]" }, { "code": null, "e": 2349, "s": 2244, "text": "NumPy is general-purpose array-processing package, it provides convenient ways to use arrays in Python. " }, { "code": null, "e": 2393, "s": 2349, "text": "Syntax: numpy.where(list_name,value)[index]" }, { "code": null, "e": 2400, "s": 2393, "text": "where " }, { "code": null, "e": 2434, "s": 2400, "text": "list_name is the name of the list" }, { "code": null, "e": 2472, "s": 2434, "text": "Value is the value to be searched for" }, { "code": null, "e": 2534, "s": 2472, "text": "Index is the starting index of array (usually it will be “0”)" }, { "code": null, "e": 2708, "s": 2534, "text": "For this, we will create an array using numpy.array() and then get all the indices of elements in an input array when the condition is satisfied using numpy.where() methods." }, { "code": null, "e": 2719, "s": 2708, "text": "Example : " }, { "code": null, "e": 2727, "s": 2719, "text": "Python3" }, { "code": "# import numpy moduleimport numpy # initialize a arraymy_list = numpy.array([1, 2, 3, 1, 5, 4]) indices = numpy.where(my_list == 1)[0] # display resultprint(indices) ", "e": 2900, "s": 2727, "text": null }, { "code": null, "e": 2909, "s": 2900, "text": "Output :" }, { "code": null, "e": 2916, "s": 2909, "text": "[0, 3]" }, { "code": null, "e": 2923, "s": 2916, "text": "Picked" }, { "code": null, "e": 2944, "s": 2923, "text": "Python list-programs" }, { "code": null, "e": 2956, "s": 2944, "text": "python-list" }, { "code": null, "e": 2963, "s": 2956, "text": "Python" }, { "code": null, "e": 2979, "s": 2963, "text": "Python Programs" }, { "code": null, "e": 2991, "s": 2979, "text": "python-list" } ]
Python | Sort given list by frequency and remove duplicates
11 May, 2020 Problems associated with sorting and removal of duplicates is quite common in development domain and general coding as well. The sorting by frequency has been discussed, but sometimes, we even wish to remove the duplicates without using more LOC’s and in a shorter way. Let’s discuss certain ways in which this can be done. Method #1 : Using count() + set() + sorted() The sorted function can be used to sort the elements as desired, the frequency can be computed using the count function and removal of duplicates can be handled using the set function. # Python3 code to demonstrate# sorting and removal of duplicates# Using sorted() + set() + count() # initializing listtest_list = [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5] # printing original listprint("The original list : " + str(test_list)) # using sorted() + set() + count()# sorting and removal of duplicatesres = sorted(set(test_list), key = lambda ele: test_list.count(ele)) # print resultprint("The list after sorting and removal : " + str(res)) The original list : [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5] The list after sorting and removal : [2, 3, 6, 5] Method #2 : Using Counter.most_common() + list comprehension If one has a particular use case of sorting by the decreasing order of frequency, one can also use most-common function of Counter library to get frequency part. # Python3 code to demonstrate# sorting and removal of duplicates# Using Counter.most_common() + list comprehensionfrom collections import Counter # initializing listtest_list = [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5] # printing original listprint("The original list : " + str(test_list)) # using Counter.most_common() + list comprehension# sorting and removal of duplicatesres = [key for key, value in Counter(test_list).most_common()] # print resultprint("The list after sorting and removal : " + str(res)) The original list : [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5] The list after sorting and removal : [5, 6, 3, 2] Python list-programs Python-sort Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2020" }, { "code": null, "e": 352, "s": 28, "text": "Problems associated with sorting and removal of duplicates is quite common in development domain and general coding as well. The sorting by frequency has been discussed, but sometimes, we even wish to remove the duplicates without using more LOC’s and in a shorter way. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 397, "s": 352, "text": "Method #1 : Using count() + set() + sorted()" }, { "code": null, "e": 582, "s": 397, "text": "The sorted function can be used to sort the elements as desired, the frequency can be computed using the count function and removal of duplicates can be handled using the set function." }, { "code": "# Python3 code to demonstrate# sorting and removal of duplicates# Using sorted() + set() + count() # initializing listtest_list = [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5] # printing original listprint(\"The original list : \" + str(test_list)) # using sorted() + set() + count()# sorting and removal of duplicatesres = sorted(set(test_list), key = lambda ele: test_list.count(ele)) # print resultprint(\"The list after sorting and removal : \" + str(res))", "e": 1031, "s": 582, "text": null }, { "code": null, "e": 1136, "s": 1031, "text": "The original list : [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5]\nThe list after sorting and removal : [2, 3, 6, 5]\n" }, { "code": null, "e": 1199, "s": 1138, "text": "Method #2 : Using Counter.most_common() + list comprehension" }, { "code": null, "e": 1361, "s": 1199, "text": "If one has a particular use case of sorting by the decreasing order of frequency, one can also use most-common function of Counter library to get frequency part." }, { "code": "# Python3 code to demonstrate# sorting and removal of duplicates# Using Counter.most_common() + list comprehensionfrom collections import Counter # initializing listtest_list = [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5] # printing original listprint(\"The original list : \" + str(test_list)) # using Counter.most_common() + list comprehension# sorting and removal of duplicatesres = [key for key, value in Counter(test_list).most_common()] # print resultprint(\"The list after sorting and removal : \" + str(res))", "e": 1867, "s": 1361, "text": null }, { "code": null, "e": 1972, "s": 1867, "text": "The original list : [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5]\nThe list after sorting and removal : [5, 6, 3, 2]\n" }, { "code": null, "e": 1993, "s": 1972, "text": "Python list-programs" }, { "code": null, "e": 2005, "s": 1993, "text": "Python-sort" }, { "code": null, "e": 2012, "s": 2005, "text": "Python" }, { "code": null, "e": 2028, "s": 2012, "text": "Python Programs" } ]
Scrape and Save Table Data in CSV file using Selenium in Python
30 Jun, 2021 Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make things easy, we will be using it. Further to store the data, we will be using the pandas and csv module of python. Note: Make sure that you have the chromedriver installed in your system and it must be in the same folder as the python file. The chromedriver can be found here. First, we need to locate the elements of the table, for this selenium WebDriver. We will be using the xpath method as most of the elements in the webpage have a unique xpath. Step 1: Import the required modules. Python3 from selenium import webdriverfrom selenium.webdriver.support.ui import Selectfrom selenium.webdriver.support.ui import WebDriverWait import timeimport pandas as pdfrom selenium.webdriver.support.ui import Selectfrom selenium.common.exceptions import NoSuchElementExceptionfrom selenium.webdriver.common.keys import Keysimport csv Step 2: Initialise the web browser with a variable driver, mention the executable_path as the location where you have the chromedriver file, and direct to the required URL. Python3 driver = webdriver.Chrome( executable_path='/usr/lib/chromium-browser/chromedriver') driver.get('https://www.geeksforgeeks.org/selenium-python-tutorial/') Step 3: Wait for the WebPage to load. You can do so by the implicitly_wait(​) method. When fully loaded, maximize the window use maximize_window(). Python3 driver.implicitly_wait(10)driver.maximize_window() Step 4: Try to find a pattern in the xpath’s of the rows and locate them using find_element_by_xpath(), and run a loop to find all the table cells and convert them into text by adding .text() at the end of every element located through the generalized xpath. Python3 while(1): try: method=driver.find_element_by_xpath('//*[@id="post-427949"]\ /div[3]/table[2]/tbody/tr['+str(r)+']/td[1]').text Desc=driver.find_element_by_xpath('//*[@id="post-427949"]\ /div[3]/table[2]/tbody/tr['+str(r)+']/td[2]').text Table_dict={ 'Method':method, 'Description':Desc } templist.append(Table_dict) df=pd.DataFrame(templist) r+=1 except NoSuchElementException: break Step 5: Export the Dataframe to a CSV file and close the exit of the browser. Python3 df.to_csv('table.csv')driver.close() Below is the complete implementation: Python3 from selenium import webdriverfrom selenium.webdriver.support.ui import Selectfrom selenium.webdriver.support.ui import WebDriverWait import timeimport pandas as pdfrom selenium.webdriver.support.ui import Selectfrom selenium.common.exceptions import NoSuchElementExceptionfrom selenium.webdriver.common.keys import Keysimport csv driver = webdriver.Chrome(executable_path = '/usr/lib/chromium-browser/chromedriver') driver.get('https://www.geeksforgeeks.org/selenium-python-tutorial/')driver.implicitly_wait(10)driver.maximize_window()r=1templist = [] while(1): try: method=driver.find_element_by_xpath('//*[@id="post-427949"]\ /div[3]/table[2]/tbody/tr['+str(r)+']/td[1]').text Desc=driver.find_element_by_xpath('//*[@id="post-427949"]/\ div[3]/table[2]/tbody/tr['+str(r)+']/td[2]').text Table_dict={ 'Method': method, 'Description':Desc} templist.append(Table_dict) df = pd.DataFrame(templist) r + = 1 # if there are no more table data to scrape except NoSuchElementException: break # saving the dataframe to a csvdf.to_csv('table.csv') driver.close() Output: Python Selenium-Exercises Python-selenium 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 | os.path.join() method Introduction To PYTHON Python OOPs Concepts 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": 54, "s": 26, "text": "\n30 Jun, 2021" }, { "code": null, "e": 520, "s": 54, "text": "Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make things easy, we will be using it. Further to store the data, we will be using the pandas and csv module of python." }, { "code": null, "e": 682, "s": 520, "text": "Note: Make sure that you have the chromedriver installed in your system and it must be in the same folder as the python file. The chromedriver can be found here." }, { "code": null, "e": 858, "s": 682, "text": "First, we need to locate the elements of the table, for this selenium WebDriver. We will be using the xpath method as most of the elements in the webpage have a unique xpath. " }, { "code": null, "e": 896, "s": 858, "text": "Step 1: Import the required modules. " }, { "code": null, "e": 904, "s": 896, "text": "Python3" }, { "code": "from selenium import webdriverfrom selenium.webdriver.support.ui import Selectfrom selenium.webdriver.support.ui import WebDriverWait import timeimport pandas as pdfrom selenium.webdriver.support.ui import Selectfrom selenium.common.exceptions import NoSuchElementExceptionfrom selenium.webdriver.common.keys import Keysimport csv", "e": 1235, "s": 904, "text": null }, { "code": null, "e": 1408, "s": 1235, "text": "Step 2: Initialise the web browser with a variable driver, mention the executable_path as the location where you have the chromedriver file, and direct to the required URL." }, { "code": null, "e": 1416, "s": 1408, "text": "Python3" }, { "code": "driver = webdriver.Chrome( executable_path='/usr/lib/chromium-browser/chromedriver') driver.get('https://www.geeksforgeeks.org/selenium-python-tutorial/')", "e": 1572, "s": 1416, "text": null }, { "code": null, "e": 1720, "s": 1572, "text": "Step 3: Wait for the WebPage to load. You can do so by the implicitly_wait(​) method. When fully loaded, maximize the window use maximize_window()." }, { "code": null, "e": 1728, "s": 1720, "text": "Python3" }, { "code": "driver.implicitly_wait(10)driver.maximize_window()", "e": 1779, "s": 1728, "text": null }, { "code": null, "e": 2038, "s": 1779, "text": "Step 4: Try to find a pattern in the xpath’s of the rows and locate them using find_element_by_xpath(), and run a loop to find all the table cells and convert them into text by adding .text() at the end of every element located through the generalized xpath." }, { "code": null, "e": 2046, "s": 2038, "text": "Python3" }, { "code": "while(1): try: method=driver.find_element_by_xpath('//*[@id=\"post-427949\"]\\ /div[3]/table[2]/tbody/tr['+str(r)+']/td[1]').text Desc=driver.find_element_by_xpath('//*[@id=\"post-427949\"]\\ /div[3]/table[2]/tbody/tr['+str(r)+']/td[2]').text Table_dict={ 'Method':method, 'Description':Desc } templist.append(Table_dict) df=pd.DataFrame(templist) r+=1 except NoSuchElementException: break", "e": 2536, "s": 2046, "text": null }, { "code": null, "e": 2614, "s": 2536, "text": "Step 5: Export the Dataframe to a CSV file and close the exit of the browser." }, { "code": null, "e": 2622, "s": 2614, "text": "Python3" }, { "code": "df.to_csv('table.csv')driver.close()", "e": 2659, "s": 2622, "text": null }, { "code": null, "e": 2697, "s": 2659, "text": "Below is the complete implementation:" }, { "code": null, "e": 2705, "s": 2697, "text": "Python3" }, { "code": "from selenium import webdriverfrom selenium.webdriver.support.ui import Selectfrom selenium.webdriver.support.ui import WebDriverWait import timeimport pandas as pdfrom selenium.webdriver.support.ui import Selectfrom selenium.common.exceptions import NoSuchElementExceptionfrom selenium.webdriver.common.keys import Keysimport csv driver = webdriver.Chrome(executable_path = '/usr/lib/chromium-browser/chromedriver') driver.get('https://www.geeksforgeeks.org/selenium-python-tutorial/')driver.implicitly_wait(10)driver.maximize_window()r=1templist = [] while(1): try: method=driver.find_element_by_xpath('//*[@id=\"post-427949\"]\\ /div[3]/table[2]/tbody/tr['+str(r)+']/td[1]').text Desc=driver.find_element_by_xpath('//*[@id=\"post-427949\"]/\\ div[3]/table[2]/tbody/tr['+str(r)+']/td[2]').text Table_dict={ 'Method': method, 'Description':Desc} templist.append(Table_dict) df = pd.DataFrame(templist) r + = 1 # if there are no more table data to scrape except NoSuchElementException: break # saving the dataframe to a csvdf.to_csv('table.csv') driver.close()", "e": 3935, "s": 2705, "text": null }, { "code": null, "e": 3943, "s": 3935, "text": "Output:" }, { "code": null, "e": 3969, "s": 3943, "text": "Python Selenium-Exercises" }, { "code": null, "e": 3985, "s": 3969, "text": "Python-selenium" }, { "code": null, "e": 3992, "s": 3985, "text": "Python" }, { "code": null, "e": 4090, "s": 3992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4122, "s": 4090, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4149, "s": 4122, "text": "Python Classes and Objects" }, { "code": null, "e": 4180, "s": 4149, "text": "Python | os.path.join() method" }, { "code": null, "e": 4203, "s": 4180, "text": "Introduction To PYTHON" }, { "code": null, "e": 4224, "s": 4203, "text": "Python OOPs Concepts" }, { "code": null, "e": 4280, "s": 4224, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4322, "s": 4280, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4364, "s": 4322, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4403, "s": 4364, "text": "Python | Get unique values from a list" } ]
PHP | str_pad() Function
22 Mar, 2018 The str_pad() function is a built-in function in PHP and is used to pad a string to a given length. We can pad the input string by any other string up to a specified length. If we do not pass the other string to the str_pad() function then the input string will be padded by spaces. Syntax : string str_pad($string, $length, $pad_string, $pad_type) Parameters: This function accepts four parameters as shown in the above syntax out of which first two are mandatory to be supplied and rest two are optional. All of these parameters are described below: $string: This parameter is mandatory. It specifies the input string which is needed to be padded. $length: This parameter is also mandatory. It specifies the length of the new string that will be generated after padding the input string $string. If this length is less than or equals the length of input string then no padding will be done. $pad_string: This parameter is optional and its default value is whitespace ‘ ‘. It specifies the string to be used for padding. $pad_type: This parameter is also optional. It specifies which side of the string needs to be padded, i.e. left, right or both. By default it’s value is set to STR_PAD_RIGHT. If we want to pad the left side of the input string then we should set this parameter to STR_PAD_LEFT and if we want to pad both sides then this parameter should be set to STR_PAD_BOTH. Return Value: This parameter returns a new string obtained after padding the input string $string. Examples: Input : $string = "Hello World", $length = 20, $pad_string = "." Output : Hello World........ Input : $string = "Geeks for geeks", $length = 18, $pad_string = ")" Output : Geeks for geeks))) Below programs illustrate the str_pad() function in PHP: Program 1: In this program we will pad to both the sides of the input string by setting last parameter to STR_PAD_BOTH. If the padding length is not an even number, the right side gets the extra padding. <?php $str = "Geeks for geeks"; echo str_pad($str, 21, ":-)", STR_PAD_BOTH); ?> Output: :-)Geeks for geeks:-) Program 2: In this program we will pad to left side of the input string by setting last parameter to STR_PAD_LEFT. <?php $str = "Geeks for geeks"; echo str_pad($str, 25, "Contribute", STR_PAD_LEFT); ?> Output: ContributeGeeks for geeks Program 3: In this program we will pad to right side of the input string by setting last parameter to STR_PAD_RIGHT. <?php $str = "Geeks for geeks"; echo str_pad($str, 26, " Contribute", STR_PAD_RIGHT); ?> Output: Geeks for geeks Contribute Reference:http://php.net/manual/en/function.str-pad.php PHP-string PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Mar, 2018" }, { "code": null, "e": 311, "s": 28, "text": "The str_pad() function is a built-in function in PHP and is used to pad a string to a given length. We can pad the input string by any other string up to a specified length. If we do not pass the other string to the str_pad() function then the input string will be padded by spaces." }, { "code": null, "e": 320, "s": 311, "text": "Syntax :" }, { "code": null, "e": 377, "s": 320, "text": "string str_pad($string, $length, $pad_string, $pad_type)" }, { "code": null, "e": 580, "s": 377, "text": "Parameters: This function accepts four parameters as shown in the above syntax out of which first two are mandatory to be supplied and rest two are optional. All of these parameters are described below:" }, { "code": null, "e": 678, "s": 580, "text": "$string: This parameter is mandatory. It specifies the input string which is needed to be padded." }, { "code": null, "e": 921, "s": 678, "text": "$length: This parameter is also mandatory. It specifies the length of the new string that will be generated after padding the input string $string. If this length is less than or equals the length of input string then no padding will be done." }, { "code": null, "e": 1050, "s": 921, "text": "$pad_string: This parameter is optional and its default value is whitespace ‘ ‘. It specifies the string to be used for padding." }, { "code": null, "e": 1411, "s": 1050, "text": "$pad_type: This parameter is also optional. It specifies which side of the string needs to be padded, i.e. left, right or both. By default it’s value is set to STR_PAD_RIGHT. If we want to pad the left side of the input string then we should set this parameter to STR_PAD_LEFT and if we want to pad both sides then this parameter should be set to STR_PAD_BOTH." }, { "code": null, "e": 1510, "s": 1411, "text": "Return Value: This parameter returns a new string obtained after padding the input string $string." }, { "code": null, "e": 1520, "s": 1510, "text": "Examples:" }, { "code": null, "e": 1730, "s": 1520, "text": "Input : $string = \"Hello World\", $length = 20, \n $pad_string = \".\"\nOutput : Hello World........\n\nInput : $string = \"Geeks for geeks\", $length = 18,\n $pad_string = \")\"\nOutput : Geeks for geeks)))\n" }, { "code": null, "e": 1787, "s": 1730, "text": "Below programs illustrate the str_pad() function in PHP:" }, { "code": null, "e": 1991, "s": 1787, "text": "Program 1: In this program we will pad to both the sides of the input string by setting last parameter to STR_PAD_BOTH. If the padding length is not an even number, the right side gets the extra padding." }, { "code": "<?php $str = \"Geeks for geeks\"; echo str_pad($str, 21, \":-)\", STR_PAD_BOTH); ?>", "e": 2075, "s": 1991, "text": null }, { "code": null, "e": 2083, "s": 2075, "text": "Output:" }, { "code": null, "e": 2106, "s": 2083, "text": ":-)Geeks for geeks:-)\n" }, { "code": null, "e": 2221, "s": 2106, "text": "Program 2: In this program we will pad to left side of the input string by setting last parameter to STR_PAD_LEFT." }, { "code": "<?php $str = \"Geeks for geeks\"; echo str_pad($str, 25, \"Contribute\", STR_PAD_LEFT); ?>", "e": 2312, "s": 2221, "text": null }, { "code": null, "e": 2320, "s": 2312, "text": "Output:" }, { "code": null, "e": 2347, "s": 2320, "text": "ContributeGeeks for geeks\n" }, { "code": null, "e": 2464, "s": 2347, "text": "Program 3: In this program we will pad to right side of the input string by setting last parameter to STR_PAD_RIGHT." }, { "code": "<?php $str = \"Geeks for geeks\"; echo str_pad($str, 26, \" Contribute\", STR_PAD_RIGHT); ?>", "e": 2557, "s": 2464, "text": null }, { "code": null, "e": 2565, "s": 2557, "text": "Output:" }, { "code": null, "e": 2593, "s": 2565, "text": "Geeks for geeks Contribute\n" }, { "code": null, "e": 2649, "s": 2593, "text": "Reference:http://php.net/manual/en/function.str-pad.php" }, { "code": null, "e": 2660, "s": 2649, "text": "PHP-string" }, { "code": null, "e": 2664, "s": 2660, "text": "PHP" }, { "code": null, "e": 2681, "s": 2664, "text": "Web Technologies" }, { "code": null, "e": 2685, "s": 2681, "text": "PHP" } ]
strspn() function in C
02 Oct, 2017 The strspn() function returns the length of the initial substring of the string pointed to by str1 that is made up of only those character contained in the string pointed to by str2. Syntax : size_t strspn(const char *str1, const char *str2) str1 : string to be scanned. str2 : string containing the characters to match. Return Value : This function returns the number of characters in the initial segment of str1 which consist only of characters from str2. // C program to illustrate strspn() function#include <stdio.h>#include <string.h> int main () { int len = strspn("geeks for geeks","geek"); printf("Length of initial segment matching : %d\n", len ); return(0);} Output: Length of initial segment matching 4 // C program to illustrate strspn() function#include <stdio.h>#include <string.h> int main () { int len = strspn("i am","xyz"); printf("Length of initial segment matching : %d\n", len ); return(0);} Output: Length of initial segment matching 0 This article is contributed by Shivani Ghughtyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Library C-String C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n02 Oct, 2017" }, { "code": null, "e": 236, "s": 53, "text": "The strspn() function returns the length of the initial substring of the string pointed to by str1 that is made up of only those character contained in the string pointed to by str2." }, { "code": null, "e": 245, "s": 236, "text": "Syntax :" }, { "code": null, "e": 514, "s": 245, "text": "size_t strspn(const char *str1, const char *str2)\nstr1 : string to be scanned.\nstr2 : string containing the \ncharacters to match.\nReturn Value : This function\nreturns the number of characters\nin the initial segment of str1 \nwhich consist only of characters \nfrom str2." }, { "code": " // C program to illustrate strspn() function#include <stdio.h>#include <string.h> int main () { int len = strspn(\"geeks for geeks\",\"geek\"); printf(\"Length of initial segment matching : %d\\n\", len ); return(0);}", "e": 739, "s": 514, "text": null }, { "code": null, "e": 747, "s": 739, "text": "Output:" }, { "code": null, "e": 784, "s": 747, "text": "Length of initial segment matching 4" }, { "code": " // C program to illustrate strspn() function#include <stdio.h>#include <string.h> int main () { int len = strspn(\"i am\",\"xyz\"); printf(\"Length of initial segment matching : %d\\n\", len ); return(0);}", "e": 993, "s": 784, "text": null }, { "code": null, "e": 1001, "s": 993, "text": "Output:" }, { "code": null, "e": 1038, "s": 1001, "text": "Length of initial segment matching 0" }, { "code": null, "e": 1343, "s": 1038, "text": "This article is contributed by Shivani Ghughtyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1468, "s": 1343, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1478, "s": 1468, "text": "C-Library" }, { "code": null, "e": 1487, "s": 1478, "text": "C-String" }, { "code": null, "e": 1498, "s": 1487, "text": "C Language" } ]
std::setbase, std::setw , std::setfill in C++
10 Nov, 2021 The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : std::setbase (int base); decimal : if base is 10 hexadecimal : if base is 16 octal : if base is 8 zero : if base is any other value. Implementation : This code uses the std::setbase manipulator to set hexadecimal as the base field selective flag. CPP // CPP Program to illustrate// std::setbase manipulator#include <iostream>#include <iomanip> // std::setbase int main(){ // set base to hexadecimal std::cout << std::setbase(16); // displaying 255 in hexadecimal std::cout << 255 << std::endl; // set base to Octal std::cout << std::setbase(8); // displaying 255 in Octal std::cout << 255 << std::endl; return 0;} Output: ff 377 std::setw : Set field width; Sets the field width to be used on output operations. Behaves as if member width were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams). Syntax : std::setw (int n); where n is Number of characters to be used as field width. CPP // CPP Program to illustrate// std::setw manipulator#include <iostream>#include <iomanip> // std::setw int main(){ // set width of 10 std::cout << std::setw(10); std::cout << 100 << std::endl; std::string str = "GFG"; // set width of 12 std::cout << std::setw(12); std::cout << str << std::endl; return 0;} Output: 100 GFG Note: Here argument given to setw() is minimum width of the output, so if we have output with more width than argument’s value then output width will not be exactly the argument given to setw() but will be equal to the output size(i.e., the output will not get truncated). Default width of setw() is 0.Example: CPP #include <iostream>#include<iomanip>#include<string>using std::cout;using std::string;using std::endl; int main() { string temp="Hello setw"; cout<<std::setw(5)<<temp<<endl; return 0;} Output: Hello setw std::setfill : Set fill character; Sets c as the stream’s fill character. Behaves as if member fill were called with c as argument on the stream on which it is inserted as a manipulator (it can be inserted on output streams).Syntax : std::setfill (char_type c); char_type is the type of characters used by the stream (i.e., its first class template parameter, charT). Implementation : CPP // CPP Program to test std::setfill manipulator#include <iostream>#include <iomanip> // std::setfill, std::setw int main(){ // setfill is x and width is set as 10 std::cout << std::setfill('x') << std::setw(10); std::cout << 77 << std::endl; std::string str = "Geeks"; // setfill is G and width is set as 10 // And std::left is used set str to left side std::cout << std::left << std::setfill('G') << std::setw(10); std::cout << str << std::endl; return 0;} Output: xxxxxxxx77 GeeksGGGGG Pattern using std::setw and std::fill : CPP // CPP Program to print// pattern using std::setw and std::fill#include <iostream>#include <iomanip> // std::setfill, std::setw int main(){ int n = 5; for (int i = 1; i <= n; i++) { std::cout << std::left << std::setfill(' ') << std::setw(n); std::cout << std::string(i, '*') << std::endl; }} Output: * ** *** **** ***** This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Aakash_Panchal singghakshay CBSE - Class 11 CPP-Library school-programming C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Nov, 2021" }, { "code": null, "e": 190, "s": 52, "text": "The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. " }, { "code": null, "e": 326, "s": 190, "text": "std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : " }, { "code": null, "e": 459, "s": 326, "text": "std::setbase (int base);\ndecimal : if base is 10\nhexadecimal : if base is 16\noctal : if base is 8\nzero : if base is any other value." }, { "code": null, "e": 573, "s": 459, "text": "Implementation : This code uses the std::setbase manipulator to set hexadecimal as the base field selective flag." }, { "code": null, "e": 577, "s": 573, "text": "CPP" }, { "code": "// CPP Program to illustrate// std::setbase manipulator#include <iostream>#include <iomanip> // std::setbase int main(){ // set base to hexadecimal std::cout << std::setbase(16); // displaying 255 in hexadecimal std::cout << 255 << std::endl; // set base to Octal std::cout << std::setbase(8); // displaying 255 in Octal std::cout << 255 << std::endl; return 0;}", "e": 970, "s": 577, "text": null }, { "code": null, "e": 979, "s": 970, "text": "Output: " }, { "code": null, "e": 986, "s": 979, "text": "ff\n377" }, { "code": null, "e": 1269, "s": 986, "text": "std::setw : Set field width; Sets the field width to be used on output operations. Behaves as if member width were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams). Syntax : " }, { "code": null, "e": 1348, "s": 1269, "text": "std::setw (int n);\nwhere n is Number of characters to \nbe used as field width." }, { "code": null, "e": 1352, "s": 1348, "text": "CPP" }, { "code": "// CPP Program to illustrate// std::setw manipulator#include <iostream>#include <iomanip> // std::setw int main(){ // set width of 10 std::cout << std::setw(10); std::cout << 100 << std::endl; std::string str = \"GFG\"; // set width of 12 std::cout << std::setw(12); std::cout << str << std::endl; return 0;}", "e": 1687, "s": 1352, "text": null }, { "code": null, "e": 1696, "s": 1687, "text": "Output: " }, { "code": null, "e": 1720, "s": 1696, "text": " 100\n GFG" }, { "code": null, "e": 2032, "s": 1720, "text": "Note: Here argument given to setw() is minimum width of the output, so if we have output with more width than argument’s value then output width will not be exactly the argument given to setw() but will be equal to the output size(i.e., the output will not get truncated). Default width of setw() is 0.Example: " }, { "code": null, "e": 2036, "s": 2032, "text": "CPP" }, { "code": "#include <iostream>#include<iomanip>#include<string>using std::cout;using std::string;using std::endl; int main() { string temp=\"Hello setw\"; cout<<std::setw(5)<<temp<<endl; return 0;}", "e": 2230, "s": 2036, "text": null }, { "code": null, "e": 2239, "s": 2230, "text": "Output: " }, { "code": null, "e": 2250, "s": 2239, "text": "Hello setw" }, { "code": null, "e": 2485, "s": 2250, "text": "std::setfill : Set fill character; Sets c as the stream’s fill character. Behaves as if member fill were called with c as argument on the stream on which it is inserted as a manipulator (it can be inserted on output streams).Syntax : " }, { "code": null, "e": 2621, "s": 2485, "text": "std::setfill (char_type c);\nchar_type is the type of characters \nused by the stream (i.e., its first class template \nparameter, charT)." }, { "code": null, "e": 2639, "s": 2621, "text": "Implementation : " }, { "code": null, "e": 2643, "s": 2639, "text": "CPP" }, { "code": "// CPP Program to test std::setfill manipulator#include <iostream>#include <iomanip> // std::setfill, std::setw int main(){ // setfill is x and width is set as 10 std::cout << std::setfill('x') << std::setw(10); std::cout << 77 << std::endl; std::string str = \"Geeks\"; // setfill is G and width is set as 10 // And std::left is used set str to left side std::cout << std::left << std::setfill('G') << std::setw(10); std::cout << str << std::endl; return 0;}", "e": 3132, "s": 2643, "text": null }, { "code": null, "e": 3141, "s": 3132, "text": "Output: " }, { "code": null, "e": 3163, "s": 3141, "text": "xxxxxxxx77\nGeeksGGGGG" }, { "code": null, "e": 3204, "s": 3163, "text": "Pattern using std::setw and std::fill : " }, { "code": null, "e": 3208, "s": 3204, "text": "CPP" }, { "code": "// CPP Program to print// pattern using std::setw and std::fill#include <iostream>#include <iomanip> // std::setfill, std::setw int main(){ int n = 5; for (int i = 1; i <= n; i++) { std::cout << std::left << std::setfill(' ') << std::setw(n); std::cout << std::string(i, '*') << std::endl; }}", "e": 3524, "s": 3208, "text": null }, { "code": null, "e": 3533, "s": 3524, "text": "Output: " }, { "code": null, "e": 3553, "s": 3533, "text": "*\n**\n***\n****\n*****" }, { "code": null, "e": 3973, "s": 3553, "text": "This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3988, "s": 3973, "text": "Aakash_Panchal" }, { "code": null, "e": 4001, "s": 3988, "text": "singghakshay" }, { "code": null, "e": 4017, "s": 4001, "text": "CBSE - Class 11" }, { "code": null, "e": 4029, "s": 4017, "text": "CPP-Library" }, { "code": null, "e": 4048, "s": 4029, "text": "school-programming" }, { "code": null, "e": 4052, "s": 4048, "text": "C++" }, { "code": null, "e": 4056, "s": 4052, "text": "CPP" } ]
Find columns and rows with NA in R DataFrame
26 Mar, 2021 A data frame comprises cells, called data elements arranged in the form of a table of rows and columns. A data frame can have data elements belonging to different data types as well as missing values, denoted by NA. Approach Declare data frame Use function to get values to get NA values Store position Display result The following in-built functions in R collectively can be used to find the rows and column pairs with NA values in the data frame. The is.na() function returns a logical vector of True and False values to indicate which of the corresponding elements are NA or not. This is followed by the application of which() function which indicates the position of the data elements. The following code snippet can be used to find such element index positions. Syntax: which(is.na(dataframe), arr.ind=TRUE) Example: R # declaring data framedata_frame = data.frame(col1 = c(1,NA),col2 = c(7:8),col3 = c(NA,NA)) # printing original data frameprint ("Original Data Frame")print(data_frame) # extracting positions of NA valuesprint ("Row and Col positions of NA values")which(is.na(data_frame), arr.ind=TRUE) Output [1] "Original Data Frame" col1 col2 col3 1 1 7 NA 2 NA 8 NA [1] "Row and Col positions of NA values" row col [1,] 2 1 [2,] 1 3 [3,] 2 3 In case, we don’t specify arr,ind=TRUE as an argument, then the element number counting row wise is returned. Example: R # declaring data framedata_frame = data.frame(col1 = c("A",NA,"B"),col2 = c(100:102),col3 = c(NA,NA,9)) # printing original data frameprint ("Original Data Frame")print(data_frame) # finding NA values beginning with row1 and col1 as the# first element. Rows2 and col2 is second element.print ("Row and Col positions of NA values")which(is.na(data_frame)) Output [1] "Original Data Frame" col1 col2 col3 1 A 100 NA 2 <NA> 101 NA 3 B 102 9 [1] "Row and Col positions of NA values" [1] 2 7 8 The missing values can also be individually be computed within a column, by accessing the specific column of the dataframe using the dataframe$colname as an argument in the above code snippet. In case no NA values are present in a specific column, integer(0) is returned as an output. Example: R # declaring data framedata_frame = data.frame(col1 = c("A",NA,"B"),col2 = c(100:102),col3 = c(NA,NA,9)) # printing original data frameprint ("Original Data Frame")print(data_frame) # extracting positions of NA valuesprint ("NA values in column 1")which(is.na(data_frame$col1), arr.ind=TRUE) # extracting positions of NA valuesprint ("NA values in column 2")which(is.na(data_frame$col2), arr.ind=TRUE) Output [1] "Original Data Frame" col1 col2 col3 1 A 100 NA 2 <NA> 101 NA 3 B 102 9 [1] "NA values in column 1" [1] 2 [1] "NA values in column 2" integer(0) Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2021" }, { "code": null, "e": 245, "s": 28, "text": "A data frame comprises cells, called data elements arranged in the form of a table of rows and columns. A data frame can have data elements belonging to different data types as well as missing values, denoted by NA. " }, { "code": null, "e": 254, "s": 245, "text": "Approach" }, { "code": null, "e": 273, "s": 254, "text": "Declare data frame" }, { "code": null, "e": 317, "s": 273, "text": "Use function to get values to get NA values" }, { "code": null, "e": 332, "s": 317, "text": "Store position" }, { "code": null, "e": 347, "s": 332, "text": "Display result" }, { "code": null, "e": 796, "s": 347, "text": "The following in-built functions in R collectively can be used to find the rows and column pairs with NA values in the data frame. The is.na() function returns a logical vector of True and False values to indicate which of the corresponding elements are NA or not. This is followed by the application of which() function which indicates the position of the data elements. The following code snippet can be used to find such element index positions." }, { "code": null, "e": 804, "s": 796, "text": "Syntax:" }, { "code": null, "e": 842, "s": 804, "text": "which(is.na(dataframe), arr.ind=TRUE)" }, { "code": null, "e": 851, "s": 842, "text": "Example:" }, { "code": null, "e": 853, "s": 851, "text": "R" }, { "code": "# declaring data framedata_frame = data.frame(col1 = c(1,NA),col2 = c(7:8),col3 = c(NA,NA)) # printing original data frameprint (\"Original Data Frame\")print(data_frame) # extracting positions of NA valuesprint (\"Row and Col positions of NA values\")which(is.na(data_frame), arr.ind=TRUE)", "e": 1142, "s": 853, "text": null }, { "code": null, "e": 1149, "s": 1142, "text": "Output" }, { "code": null, "e": 1317, "s": 1149, "text": "[1] \"Original Data Frame\"\n col1 col2 col3\n1 1 7 NA\n2 NA 8 NA\n[1] \"Row and Col positions of NA values\"\n row col\n[1,] 2 1\n[2,] 1 3\n[3,] 2 3" }, { "code": null, "e": 1428, "s": 1317, "text": "In case, we don’t specify arr,ind=TRUE as an argument, then the element number counting row wise is returned. " }, { "code": null, "e": 1437, "s": 1428, "text": "Example:" }, { "code": null, "e": 1439, "s": 1437, "text": "R" }, { "code": "# declaring data framedata_frame = data.frame(col1 = c(\"A\",NA,\"B\"),col2 = c(100:102),col3 = c(NA,NA,9)) # printing original data frameprint (\"Original Data Frame\")print(data_frame) # finding NA values beginning with row1 and col1 as the# first element. Rows2 and col2 is second element.print (\"Row and Col positions of NA values\")which(is.na(data_frame))", "e": 1796, "s": 1439, "text": null }, { "code": null, "e": 1803, "s": 1796, "text": "Output" }, { "code": null, "e": 1947, "s": 1803, "text": "[1] \"Original Data Frame\"\n col1 col2 col3\n1 A 100 NA\n2 <NA> 101 NA\n3 B 102 9\n[1] \"Row and Col positions of NA values\"\n[1] 2 7 8" }, { "code": null, "e": 2233, "s": 1947, "text": "The missing values can also be individually be computed within a column, by accessing the specific column of the dataframe using the dataframe$colname as an argument in the above code snippet. In case no NA values are present in a specific column, integer(0) is returned as an output. " }, { "code": null, "e": 2242, "s": 2233, "text": "Example:" }, { "code": null, "e": 2244, "s": 2242, "text": "R" }, { "code": "# declaring data framedata_frame = data.frame(col1 = c(\"A\",NA,\"B\"),col2 = c(100:102),col3 = c(NA,NA,9)) # printing original data frameprint (\"Original Data Frame\")print(data_frame) # extracting positions of NA valuesprint (\"NA values in column 1\")which(is.na(data_frame$col1), arr.ind=TRUE) # extracting positions of NA valuesprint (\"NA values in column 2\")which(is.na(data_frame$col2), arr.ind=TRUE)", "e": 2648, "s": 2244, "text": null }, { "code": null, "e": 2655, "s": 2648, "text": "Output" }, { "code": null, "e": 2822, "s": 2655, "text": " [1] \"Original Data Frame\"\n col1 col2 col3\n1 A 100 NA\n2 <NA> 101 NA\n3 B 102 9\n[1] \"NA values in column 1\"\n[1] 2\n[1] \"NA values in column 2\"\ninteger(0)" }, { "code": null, "e": 2829, "s": 2822, "text": "Picked" }, { "code": null, "e": 2850, "s": 2829, "text": "R DataFrame-Programs" }, { "code": null, "e": 2862, "s": 2850, "text": "R-DataFrame" }, { "code": null, "e": 2873, "s": 2862, "text": "R Language" }, { "code": null, "e": 2884, "s": 2873, "text": "R Programs" } ]
Stable sort for descending order
10 Sep, 2021 Given an array of n integers, we have to reverse sort the array elements such the equal keys are stable after sorting. Examples: Input : arr[] = {4, 2, 3, 2, 4} Output : 4, 4, 3, 2, 2 Prerequisite : Stability in sorting algorithmsMethod 1 (Writing our own sorting function : Bubble Sort)We know sorting algorithms like Bubble Sort, Insertion Sort, Merge Sort, Count Sort are stable. We implement here Bubble Sort.Explanation First Pass (4′, 2′, 3, 2′′, 4′′) -> (2′, 4′, 3, 4′′, 2′′) Here algorithm compares last two element and swaps since 2′′ < 4′′. (2′, 4′, 3, 4′′, 2′′) -> (2′, 4′, 4′′, 3, 2′′) swap since 3 < 4′′ (2′, 4′, 4′′, 3, 2′′) -> (2′, 4′, 4′′, 3, 2′′) (2′, 4′, 4′′, 3, 2′′) -> (4′, 2′, 4′′, 3, 2′′) swap since 2′ < 4′.Second Pass: (4′, 2′, 4′′, 3, 2′′) -> (4′, 2′, 4′′, 3, 2′′) (4′, 2′, 4′′, 3, 2′′) -> (4′, 2′, 4′′, 3, 2′′) (4′, 2′, 4′′, 3, 2′′) -> (4′, 4′′, 2′, 3, 2′′) swap since 2′ (4′, 4′′, 2′, 3, 2′′)Third Pass: (4′, 4′′, 2′, 3, 2′′) -> (4′, 4′′, 2′, 3, 2′′) (4′, 4′′, 2′, 3, 2′′) -> (4′, 4′′, 3, 2′, 2′′) swap since 2′<3 Now, the array is in sorted order and same elements are in same order as they were in the original array. C++ Java Python3 C# PHP Javascript // Bubble sort implementation to sort// elements in descending order.#include <iostream>#include <vector>using namespace std; void print(vector<int> a, int n){ for (int i = 0; i <= n; i++) cout << a[i] << " "; cout << endl;} // Sorts a[] in descending order using// bubble sort.void sort(vector<int> a, int n){ for (int i = n; i >= 0; i--) for (int j = n; j > n - i; j--) if (a[j] > a[j - 1]) swap(a[j], a[j-1]); print(a, n);} // Driver codeint main(){ int n = 7; vector<int> a; a.push_back(2); a.push_back(4); a.push_back(3); a.push_back(2); a.push_back(4); a.push_back(5); a.push_back(3); sort(a, n - 1); return 0;} // Bubble sort implementation// to sort elements in// descending order.import java.io.*;import java.util.*; class GFG{static void print(ArrayList<Integer> a, int n){ for (int i = 0; i <= n; i++) System.out.print(a.get(i) + " "); System.out.println();} // Sorts a[] in descending// order using bubble sort.static void sort(ArrayList<Integer> a, int n){ for (int i = n; i >= 0; i--) for (int j = n; j > n - i; j--) if (a.get(j) > a.get(j - 1)) { int tempswap = a.get(j); a.remove(j); a.add(j, a.get(j - 1)); a.remove(j - 1); a.add(j - 1, tempswap); } print(a, n);} // Driver codepublic static void main(String[] args){ int n = 6; ArrayList<Integer> a = new ArrayList<Integer>(); a.add(2); a.add(4); a.add(3); a.add(2); a.add(4); a.add(5); a.add(3); sort(a, n);}} // This code is contributed by// Manish Shaw(manishshaw1) # Bubble sort implementation to sort# elements in descending order. def print1(a, n): for i in range(0,n+1): print(a[i],end=" ") print("") # Sorts a[] in descending order using# bubble sort.def sort(a, n): for i in range(n,0,-1): for j in range(n, n - i,-1): if (a[j] > a[j - 1]): a[j], a[j-1]=a[j-1], a[j] print1(a,n) # Driver coden = 7a = [2,4,3,2,4,5,3] sort(a, n-1) # This code is contributed# by Smitha Dinesh Semwal // Bubble sort implementation// to sort elements in// descending order.using System;using System.Collections.Generic; class GFG{static void print(List<int> a, int n){ for (int i = 0; i <= n; i++) Console.Write(a[i] + " "); Console.WriteLine();} // Sorts a[] in descending// order using bubble sort.static void sort(List<int> a, int n){ for (int i = n; i >= 0; i--) for (int j = n; j > n - i; j--) if (a[j] > a[j - 1]) { int tempswap = a[j]; a[j] = a[j - 1]; a[j - 1] = tempswap; } print(a, n);} // Driver codestatic void Main(){ int n = 6; List<int> a = new List<int>(); a.Add(2); a.Add(4); a.Add(3); a.Add(2); a.Add(4); a.Add(5); a.Add(3); sort(a, n);}} // This code is contributed by// Manish Shaw(manishshaw1) <?php// Bubble sort implementation// to sort elements in// descending order. function swap(&$x, &$y){ $x ^= $y ^= $x ^= $y;} function print1($a, $n){ for ($i = 0; $i <= $n; $i++) echo ($a[$i] . " "); echo ("\n");} // Sorts a[] in descending// order using bubble sort.function sort1($a, $n){ for ($i = $n; $i >= 0; $i--) { for ($j = $n; $j > $n - $i; $j--) { if ($a[$j] > $a[$j - 1]) swap($a[$j], $a[$j - 1]); } } print1($a, $n);} // Driver code$n = 6;$a = array();array_push($a, 2);array_push($a, 4);array_push($a, 3);array_push($a, 2);array_push($a, 4);array_push($a, 5);array_push($a, 3);sort1($a, $n); // This code is contributed by// Manish Shaw(manishshaw1)?> <script> // Bubble sort implementation// to sort elements in// descending order. function print(a,n){ for (let i = 0; i <= n; i++) document.write(a[i] + " "); document.write("<br>");} // Sorts a[] in descending// order using bubble sort.function sort(a,n){ for (let i = n; i >= 0; i--) for (let j = n; j > n - i; j--) if (a[j] > a[j-1]){ let tempswap = a[j]; a[j] = a[j - 1]; a[j - 1] = tempswap; } print(a, n); } // Driver codelet n = 6;let a=[];a.push(2);a.push(4);a.push(3);a.push(2);a.push(4);a.push(5);a.push(3);sort(a, n); // This code is contributed by avanitrachhadiya2155 </script> Output: 5 4 4 3 3 2 2 Method 2 (Using library function) We can use stable_sort to sort elements in stable manner. C++ Java Python 3 C# Javascript // C++ program to demonstrate descending order// stable sort using greater<>().#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); stable_sort(arr, arr + n, greater<int>()); cout << "Array after sorting : \n"; for (int i = 0; i < n; ++i) cout << arr[i] << " "; return 0;} // Java program to demonstrate descending order// stable sort using greater<>().import java.util.*; class GFG{ static void reverse(int a[]) { int i, k, n = a.length; int t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void main(String[] args) { int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; int n = arr.length; Arrays.sort(arr); reverse(arr); System.out.println("Array after sorting : \n"); for (int i = 0; i < n; ++i) { System.out.print(arr[i] + " "); } }} // This code has been contributed by 29AjayKumar # Python 3 program to demonstrate# descending order if __name__ == "__main__": arr = [ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ] n = len(arr) arr.sort(reverse = True) print("Array after sorting : ") for i in range(n): print(arr[i], end = " ") # This code is contributed by ita_c // C# program to demonstrate descending orderusing System; class GFG{ static void reverse(int []a) { int i, k, n = a.Length; int t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void Main(String[] args) { int []arr = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; int n = arr.Length; Array.Sort(arr); reverse(arr); Console.WriteLine("Array after sorting : \n"); for (int i = 0; i < n; ++i) { Console.Write(arr[i] + " "); } }} // This code is contributed by 29AjayKumar <script>// javascript program to demonstrate descending order function reverse(a) { var i, k, n = a.length; var t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code var arr = [ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ] ; var n = arr.length; arr.sort(); reverse(arr); document.write("Array after sorting : " + "<br>"); for (var i = 0; i < n; ++i) { document.write(arr[i] + " "); } // This code is contributed by bunnyram19. </script> Output: Array after sorting : 9 8 7 6 5 4 3 2 1 0 manishshaw1 ukasp 29AjayKumar bunnyram19 avanitrachhadiya2155 anikakapoor Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Sep, 2021" }, { "code": null, "e": 184, "s": 53, "text": "Given an array of n integers, we have to reverse sort the array elements such the equal keys are stable after sorting. Examples: " }, { "code": null, "e": 239, "s": 184, "text": "Input : arr[] = {4, 2, 3, 2, 4}\nOutput : 4, 4, 3, 2, 2" }, { "code": null, "e": 1205, "s": 241, "text": "Prerequisite : Stability in sorting algorithmsMethod 1 (Writing our own sorting function : Bubble Sort)We know sorting algorithms like Bubble Sort, Insertion Sort, Merge Sort, Count Sort are stable. We implement here Bubble Sort.Explanation First Pass (4′, 2′, 3, 2′′, 4′′) -> (2′, 4′, 3, 4′′, 2′′) Here algorithm compares last two element and swaps since 2′′ < 4′′. (2′, 4′, 3, 4′′, 2′′) -> (2′, 4′, 4′′, 3, 2′′) swap since 3 < 4′′ (2′, 4′, 4′′, 3, 2′′) -> (2′, 4′, 4′′, 3, 2′′) (2′, 4′, 4′′, 3, 2′′) -> (4′, 2′, 4′′, 3, 2′′) swap since 2′ < 4′.Second Pass: (4′, 2′, 4′′, 3, 2′′) -> (4′, 2′, 4′′, 3, 2′′) (4′, 2′, 4′′, 3, 2′′) -> (4′, 2′, 4′′, 3, 2′′) (4′, 2′, 4′′, 3, 2′′) -> (4′, 4′′, 2′, 3, 2′′) swap since 2′ (4′, 4′′, 2′, 3, 2′′)Third Pass: (4′, 4′′, 2′, 3, 2′′) -> (4′, 4′′, 2′, 3, 2′′) (4′, 4′′, 2′, 3, 2′′) -> (4′, 4′′, 3, 2′, 2′′) swap since 2′<3 Now, the array is in sorted order and same elements are in same order as they were in the original array. " }, { "code": null, "e": 1209, "s": 1205, "text": "C++" }, { "code": null, "e": 1214, "s": 1209, "text": "Java" }, { "code": null, "e": 1222, "s": 1214, "text": "Python3" }, { "code": null, "e": 1225, "s": 1222, "text": "C#" }, { "code": null, "e": 1229, "s": 1225, "text": "PHP" }, { "code": null, "e": 1240, "s": 1229, "text": "Javascript" }, { "code": "// Bubble sort implementation to sort// elements in descending order.#include <iostream>#include <vector>using namespace std; void print(vector<int> a, int n){ for (int i = 0; i <= n; i++) cout << a[i] << \" \"; cout << endl;} // Sorts a[] in descending order using// bubble sort.void sort(vector<int> a, int n){ for (int i = n; i >= 0; i--) for (int j = n; j > n - i; j--) if (a[j] > a[j - 1]) swap(a[j], a[j-1]); print(a, n);} // Driver codeint main(){ int n = 7; vector<int> a; a.push_back(2); a.push_back(4); a.push_back(3); a.push_back(2); a.push_back(4); a.push_back(5); a.push_back(3); sort(a, n - 1); return 0;}", "e": 1946, "s": 1240, "text": null }, { "code": "// Bubble sort implementation// to sort elements in// descending order.import java.io.*;import java.util.*; class GFG{static void print(ArrayList<Integer> a, int n){ for (int i = 0; i <= n; i++) System.out.print(a.get(i) + \" \"); System.out.println();} // Sorts a[] in descending// order using bubble sort.static void sort(ArrayList<Integer> a, int n){ for (int i = n; i >= 0; i--) for (int j = n; j > n - i; j--) if (a.get(j) > a.get(j - 1)) { int tempswap = a.get(j); a.remove(j); a.add(j, a.get(j - 1)); a.remove(j - 1); a.add(j - 1, tempswap); } print(a, n);} // Driver codepublic static void main(String[] args){ int n = 6; ArrayList<Integer> a = new ArrayList<Integer>(); a.add(2); a.add(4); a.add(3); a.add(2); a.add(4); a.add(5); a.add(3); sort(a, n);}} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 3020, "s": 1946, "text": null }, { "code": "# Bubble sort implementation to sort# elements in descending order. def print1(a, n): for i in range(0,n+1): print(a[i],end=\" \") print(\"\") # Sorts a[] in descending order using# bubble sort.def sort(a, n): for i in range(n,0,-1): for j in range(n, n - i,-1): if (a[j] > a[j - 1]): a[j], a[j-1]=a[j-1], a[j] print1(a,n) # Driver coden = 7a = [2,4,3,2,4,5,3] sort(a, n-1) # This code is contributed# by Smitha Dinesh Semwal", "e": 3498, "s": 3020, "text": null }, { "code": "// Bubble sort implementation// to sort elements in// descending order.using System;using System.Collections.Generic; class GFG{static void print(List<int> a, int n){ for (int i = 0; i <= n; i++) Console.Write(a[i] + \" \"); Console.WriteLine();} // Sorts a[] in descending// order using bubble sort.static void sort(List<int> a, int n){ for (int i = n; i >= 0; i--) for (int j = n; j > n - i; j--) if (a[j] > a[j - 1]) { int tempswap = a[j]; a[j] = a[j - 1]; a[j - 1] = tempswap; } print(a, n);} // Driver codestatic void Main(){ int n = 6; List<int> a = new List<int>(); a.Add(2); a.Add(4); a.Add(3); a.Add(2); a.Add(4); a.Add(5); a.Add(3); sort(a, n);}} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 4416, "s": 3498, "text": null }, { "code": "<?php// Bubble sort implementation// to sort elements in// descending order. function swap(&$x, &$y){ $x ^= $y ^= $x ^= $y;} function print1($a, $n){ for ($i = 0; $i <= $n; $i++) echo ($a[$i] . \" \"); echo (\"\\n\");} // Sorts a[] in descending// order using bubble sort.function sort1($a, $n){ for ($i = $n; $i >= 0; $i--) { for ($j = $n; $j > $n - $i; $j--) { if ($a[$j] > $a[$j - 1]) swap($a[$j], $a[$j - 1]); } } print1($a, $n);} // Driver code$n = 6;$a = array();array_push($a, 2);array_push($a, 4);array_push($a, 3);array_push($a, 2);array_push($a, 4);array_push($a, 5);array_push($a, 3);sort1($a, $n); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 5196, "s": 4416, "text": null }, { "code": "<script> // Bubble sort implementation// to sort elements in// descending order. function print(a,n){ for (let i = 0; i <= n; i++) document.write(a[i] + \" \"); document.write(\"<br>\");} // Sorts a[] in descending// order using bubble sort.function sort(a,n){ for (let i = n; i >= 0; i--) for (let j = n; j > n - i; j--) if (a[j] > a[j-1]){ let tempswap = a[j]; a[j] = a[j - 1]; a[j - 1] = tempswap; } print(a, n); } // Driver codelet n = 6;let a=[];a.push(2);a.push(4);a.push(3);a.push(2);a.push(4);a.push(5);a.push(3);sort(a, n); // This code is contributed by avanitrachhadiya2155 </script>", "e": 5936, "s": 5196, "text": null }, { "code": null, "e": 5946, "s": 5936, "text": "Output: " }, { "code": null, "e": 5960, "s": 5946, "text": "5 4 4 3 3 2 2" }, { "code": null, "e": 6053, "s": 5960, "text": "Method 2 (Using library function) We can use stable_sort to sort elements in stable manner. " }, { "code": null, "e": 6057, "s": 6053, "text": "C++" }, { "code": null, "e": 6062, "s": 6057, "text": "Java" }, { "code": null, "e": 6071, "s": 6062, "text": "Python 3" }, { "code": null, "e": 6074, "s": 6071, "text": "C#" }, { "code": null, "e": 6085, "s": 6074, "text": "Javascript" }, { "code": "// C++ program to demonstrate descending order// stable sort using greater<>().#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); stable_sort(arr, arr + n, greater<int>()); cout << \"Array after sorting : \\n\"; for (int i = 0; i < n; ++i) cout << arr[i] << \" \"; return 0;}", "e": 6474, "s": 6085, "text": null }, { "code": "// Java program to demonstrate descending order// stable sort using greater<>().import java.util.*; class GFG{ static void reverse(int a[]) { int i, k, n = a.length; int t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void main(String[] args) { int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; int n = arr.length; Arrays.sort(arr); reverse(arr); System.out.println(\"Array after sorting : \\n\"); for (int i = 0; i < n; ++i) { System.out.print(arr[i] + \" \"); } }} // This code has been contributed by 29AjayKumar", "e": 7209, "s": 6474, "text": null }, { "code": "# Python 3 program to demonstrate# descending order if __name__ == \"__main__\": arr = [ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ] n = len(arr) arr.sort(reverse = True) print(\"Array after sorting : \") for i in range(n): print(arr[i], end = \" \") # This code is contributed by ita_c", "e": 7517, "s": 7209, "text": null }, { "code": "// C# program to demonstrate descending orderusing System; class GFG{ static void reverse(int []a) { int i, k, n = a.Length; int t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void Main(String[] args) { int []arr = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; int n = arr.Length; Array.Sort(arr); reverse(arr); Console.WriteLine(\"Array after sorting : \\n\"); for (int i = 0; i < n; ++i) { Console.Write(arr[i] + \" \"); } }} // This code is contributed by 29AjayKumar", "e": 8204, "s": 7517, "text": null }, { "code": "<script>// javascript program to demonstrate descending order function reverse(a) { var i, k, n = a.length; var t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code var arr = [ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ] ; var n = arr.length; arr.sort(); reverse(arr); document.write(\"Array after sorting : \" + \"<br>\"); for (var i = 0; i < n; ++i) { document.write(arr[i] + \" \"); } // This code is contributed by bunnyram19. </script>", "e": 8859, "s": 8204, "text": null }, { "code": null, "e": 8869, "s": 8859, "text": "Output: " }, { "code": null, "e": 8913, "s": 8869, "text": "Array after sorting : \n9 8 7 6 5 4 3 2 1 0 " }, { "code": null, "e": 8927, "s": 8915, "text": "manishshaw1" }, { "code": null, "e": 8933, "s": 8927, "text": "ukasp" }, { "code": null, "e": 8945, "s": 8933, "text": "29AjayKumar" }, { "code": null, "e": 8956, "s": 8945, "text": "bunnyram19" }, { "code": null, "e": 8977, "s": 8956, "text": "avanitrachhadiya2155" }, { "code": null, "e": 8989, "s": 8977, "text": "anikakapoor" }, { "code": null, "e": 8997, "s": 8989, "text": "Sorting" }, { "code": null, "e": 9005, "s": 8997, "text": "Sorting" } ]
How to save an HTML 5 Canvas as an image on the server ?
20 Aug, 2019 Saving HTML canvas as an image is pretty easy, it can be done by just right-clicking on the canvas and save it as an image. But saving canvas as an image on the server is quite different. This article will show you how to achieve that. Sometimes it is required to save canvas image after doing some server processing and this article will help in sending canvas image over the server for processing. Here you will see, how to convert an HTML content into an image using JQuery. We know that there is a plugins html2canvas, by using that plugin we can easily convert the HTML content into image content after that we can save that file by right-clicking and choosing the save image option. After that, we will convert that CANVAS image into the URL format and that to the server by using ajax after that the main part will be done by the PHP code. The PHP code will save that image on your server. Below steps will illustrate the approach clearly. Step 1: HTML code to convert canvas into image. <!DOCTYPE html><html> <head> <title></title> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"> </script> <style> .top { margin-top: 20px; } h1 { color: green; } input { background-color: transparent; border: 0px solid; width: 300; } body { text-align: center; } </style></head> <body> <div class="col-md-offset-4 col-md-4 col--md-offset-4 top"> <div id="createImg" style="border:1px solid;"> <h1>GeeksforGeeks</h1> <h4>How to save an HTML5 Canvas as an image on a server?</h4> <input type="text" value="" placeholder="Enter wahtaever you want" class="form-control" /> <br/> </div> <button id="geeks" type="button" class="btn btn-primary top"> Create Image</button> <div id="img" style="display:none;"> <img src="" id="newimg" class="top" /> </div> </div> <script> $(function() { $("#geeks").click(function() { html2canvas($("#createImg"), { onrendered: function(canvas) { var imgsrc = canvas.toDataURL("image/png"); console.log(imgsrc); $("#newimg").attr('src', imgsrc); $("#img").show(); var dataURL = canvas.toDataURL(); $.ajax({ type: "POST", url: "script.php", data: { imgBase64: dataURL } }).done(function(o) { console.log('saved'); }); } }); }); }); </script></body> </html> Step 2: Display the output to check that the canvas is successfully converted into an image. Before clicking the Button: After clicking the Button: Step 3: Converting the image into URL format using canvas.toDataURL() method. var dataURL = canvas.toDataURL(); Step 4: Sending the converted URL format into your server via Ajax. $.ajax({ type: "POST", url: "script.php", data: { imgBase64: dataURL }}).done(function(o) { console.log('saved'); }); Step 5: This php code will save the image into the server. <?php // Requires php5 define('UPLOAD_DIR', 'images/'); $img = $_POST['imgBase64']; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $file = UPLOAD_DIR . uniqid() . '.png'; $success = file_put_contents($file, $data); print $success ? $file : 'Unable to save the file.'; ?> Picked PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Aug, 2019" }, { "code": null, "e": 428, "s": 28, "text": "Saving HTML canvas as an image is pretty easy, it can be done by just right-clicking on the canvas and save it as an image. But saving canvas as an image on the server is quite different. This article will show you how to achieve that. Sometimes it is required to save canvas image after doing some server processing and this article will help in sending canvas image over the server for processing." }, { "code": null, "e": 717, "s": 428, "text": "Here you will see, how to convert an HTML content into an image using JQuery. We know that there is a plugins html2canvas, by using that plugin we can easily convert the HTML content into image content after that we can save that file by right-clicking and choosing the save image option." }, { "code": null, "e": 925, "s": 717, "text": "After that, we will convert that CANVAS image into the URL format and that to the server by using ajax after that the main part will be done by the PHP code. The PHP code will save that image on your server." }, { "code": null, "e": 975, "s": 925, "text": "Below steps will illustrate the approach clearly." }, { "code": null, "e": 1023, "s": 975, "text": "Step 1: HTML code to convert canvas into image." }, { "code": "<!DOCTYPE html><html> <head> <title></title> <link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js\"> </script> <script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js\"> </script> <style> .top { margin-top: 20px; } h1 { color: green; } input { background-color: transparent; border: 0px solid; width: 300; } body { text-align: center; } </style></head> <body> <div class=\"col-md-offset-4 col-md-4 col--md-offset-4 top\"> <div id=\"createImg\" style=\"border:1px solid;\"> <h1>GeeksforGeeks</h1> <h4>How to save an HTML5 Canvas as an image on a server?</h4> <input type=\"text\" value=\"\" placeholder=\"Enter wahtaever you want\" class=\"form-control\" /> <br/> </div> <button id=\"geeks\" type=\"button\" class=\"btn btn-primary top\"> Create Image</button> <div id=\"img\" style=\"display:none;\"> <img src=\"\" id=\"newimg\" class=\"top\" /> </div> </div> <script> $(function() { $(\"#geeks\").click(function() { html2canvas($(\"#createImg\"), { onrendered: function(canvas) { var imgsrc = canvas.toDataURL(\"image/png\"); console.log(imgsrc); $(\"#newimg\").attr('src', imgsrc); $(\"#img\").show(); var dataURL = canvas.toDataURL(); $.ajax({ type: \"POST\", url: \"script.php\", data: { imgBase64: dataURL } }).done(function(o) { console.log('saved'); }); } }); }); }); </script></body> </html>", "e": 3346, "s": 1023, "text": null }, { "code": null, "e": 3439, "s": 3346, "text": "Step 2: Display the output to check that the canvas is successfully converted into an image." }, { "code": null, "e": 3467, "s": 3439, "text": "Before clicking the Button:" }, { "code": null, "e": 3494, "s": 3467, "text": "After clicking the Button:" }, { "code": null, "e": 3572, "s": 3494, "text": "Step 3: Converting the image into URL format using canvas.toDataURL() method." }, { "code": "var dataURL = canvas.toDataURL();", "e": 3606, "s": 3572, "text": null }, { "code": null, "e": 3674, "s": 3606, "text": "Step 4: Sending the converted URL format into your server via Ajax." }, { "code": "$.ajax({ type: \"POST\", url: \"script.php\", data: { imgBase64: dataURL }}).done(function(o) { console.log('saved'); });", "e": 3815, "s": 3674, "text": null }, { "code": null, "e": 3874, "s": 3815, "text": "Step 5: This php code will save the image into the server." }, { "code": "<?php // Requires php5 define('UPLOAD_DIR', 'images/'); $img = $_POST['imgBase64']; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $file = UPLOAD_DIR . uniqid() . '.png'; $success = file_put_contents($file, $data); print $success ? $file : 'Unable to save the file.'; ?> ", "e": 4235, "s": 3874, "text": null }, { "code": null, "e": 4242, "s": 4235, "text": "Picked" }, { "code": null, "e": 4246, "s": 4242, "text": "PHP" }, { "code": null, "e": 4263, "s": 4246, "text": "Web Technologies" }, { "code": null, "e": 4290, "s": 4263, "text": "Web technologies Questions" }, { "code": null, "e": 4294, "s": 4290, "text": "PHP" } ]
De Bruijn sequence | Set 1
10 Jul, 2021 Given an integer n and a set of characters A of size k, find a string S such that every possible string on A of length n appears exactly once as a substring in S. Such a string is called de Bruijn sequence. Examples: Input: n = 3, k = 2, A = {0, 1) Output: 0011101000 All possible strings of length three (000, 001, 010, 011, 100, 101, 110 and 111) appear exactly once as sub-strings in A. Input: n = 2, k = 2, A = {0, 1) Output: 01100 Approach: We can solve this problem by constructing a directed graph with kn-1 nodes with each node having k outgoing edges. Each node corresponds to a string of size n-1. Every edge corresponds to one of the k characters in A and adds that character to the starting string. For example, if n=3 and k=2, then we construct the following graph: The node ’01’ is connected to node ’11’ through edge ‘1’, as adding ‘1’ to ’01’ (and removing the first character) gives us ’11’. We can observe that every node in this graph has equal in-degree and out-degree, which means that a Eulerian circuit exists in this graph. The Eulerian circuit will correspond to a de Bruijn sequence as every combination of a node and an outgoing edge represents a unique string of length n. The de Bruijn sequence will contain the characters of the starting node and the characters of all the edges in the order they are traversed in. Therefore the length of the string will be kn+n-1. We will use Hierholzer’s Algorithm to find the Eulerian circuit. The time complexity of this approach is O(kn). Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; unordered_set<string> seen;vector<int> edges; // Modified DFS in which no edge// is traversed twicevoid dfs(string node, int& k, string& A){ for (int i = 0; i < k; ++i) { string str = node + A[i]; if (seen.find(str) == seen.end()) { seen.insert(str); dfs(str.substr(1), k, A); edges.push_back(i); } }} // Function to find a de Bruijn sequence// of order n on k charactersstring deBruijn(int n, int k, string A){ // Clearing global variables seen.clear(); edges.clear(); string startingNode = string(n - 1, A[0]); dfs(startingNode, k, A); string S; // Number of edges int l = pow(k, n); for (int i = 0; i < l; ++i) S += A[edges[i]]; S += startingNode; return S;} // Driver codeint main(){ int n = 3, k = 2; string A = "01"; cout << deBruijn(n, k, A); return 0;} // Java implementation of// the above approachimport java.util.*; class GFG{ static Set<String> seen = new HashSet<String>(); static Vector<Integer> edges = new Vector<Integer>(); // Modified DFS in which no edge // is traversed twice static void dfs(String node, int k, String A) { for (int i = 0; i < k; ++i) { String str = node + A.charAt(i); if (!seen.contains(str)) { seen.add(str); dfs(str.substring(1), k, A); edges.add(i); } } } // Function to find a de Bruijn sequence // of order n on k characters static String deBruijn(int n, int k, String A) { // Clearing global variables seen.clear(); edges.clear(); String startingNode = string(n - 1, A.charAt(0)); dfs(startingNode, k, A); String S = ""; // Number of edges int l = (int) Math.pow(k, n); for (int i = 0; i < l; ++i) S += A.charAt(edges.get(i)); S += startingNode; return S; } private static String string(int n, char charAt) { String str = ""; for (int i = 0; i < n; i++) str += charAt; return str; } // Driver code public static void main(String[] args) { int n = 3, k = 2; String A = "01"; System.out.print(deBruijn(n, k, A)); }} // This code is contributed by 29AjayKumar # Python3 implementation of# the above approachimport math seen = set()edges = [] # Modified DFS in which no edge# is traversed twicedef dfs( node, k, A): for i in range(k): str = node + A[i] if (str not in seen): seen.add(str) dfs(str[1:], k, A) edges.append(i) # Function to find a de Bruijn sequence# of order n on k charactersdef deBruijn(n, k, A): # Clearing global variables seen.clear() edges.clear() startingNode = A[0] * (n - 1) dfs(startingNode, k, A) S = "" # Number of edges l = int(math.pow(k, n)) for i in range(l): S += A[edges[i]] S += startingNode return S # Driver coden = 3k = 2A = "01" print(deBruijn(n, k, A)) # This code is contributed by shubhamsingh10 // C# implementation of// the above approachusing System;using System.Collections.Generic; class GFG{ static HashSet<String> seen = new HashSet<String>(); static List<int> edges = new List<int>(); // Modified DFS in which no edge // is traversed twice static void dfs(String node, int k, String A) { for (int i = 0; i < k; ++i) { String str = node + A[i]; if (!seen.Contains(str)) { seen.Add(str); dfs(str.Substring(1), k, A); edges.Add(i); } } } // Function to find a de Bruijn sequence // of order n on k characters static String deBruijn(int n, int k, String A) { // Clearing global variables seen.Clear(); edges.Clear(); String startingNode = strings(n - 1, A[0]); dfs(startingNode, k, A); String S = ""; // Number of edges int l = (int) Math.Pow(k, n); for (int i = 0; i < l; ++i) S += A[edges[i]]; S += startingNode; return S; } private static String strings(int n, char charAt) { String str = ""; for (int i = 0; i < n; i++) str += charAt; return str; } // Driver code public static void Main(String[] args) { int n = 3, k = 2; String A = "01"; Console.Write(deBruijn(n, k, A)); }} // This code is contributed by 29AjayKumar <script> // Javascript implementation of// the above approachvar seen = new Set();var edges = []; // Modified DFS in which no edge// is traversed twicefunction dfs(node, k, A){ for (var i = 0; i < k; ++i) { var str = node + A[i]; if (!seen.has(str)) { seen.add(str); dfs(str.substring(1), k, A); edges.push(i); } }} // Function to find a de Bruijn sequence// of order n on k charactersfunction deBruijn(n, k, A){ // Clearing global variables seen = new Set(); edges = []; var startingNode = A[0].repeat(n-1); dfs(startingNode, k, A); var S = ""; // Number of edges var l = Math.pow(k, n); for (var i = 0; i < l; ++i) S += A[edges[i]]; S += startingNode; return S;}function strings(n, charAt){ var str = ""; for (var i = 0; i < n; i++) str += charAt; return str;} // Driver codevar n = 3, k = 2;var A = "01";document.write(deBruijn(n, k, A)); // This code is contributed by rrrtnx.</script> 0011101000 29AjayKumar rrrtnx SHUBHAMSINGH10 DFS Euler-Circuit Technical Scripter 2018 Graph Strings Technical Scripter Strings DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in a directed graph Find if there is a path between two vertices in an undirected graph Introduction to Data Structures What is Data Structure: Types, Classifications and Applications K Centers Problem | Set 1 (Greedy Approximate Algorithm) Write a program to reverse an array or string Reverse a string in Java C++ Data Types Write a program to print all permutations of a given string Python program to check if a string is palindrome or not
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jul, 2021" }, { "code": null, "e": 261, "s": 54, "text": "Given an integer n and a set of characters A of size k, find a string S such that every possible string on A of length n appears exactly once as a substring in S. Such a string is called de Bruijn sequence." }, { "code": null, "e": 272, "s": 261, "text": "Examples: " }, { "code": null, "e": 445, "s": 272, "text": "Input: n = 3, k = 2, A = {0, 1) Output: 0011101000 All possible strings of length three (000, 001, 010, 011, 100, 101, 110 and 111) appear exactly once as sub-strings in A." }, { "code": null, "e": 493, "s": 445, "text": "Input: n = 2, k = 2, A = {0, 1) Output: 01100 " }, { "code": null, "e": 769, "s": 493, "text": "Approach: We can solve this problem by constructing a directed graph with kn-1 nodes with each node having k outgoing edges. Each node corresponds to a string of size n-1. Every edge corresponds to one of the k characters in A and adds that character to the starting string. " }, { "code": null, "e": 838, "s": 769, "text": "For example, if n=3 and k=2, then we construct the following graph: " }, { "code": null, "e": 968, "s": 838, "text": "The node ’01’ is connected to node ’11’ through edge ‘1’, as adding ‘1’ to ’01’ (and removing the first character) gives us ’11’." }, { "code": null, "e": 1107, "s": 968, "text": "We can observe that every node in this graph has equal in-degree and out-degree, which means that a Eulerian circuit exists in this graph." }, { "code": null, "e": 1260, "s": 1107, "text": "The Eulerian circuit will correspond to a de Bruijn sequence as every combination of a node and an outgoing edge represents a unique string of length n." }, { "code": null, "e": 1404, "s": 1260, "text": "The de Bruijn sequence will contain the characters of the starting node and the characters of all the edges in the order they are traversed in." }, { "code": null, "e": 1567, "s": 1404, "text": "Therefore the length of the string will be kn+n-1. We will use Hierholzer’s Algorithm to find the Eulerian circuit. The time complexity of this approach is O(kn)." }, { "code": null, "e": 1620, "s": 1567, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1624, "s": 1620, "text": "C++" }, { "code": null, "e": 1629, "s": 1624, "text": "Java" }, { "code": null, "e": 1637, "s": 1629, "text": "Python3" }, { "code": null, "e": 1640, "s": 1637, "text": "C#" }, { "code": null, "e": 1651, "s": 1640, "text": "Javascript" }, { "code": "// C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; unordered_set<string> seen;vector<int> edges; // Modified DFS in which no edge// is traversed twicevoid dfs(string node, int& k, string& A){ for (int i = 0; i < k; ++i) { string str = node + A[i]; if (seen.find(str) == seen.end()) { seen.insert(str); dfs(str.substr(1), k, A); edges.push_back(i); } }} // Function to find a de Bruijn sequence// of order n on k charactersstring deBruijn(int n, int k, string A){ // Clearing global variables seen.clear(); edges.clear(); string startingNode = string(n - 1, A[0]); dfs(startingNode, k, A); string S; // Number of edges int l = pow(k, n); for (int i = 0; i < l; ++i) S += A[edges[i]]; S += startingNode; return S;} // Driver codeint main(){ int n = 3, k = 2; string A = \"01\"; cout << deBruijn(n, k, A); return 0;}", "e": 2621, "s": 1651, "text": null }, { "code": "// Java implementation of// the above approachimport java.util.*; class GFG{ static Set<String> seen = new HashSet<String>(); static Vector<Integer> edges = new Vector<Integer>(); // Modified DFS in which no edge // is traversed twice static void dfs(String node, int k, String A) { for (int i = 0; i < k; ++i) { String str = node + A.charAt(i); if (!seen.contains(str)) { seen.add(str); dfs(str.substring(1), k, A); edges.add(i); } } } // Function to find a de Bruijn sequence // of order n on k characters static String deBruijn(int n, int k, String A) { // Clearing global variables seen.clear(); edges.clear(); String startingNode = string(n - 1, A.charAt(0)); dfs(startingNode, k, A); String S = \"\"; // Number of edges int l = (int) Math.pow(k, n); for (int i = 0; i < l; ++i) S += A.charAt(edges.get(i)); S += startingNode; return S; } private static String string(int n, char charAt) { String str = \"\"; for (int i = 0; i < n; i++) str += charAt; return str; } // Driver code public static void main(String[] args) { int n = 3, k = 2; String A = \"01\"; System.out.print(deBruijn(n, k, A)); }} // This code is contributed by 29AjayKumar", "e": 4081, "s": 2621, "text": null }, { "code": "# Python3 implementation of# the above approachimport math seen = set()edges = [] # Modified DFS in which no edge# is traversed twicedef dfs( node, k, A): for i in range(k): str = node + A[i] if (str not in seen): seen.add(str) dfs(str[1:], k, A) edges.append(i) # Function to find a de Bruijn sequence# of order n on k charactersdef deBruijn(n, k, A): # Clearing global variables seen.clear() edges.clear() startingNode = A[0] * (n - 1) dfs(startingNode, k, A) S = \"\" # Number of edges l = int(math.pow(k, n)) for i in range(l): S += A[edges[i]] S += startingNode return S # Driver coden = 3k = 2A = \"01\" print(deBruijn(n, k, A)) # This code is contributed by shubhamsingh10", "e": 4881, "s": 4081, "text": null }, { "code": "// C# implementation of// the above approachusing System;using System.Collections.Generic; class GFG{ static HashSet<String> seen = new HashSet<String>(); static List<int> edges = new List<int>(); // Modified DFS in which no edge // is traversed twice static void dfs(String node, int k, String A) { for (int i = 0; i < k; ++i) { String str = node + A[i]; if (!seen.Contains(str)) { seen.Add(str); dfs(str.Substring(1), k, A); edges.Add(i); } } } // Function to find a de Bruijn sequence // of order n on k characters static String deBruijn(int n, int k, String A) { // Clearing global variables seen.Clear(); edges.Clear(); String startingNode = strings(n - 1, A[0]); dfs(startingNode, k, A); String S = \"\"; // Number of edges int l = (int) Math.Pow(k, n); for (int i = 0; i < l; ++i) S += A[edges[i]]; S += startingNode; return S; } private static String strings(int n, char charAt) { String str = \"\"; for (int i = 0; i < n; i++) str += charAt; return str; } // Driver code public static void Main(String[] args) { int n = 3, k = 2; String A = \"01\"; Console.Write(deBruijn(n, k, A)); }} // This code is contributed by 29AjayKumar", "e": 6332, "s": 4881, "text": null }, { "code": "<script> // Javascript implementation of// the above approachvar seen = new Set();var edges = []; // Modified DFS in which no edge// is traversed twicefunction dfs(node, k, A){ for (var i = 0; i < k; ++i) { var str = node + A[i]; if (!seen.has(str)) { seen.add(str); dfs(str.substring(1), k, A); edges.push(i); } }} // Function to find a de Bruijn sequence// of order n on k charactersfunction deBruijn(n, k, A){ // Clearing global variables seen = new Set(); edges = []; var startingNode = A[0].repeat(n-1); dfs(startingNode, k, A); var S = \"\"; // Number of edges var l = Math.pow(k, n); for (var i = 0; i < l; ++i) S += A[edges[i]]; S += startingNode; return S;}function strings(n, charAt){ var str = \"\"; for (var i = 0; i < n; i++) str += charAt; return str;} // Driver codevar n = 3, k = 2;var A = \"01\";document.write(deBruijn(n, k, A)); // This code is contributed by rrrtnx.</script>", "e": 7354, "s": 6332, "text": null }, { "code": null, "e": 7365, "s": 7354, "text": "0011101000" }, { "code": null, "e": 7379, "s": 7367, "text": "29AjayKumar" }, { "code": null, "e": 7386, "s": 7379, "text": "rrrtnx" }, { "code": null, "e": 7401, "s": 7386, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 7405, "s": 7401, "text": "DFS" }, { "code": null, "e": 7419, "s": 7405, "text": "Euler-Circuit" }, { "code": null, "e": 7443, "s": 7419, "text": "Technical Scripter 2018" }, { "code": null, "e": 7449, "s": 7443, "text": "Graph" }, { "code": null, "e": 7457, "s": 7449, "text": "Strings" }, { "code": null, "e": 7476, "s": 7457, "text": "Technical Scripter" }, { "code": null, "e": 7484, "s": 7476, "text": "Strings" }, { "code": null, "e": 7488, "s": 7484, "text": "DFS" }, { "code": null, "e": 7494, "s": 7488, "text": "Graph" }, { "code": null, "e": 7592, "s": 7494, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7657, "s": 7592, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 7725, "s": 7657, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 7757, "s": 7725, "text": "Introduction to Data Structures" }, { "code": null, "e": 7821, "s": 7757, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7878, "s": 7821, "text": "K Centers Problem | Set 1 (Greedy Approximate Algorithm)" }, { "code": null, "e": 7924, "s": 7878, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 7949, "s": 7924, "text": "Reverse a string in Java" }, { "code": null, "e": 7964, "s": 7949, "text": "C++ Data Types" }, { "code": null, "e": 8024, "s": 7964, "text": "Write a program to print all permutations of a given string" } ]
How to use text as background using CSS ?
22 Apr, 2020 There are some website designs that require using text as the background. This can be easily achieved with CSS by using the following methods. Using absolutely positioned element inside relatively positioned element: The absolutely positioned element inside a relative positioned element with absolute element having lower z-index value gives text appears as the background.Example:<!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .container { position: relative; } .containerbackground { margin: 3rem; position: absolute; top: 0; left: 0; bottom: 0; z-index: -1; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: #c6afaf; } </style></head> <body> <div class="container"> <div class="containerbackground"> Background Text </div> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html>Output: Example: <!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .container { position: relative; } .containerbackground { margin: 3rem; position: absolute; top: 0; left: 0; bottom: 0; z-index: -1; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: #c6afaf; } </style></head> <body> <div class="container"> <div class="containerbackground"> Background Text </div> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html> Output: Using :after pseudo elements: Using :after pseudo elements with :after pseudo elements having lower z-index value make it to appear as background. Use text inside :after pseudo element to make appear text as the background.Example:<!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .bgtext { position: relative; } .bgtext:after { margin: 3rem; content: "Background text"; position: absolute; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: rgb(187, 182, 182); top: 0; left: 0; z-index: -1; } </style></head> <body> <div class="bgtext"> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html>Output: Example: <!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .bgtext { position: relative; } .bgtext:after { margin: 3rem; content: "Background text"; position: absolute; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: rgb(187, 182, 182); top: 0; left: 0; z-index: -1; } </style></head> <body> <div class="bgtext"> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html> Output: Using :before pseudo elements: Using :before pseudo elements with :before pseudo elements having lower z-index value make it to appear as background. Use text inside :before pseudo element to make appear text as the background.Example:<!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .bgtext { position: relative; } .bgtext:before { margin: 3rem; content: "Background text"; position: absolute; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: rgb(187, 182, 182); top: 0; left: 0; z-index: -1; } </style></head> <body> <div class="bgtext"> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html> Output : Example: <!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .bgtext { position: relative; } .bgtext:before { margin: 3rem; content: "Background text"; position: absolute; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: rgb(187, 182, 182); top: 0; left: 0; z-index: -1; } </style></head> <body> <div class="bgtext"> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html> Output : CSS-Misc HTML-Misc Picked CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 171, "s": 28, "text": "There are some website designs that require using text as the background. This can be easily achieved with CSS by using the following methods." }, { "code": null, "e": 1137, "s": 171, "text": "Using absolutely positioned element inside relatively positioned element: The absolutely positioned element inside a relative positioned element with absolute element having lower z-index value gives text appears as the background.Example:<!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .container { position: relative; } .containerbackground { margin: 3rem; position: absolute; top: 0; left: 0; bottom: 0; z-index: -1; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: #c6afaf; } </style></head> <body> <div class=\"container\"> <div class=\"containerbackground\"> Background Text </div> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html>Output:" }, { "code": null, "e": 1146, "s": 1137, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .container { position: relative; } .containerbackground { margin: 3rem; position: absolute; top: 0; left: 0; bottom: 0; z-index: -1; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: #c6afaf; } </style></head> <body> <div class=\"container\"> <div class=\"containerbackground\"> Background Text </div> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html>", "e": 1866, "s": 1146, "text": null }, { "code": null, "e": 1874, "s": 1866, "text": "Output:" }, { "code": null, "e": 2765, "s": 1874, "text": "Using :after pseudo elements: Using :after pseudo elements with :after pseudo elements having lower z-index value make it to appear as background. Use text inside :after pseudo element to make appear text as the background.Example:<!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .bgtext { position: relative; } .bgtext:after { margin: 3rem; content: \"Background text\"; position: absolute; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: rgb(187, 182, 182); top: 0; left: 0; z-index: -1; } </style></head> <body> <div class=\"bgtext\"> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html>Output:" }, { "code": null, "e": 2774, "s": 2765, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .bgtext { position: relative; } .bgtext:after { margin: 3rem; content: \"Background text\"; position: absolute; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: rgb(187, 182, 182); top: 0; left: 0; z-index: -1; } </style></head> <body> <div class=\"bgtext\"> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html>", "e": 3427, "s": 2774, "text": null }, { "code": null, "e": 3435, "s": 3427, "text": "Output:" }, { "code": null, "e": 4339, "s": 3435, "text": "Using :before pseudo elements: Using :before pseudo elements with :before pseudo elements having lower z-index value make it to appear as background. Use text inside :before pseudo element to make appear text as the background.Example:<!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .bgtext { position: relative; } .bgtext:before { margin: 3rem; content: \"Background text\"; position: absolute; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: rgb(187, 182, 182); top: 0; left: 0; z-index: -1; } </style></head> <body> <div class=\"bgtext\"> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html> Output :" }, { "code": null, "e": 4348, "s": 4339, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Using text as background with CSS </title> <style> .bgtext { position: relative; } .bgtext:before { margin: 3rem; content: \"Background text\"; position: absolute; transform: rotate(300deg); -webkit-transform: rotate(300deg); color: rgb(187, 182, 182); top: 0; left: 0; z-index: -1; } </style></head> <body> <div class=\"bgtext\"> <p>Foreground text</p> <p>Welcome to GeeksforGeeks</p> <p>Start Learning</p> </div></body> </html> ", "e": 5009, "s": 4348, "text": null }, { "code": null, "e": 5018, "s": 5009, "text": "Output :" }, { "code": null, "e": 5027, "s": 5018, "text": "CSS-Misc" }, { "code": null, "e": 5037, "s": 5027, "text": "HTML-Misc" }, { "code": null, "e": 5044, "s": 5037, "text": "Picked" }, { "code": null, "e": 5048, "s": 5044, "text": "CSS" }, { "code": null, "e": 5053, "s": 5048, "text": "HTML" }, { "code": null, "e": 5070, "s": 5053, "text": "Web Technologies" }, { "code": null, "e": 5097, "s": 5070, "text": "Web technologies Questions" }, { "code": null, "e": 5102, "s": 5097, "text": "HTML" } ]
How to create frequency table of data.table in R?
If we have an data.table object or a data frame converted to a data.table and it has a factor column then we might want to create a frequency table that shows the number of values each factor has or the count of factor levels. This is a data summarization method which helps us to understand the variation in the occurrences of factor levels. This can be easily done with a single line of code if we have a data.table object, otherwise we first need to convert the object. Consider the below data frame − Live Demo Group<-sample(c("A","B","C","D"),20,replace=TRUE) Frequency<-sample(1:50,20) df1<-data.frame(Group,Frequency) df1 Group Frequency 1 A 11 2 B 19 3 A 41 4 D 24 5 A 22 6 B 26 7 C 46 8 C 4 9 A 45 10 C 44 11 A 50 12 C 20 13 B 27 14 D 12 15 A 34 16 B 6 17 C 35 18 D 32 19 A 42 20 D 30 Loading data.table package and reading the data frame df1 as data.table − library(data.table) df1<-as.data.table(df1) Finding the frequency table of df1 which is a data.table object now − df1[,.N,by=Group] Group N 1: A 7 2: B 4 3: D 4 4: C 5 Let’s have a look at another example − Live Demo Class<-sample(c("1","2","3","4","5"),20,replace=TRUE) Scores<-sample(1:100,20) df2<-data.frame(Class,Scores) df2 Class Scores 1 2 45 2 5 66 3 4 61 4 5 96 5 3 27 6 5 94 7 5 51 8 3 98 9 1 14 10 3 83 11 3 6 12 1 16 13 1 18 14 1 35 15 2 70 16 4 67 17 1 63 18 5 31 19 1 58 20 4 15 df2<-as.data.table(df2) df2[,.N,by=Class] Class N 1: 2 2 2: 5 5 3: 4 3 4: 3 4 5: 1 6
[ { "code": null, "e": 1535, "s": 1062, "text": "If we have an data.table object or a data frame converted to a data.table and it has a factor column then we might want to create a frequency table that shows the number of values each factor has or the count of factor levels. This is a data summarization method which helps us to understand the variation in the occurrences of factor levels. This can be easily done with a single line of code if we have a data.table object, otherwise we first need to convert the object." }, { "code": null, "e": 1567, "s": 1535, "text": "Consider the below data frame −" }, { "code": null, "e": 1578, "s": 1567, "text": " Live Demo" }, { "code": null, "e": 1692, "s": 1578, "text": "Group<-sample(c(\"A\",\"B\",\"C\",\"D\"),20,replace=TRUE)\nFrequency<-sample(1:50,20)\ndf1<-data.frame(Group,Frequency)\ndf1" }, { "code": null, "e": 1947, "s": 1692, "text": " Group Frequency\n1 A 11\n2 B 19\n3 A 41\n4 D 24\n5 A 22\n6 B 26\n7 C 46\n8 C 4\n9 A 45\n10 C 44\n11 A 50\n12 C 20\n13 B 27\n14 D 12\n15 A 34\n16 B 6\n17 C 35\n18 D 32\n19 A 42\n20 D 30" }, { "code": null, "e": 2021, "s": 1947, "text": "Loading data.table package and reading the data frame df1 as data.table −" }, { "code": null, "e": 2065, "s": 2021, "text": "library(data.table)\ndf1<-as.data.table(df1)" }, { "code": null, "e": 2135, "s": 2065, "text": "Finding the frequency table of df1 which is a data.table object now −" }, { "code": null, "e": 2153, "s": 2135, "text": "df1[,.N,by=Group]" }, { "code": null, "e": 2198, "s": 2153, "text": " Group N\n1: A 7\n2: B 4\n3: D 4\n4: C 5" }, { "code": null, "e": 2237, "s": 2198, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2248, "s": 2237, "text": " Live Demo" }, { "code": null, "e": 2361, "s": 2248, "text": "Class<-sample(c(\"1\",\"2\",\"3\",\"4\",\"5\"),20,replace=TRUE)\nScores<-sample(1:100,20)\ndf2<-data.frame(Class,Scores)\ndf2" }, { "code": null, "e": 2594, "s": 2361, "text": " Class Scores\n1 2 45\n2 5 66\n3 4 61\n4 5 96\n5 3 27\n6 5 94\n7 5 51\n8 3 98\n9 1 14\n10 3 83\n11 3 6\n12 1 16\n13 1 18\n14 1 35\n15 2 70\n16 4 67\n17 1 63\n18 5 31\n19 1 58\n20 4 15" }, { "code": null, "e": 2636, "s": 2594, "text": "df2<-as.data.table(df2)\ndf2[,.N,by=Class]" }, { "code": null, "e": 2690, "s": 2636, "text": " Class N\n1: 2 2\n2: 5 5\n3: 4 3\n4: 3 4\n5: 1 6" } ]
Bootstrap .radio-inline class
Use .radio-inline class to a series of radios for controls to appear on the same line. You can try to run the following code to implement the radio-inline class in Bootstrap − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Forms</title> <meta name = "viewport" content = "width=device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <label for = "name">Best Porgraming Language</label> <div> <label class = "radio-inline"> <input type = "radio" name = "optionsRadiosinline" id = "optionsRadios3" value = "option1" checked> Java </label> <label class = "radio-inline"> <input type = "radio" name = "optionsRadiosinline" id = "optionsRadios4" value = "option2"> C </label> <label class = "radio-inline"> <input type = "radio" name = "optionsRadiosinline" id = "optionsRadios4" value = "option3"> C++ </label> </div> </body> </html>
[ { "code": null, "e": 1238, "s": 1062, "text": "Use .radio-inline class to a series of radios for controls to appear on the same line. You can try to run the following code to implement the radio-inline class in Bootstrap −" }, { "code": null, "e": 1248, "s": 1238, "text": "Live Demo" }, { "code": null, "e": 2342, "s": 1248, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Forms</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <label for = \"name\">Best Porgraming Language</label>\n <div>\n <label class = \"radio-inline\">\n <input type = \"radio\" name = \"optionsRadiosinline\" id = \"optionsRadios3\" value = \"option1\" checked> Java\n </label>\n <label class = \"radio-inline\">\n <input type = \"radio\" name = \"optionsRadiosinline\" id = \"optionsRadios4\" value = \"option2\"> C\n </label>\n <label class = \"radio-inline\">\n <input type = \"radio\" name = \"optionsRadiosinline\" id = \"optionsRadios4\" value = \"option3\"> C++\n </label>\n </div>\n </body>\n</html>" } ]
Plotting Geospatial Data using GeoPandas - GeeksforGeeks
16 Jul, 2020 GeoPandas is an open source tool to add support for geographic data to Pandas objects. In this, article we are going to use GeoPandas and Matplotlib for plotting geospatial data. We are going to install GeoPandas, Matplotlib, NumPy and Pandas. pip install geopandas pip install matplotlib pip install numpy pip install pandas Note: If you don’t want to install these modules locally on your computer, use Jupyter Notebook or Google Colab. We are going to import Pandas for the dataframe data structure, NumPy for some mathematical functions, GeoPandas for supporting and handling geospatial data and Matplotlib for actually plotting the maps. import pandas as pd import geopandas as gpd import numpy as np import matplotlib.pyplot as plt GeoPandas gives us some default datasets along with its installation to play around with. Let’s read one of the datasets. Python3 import pandas as pdimport geopandas as gpdimport numpy as npimport matplotlib.pyplot as plt world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))world.head() Output: world.head() Some of the other datasets to play with are ‘naturalearth_cities’ and ‘nybb’. Feel free to experiment with them later. We can use world and plot the same using Matplotlib. Python3 world.plot() Output: World Plot Now, if we see world, we have a lot of fields. One of them is GDP estimate(or gdp_md_est). However, to show how easily data can be filtered in or out in pandas, let’s filter out all continents except Asia. Python3 worldfiltered = world[world.continent == "Asia"]worldfiltered.plot(column ='gdp_md_est', cmap ='Reds') GDP of Countries in Asia cmap property is used to plot the data in the shade specified. The darker shades mean higher value while the lighter shades means lower value. Now, let’s analyse the data for population estimate(pop_est). Python3 world.plot(column ='pop_est') Output: Population Estimate The above image is not very good in conveying the data. So let’s change some properties to make it more comprehensible. First, let’s increase the size of the figure and then set an axis for it. We first plot the world map without any data to on the axis and then we overlay the plot with the data on it with the shade red. This way the map is more clear and dark and makes the data more understandable. However, this map is still a little vague and won’t tell us what the shades mean. Python3 fig, ax = plt.subplots(1, figsize =(16, 8))world.plot(ax = ax, color ='black')world.plot(ax = ax, column ='pop_est', cmap ='Reds') Output: World Population Let’s import the toolkits that allow us to make dividers within the plot. After this we are going to plot the graph as we did before, but this time we are going to add a facecolor. The facecolor property is going to change the background to a color it is set to(in this case, light blue). Now we need to create a divider for creating the color box within the graph, much like dividers in HTML. We are creating a divider and setting its properties like size, justification etc. Then we need to create the color box in the divider we created. So obviously, the highest value in the color box is going to be the highest population in the dataset and the lowest value is going to be zero. Python3 from mpl_toolkits.axes_grid1 import make_axes_locatable fig, ax = plt.subplots(1, figsize =(16, 8), facecolor ='lightblue') world.plot(ax = ax, color ='black')world.plot(ax = ax, column ='pop_est', cmap ='Reds', edgecolors ='grey') # axis for the color bardiv = make_axes_locatable(ax)cax = div.append_axes("right", size ="3 %", pad = 0.05) # color barvmax = world.pop_est.max()mappable = plt.cm.ScalarMappable(cmap ='Reds', norm = plt.Normalize(vmin = 0, vmax = vmax))cbar = fig.colorbar(mappable, cax) ax.axis('off')plt.show() Output: World Population Thus in this article we have seen how we can use GeoPandas to get geospatial data and plot it using Matplotlib. Custom datasets can be used to analyse specific data and city-wise data can also be used. Also, GeoPandas can be used with Open Street Maps, which provides very specific geospatial data(example, streets, hospitals in a city etc., ). The same knowledge can be extended further and can be used for specific statistical and data analysis. Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python
[ { "code": null, "e": 25266, "s": 25238, "text": "\n16 Jul, 2020" }, { "code": null, "e": 25445, "s": 25266, "text": "GeoPandas is an open source tool to add support for geographic data to Pandas objects. In this, article we are going to use GeoPandas and Matplotlib for plotting geospatial data." }, { "code": null, "e": 25510, "s": 25445, "text": "We are going to install GeoPandas, Matplotlib, NumPy and Pandas." }, { "code": null, "e": 25593, "s": 25510, "text": "pip install geopandas\npip install matplotlib\npip install numpy\npip install pandas\n" }, { "code": null, "e": 25706, "s": 25593, "text": "Note: If you don’t want to install these modules locally on your computer, use Jupyter Notebook or Google Colab." }, { "code": null, "e": 25910, "s": 25706, "text": "We are going to import Pandas for the dataframe data structure, NumPy for some mathematical functions, GeoPandas for supporting and handling geospatial data and Matplotlib for actually plotting the maps." }, { "code": null, "e": 26005, "s": 25910, "text": "import pandas as pd\nimport geopandas as gpd\nimport numpy as np\nimport matplotlib.pyplot as plt" }, { "code": null, "e": 26127, "s": 26005, "text": "GeoPandas gives us some default datasets along with its installation to play around with. Let’s read one of the datasets." }, { "code": null, "e": 26135, "s": 26127, "text": "Python3" }, { "code": "import pandas as pdimport geopandas as gpdimport numpy as npimport matplotlib.pyplot as plt world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))world.head()", "e": 26308, "s": 26135, "text": null }, { "code": null, "e": 26316, "s": 26308, "text": "Output:" }, { "code": null, "e": 26329, "s": 26316, "text": "world.head()" }, { "code": null, "e": 26501, "s": 26329, "text": "Some of the other datasets to play with are ‘naturalearth_cities’ and ‘nybb’. Feel free to experiment with them later. We can use world and plot the same using Matplotlib." }, { "code": null, "e": 26509, "s": 26501, "text": "Python3" }, { "code": "world.plot()", "e": 26522, "s": 26509, "text": null }, { "code": null, "e": 26530, "s": 26522, "text": "Output:" }, { "code": null, "e": 26541, "s": 26530, "text": "World Plot" }, { "code": null, "e": 26748, "s": 26541, "text": "Now, if we see world, we have a lot of fields. One of them is GDP estimate(or gdp_md_est). However, to show how easily data can be filtered in or out in pandas, let’s filter out all continents except Asia. " }, { "code": null, "e": 26756, "s": 26748, "text": "Python3" }, { "code": "worldfiltered = world[world.continent == \"Asia\"]worldfiltered.plot(column ='gdp_md_est', cmap ='Reds')", "e": 26859, "s": 26756, "text": null }, { "code": null, "e": 26884, "s": 26859, "text": "GDP of Countries in Asia" }, { "code": null, "e": 27089, "s": 26884, "text": "cmap property is used to plot the data in the shade specified. The darker shades mean higher value while the lighter shades means lower value. Now, let’s analyse the data for population estimate(pop_est)." }, { "code": null, "e": 27097, "s": 27089, "text": "Python3" }, { "code": "world.plot(column ='pop_est')", "e": 27127, "s": 27097, "text": null }, { "code": null, "e": 27135, "s": 27127, "text": "Output:" }, { "code": null, "e": 27155, "s": 27135, "text": "Population Estimate" }, { "code": null, "e": 27640, "s": 27155, "text": "The above image is not very good in conveying the data. So let’s change some properties to make it more comprehensible. First, let’s increase the size of the figure and then set an axis for it. We first plot the world map without any data to on the axis and then we overlay the plot with the data on it with the shade red. This way the map is more clear and dark and makes the data more understandable. However, this map is still a little vague and won’t tell us what the shades mean." }, { "code": null, "e": 27648, "s": 27640, "text": "Python3" }, { "code": "fig, ax = plt.subplots(1, figsize =(16, 8))world.plot(ax = ax, color ='black')world.plot(ax = ax, column ='pop_est', cmap ='Reds')", "e": 27779, "s": 27648, "text": null }, { "code": null, "e": 27787, "s": 27779, "text": "Output:" }, { "code": null, "e": 27805, "s": 27787, "text": "World Population " }, { "code": null, "e": 28283, "s": 27805, "text": "Let’s import the toolkits that allow us to make dividers within the plot. After this we are going to plot the graph as we did before, but this time we are going to add a facecolor. The facecolor property is going to change the background to a color it is set to(in this case, light blue). Now we need to create a divider for creating the color box within the graph, much like dividers in HTML. We are creating a divider and setting its properties like size, justification etc. " }, { "code": null, "e": 28492, "s": 28283, "text": "Then we need to create the color box in the divider we created. So obviously, the highest value in the color box is going to be the highest population in the dataset and the lowest value is going to be zero. " }, { "code": null, "e": 28500, "s": 28492, "text": "Python3" }, { "code": "from mpl_toolkits.axes_grid1 import make_axes_locatable fig, ax = plt.subplots(1, figsize =(16, 8), facecolor ='lightblue') world.plot(ax = ax, color ='black')world.plot(ax = ax, column ='pop_est', cmap ='Reds', edgecolors ='grey') # axis for the color bardiv = make_axes_locatable(ax)cax = div.append_axes(\"right\", size =\"3 %\", pad = 0.05) # color barvmax = world.pop_est.max()mappable = plt.cm.ScalarMappable(cmap ='Reds', norm = plt.Normalize(vmin = 0, vmax = vmax))cbar = fig.colorbar(mappable, cax) ax.axis('off')plt.show()", "e": 29100, "s": 28500, "text": null }, { "code": null, "e": 29108, "s": 29100, "text": "Output:" }, { "code": null, "e": 29125, "s": 29108, "text": "World Population" }, { "code": null, "e": 29574, "s": 29125, "text": "Thus in this article we have seen how we can use GeoPandas to get geospatial data and plot it using Matplotlib. Custom datasets can be used to analyse specific data and city-wise data can also be used. Also, GeoPandas can be used with Open Street Maps, which provides very specific geospatial data(example, streets, hospitals in a city etc., ). The same knowledge can be extended further and can be used for specific statistical and data analysis. " }, { "code": null, "e": 29590, "s": 29574, "text": "Python-projects" }, { "code": null, "e": 29605, "s": 29590, "text": "python-utility" }, { "code": null, "e": 29612, "s": 29605, "text": "Python" }, { "code": null, "e": 29710, "s": 29612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29719, "s": 29710, "text": "Comments" }, { "code": null, "e": 29732, "s": 29719, "text": "Old Comments" }, { "code": null, "e": 29750, "s": 29732, "text": "Python Dictionary" }, { "code": null, "e": 29782, "s": 29750, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29817, "s": 29782, "text": "Read a file line by line in Python" }, { "code": null, "e": 29839, "s": 29817, "text": "Enumerate() in Python" }, { "code": null, "e": 29869, "s": 29839, "text": "Iterate over a list in Python" }, { "code": null, "e": 29911, "s": 29869, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29954, "s": 29911, "text": "Python program to convert a list to string" }, { "code": null, "e": 29991, "s": 29954, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30017, "s": 29991, "text": "Python String | replace()" } ]
Financial Accounting - Subsidiary Books
Cash book is a record of all the transactions related to cash. Examples include: expenses paid in cash, revenue collected in cash, payments made to creditors, payments received from debtors, cash deposited in bank, withdrawn of cash for office use, etc. In double column cash book, a discount column is included on both debit and credit sides to record the discount allowed to customers and the discount received from creditors respectively. In triple column cash book, one more column of bank is included to record all the transactions relating to bank. Note: In modern accounting, simple cash book is the most popular way to record cash transactions. The double column cash book or three column cash book is practically for academic purpose. A separate bank book is used to record all the banking transactions as they are more than cash transactions. These days, cash is used just to meet petty and routine expenditures of an organization. In most of the organizations, the salaries of employees are paid by bank transfer. Note: Cash book always shows debit balance, cash in hand, and a part of current assets. Cash book is just like a ledger account. There is no need to open a separate cash account in the ledger. The balance of cash book is directly posted to the trial balance. Since cash account is a real account, ruling is followed, i.e. what comes in – debit, and what goes out – credit. All the received cash is posted in the debit side and all payments and expenses are posted in the credit side of the cash book. Here, we have an additional Discount column on each side of the cash book. The debit side column of discount represents the discount to debtors of the company and the credit side of discount column means the discount received from our suppliers or creditors while making payments. The total of discount column of debit side of cash book is posted in the ledger account of ‘Discount Allowed to Customers’ account as ‘To Total As Per Cash Book’. Similarly, credit column of cash book is posted in ledger account of ‘Discount Received’ as ‘By total of cash book’. When one more column of Bank is added in both sides of the double column cash book to post all banking transactions, it is called triple column cash book. All banking transactions are routed through this cash book and there is no need to open a separate bank account in ledger. In any organization, there may be many petty transactions incurring for which payments have to be done. Therefore, cash is kept with an employee, who deals with it and makes regular payments out of it. To make it simple and secure, mostly a constant balance is kept with that employee. Suppose cashier pays Rs 5,000 to Mr A, who will pay day-to-day organization expenses out of it. Suppose Mr A spend Rs 4,200 out of it in a day, the main cashier pays Rs 4,200, so his balance of petty cash book will be again Rs 5,000. It is very useful system of accounting, as it saves the time of the main cashier and provides better control. We will soon discuss about ‘Analytical or Columnar Petty Cash Book’ which is most commonly used in most of the organizations. Purchase book is prepared to record all the credit purchases of an organization. Purchase book is not a purchase ledger. The features of a sale book are same as a purchase book, except for the fact that it records all the credit sales. Sometimes goods are to be retuned back to the supplier, for various reasons. The most common reason being defective goods or poor quality goods. In this case, a debit note is issued. The reason of Sale return is same as for purchase return. Sometimes customers return the goods if they don’t meet the quality standards promised. In such cases, a credit note is issued to the customer. Bills are raised by creditors to debtors. The debtors accept them and subsequently return them to the creditors. Bills accepted by debtors are called as ‘Bills Receivables’ in the books of creditors, and ‘Bills Payable’ in the books of debtors. We keep them in our record called ‘Bills Receivable Books’ and ‘Bills Payable Book’. Bills payable issues to the supplier of goods or services for payment, and the record is maintained in this book. There is a difference between a purchase book and a purchase ledger. A purchase book records only credit purchases and a purchase ledger records all the cash purchases in chronical order. The daily balance of purchase book is transferred to purchase ledger. Therefore, purchase ledger is a comprehensive account of all purchases. The same rule applies to sale book and sale ledgers. It is quite clear that maintaining a subsidiary book is facilitation to journal entries, practically it is not possible to post each and every transaction through journal entries, especially in big organizations because it makes the records bulky and unpractical. It is quite clear that maintaining a subsidiary book is facilitation to journal entries, practically it is not possible to post each and every transaction through journal entries, especially in big organizations because it makes the records bulky and unpractical. Maintenance of subsidiary books gives us more scientific, practical, specialized, controlled, and easy approach to work. Maintenance of subsidiary books gives us more scientific, practical, specialized, controlled, and easy approach to work. It provides us facility to divide the work among different departments like sale department, purchase department, cash department, bank department, etc. It makes each department more accountable and provides an easy way to audit and detect errors. It provides us facility to divide the work among different departments like sale department, purchase department, cash department, bank department, etc. It makes each department more accountable and provides an easy way to audit and detect errors. In modern days, the latest computer technology has set its base all over the world. More and more competent accounts professionals are offering their services. Accuracy, quick results, and compliance of law are the key factors of any organization. No one can ignore these factors in a competitive market. In modern days, the latest computer technology has set its base all over the world. More and more competent accounts professionals are offering their services. Accuracy, quick results, and compliance of law are the key factors of any organization. No one can ignore these factors in a competitive market. On a particular date, reconciliation of our bank balance with the balance of bank passbook is called bank reconciliation. The bank reconciliation is a statement that consists of: Balance as per our cash book/bank book Balance as per pass book Reason for difference in both of above This statement may be prepared at any time as per suitability and requirement of the firm, which depends upon the volume and number of transaction of the bank. In these days, where most of the banking transactions are done electronically, the customer gets alerts for every transaction. Time to reconcile the bank is reduced more. Trial balance is a summary of all the debit and credit balances of ledger accounts. The total of debit side and credit side of trial balance should be matched. Trial balance is prepared on the last day of the accounting cycle. Trial balance provides us a comprehensive list of balances. With the help of that, we can draw financial reports of an organization. For example, the trading account can be analyzed to ascertain the gross profit, the profit and loss account is analyzed to ascertain the profit or Loss of that particular accounting year, and finally, the balance sheet of the concern is prepared to conclude the financial position of the firm. Financial statements are prepared to ascertain the profit or loss of the business, and to know the financial position of the company. Trading, profit & Loss accounts ascertain the net profit for an accounting period and balance sheet reflects the position of the business. All the above has almost a fixed format, just put all the balances of ledger accounts into the format given below with the help of the trial balance. With that, we may derive desired results in the shape of financial equations. For the period ending 31-03-2014 as on 31-03-2014 Capital XX Add:Net Profit XX Fixed Assets XXXX Less:Description XX The equation of equity is as follows: Owner Equity = Assets – liability The owner or the sole proprietor of a business makes investments, earns some profit on it, and withdraws some money out of it for his personal use called drawings. We may write this transaction as follows: Investment (capital) ± Profit or Loss – drawings = Owner’s Equity Assets that are convertible into cash within the next accounting year are called current assets. Cash in hand, cash in bank, fixed deposit receipts (FDRs), inventory, debtors, receivable bills, short-term investments, staff loan and advances; all these come under current assets. In addition, prepaid expenses are also a part of current assets. Note: Prepaid expenses are not convertible into cash, but they save cash for the next financial or accounting year. Like current assets, current liabilities are immediate liabilities of the firm that are to be paid within one year from the date of balance sheet. Current liabilities primarily include sundry creditors, expenses payable, bills payable, short-term loans, advance from customers, etc. 13 Lectures 2 hours Manish Gupta 8 Lectures 1 hours Blair Cook 15 Lectures 59 mins Prashant Panchal 26 Lectures 2.5 hours Ross Maynard 12 Lectures 1.5 hours Dr. John McLellan 5 Lectures 50 mins Dr. John McLellan Print Add Notes Bookmark this page
[ { "code": null, "e": 2893, "s": 2639, "text": "Cash book is a record of all the transactions related to cash. Examples include: expenses paid in cash, revenue collected in cash, payments made to creditors, payments received from debtors, cash deposited in bank, withdrawn of cash for office use, etc." }, { "code": null, "e": 3081, "s": 2893, "text": "In double column cash book, a discount column is included on both debit and credit sides to record the discount allowed to customers and the discount received from creditors respectively." }, { "code": null, "e": 3194, "s": 3081, "text": "In triple column cash book, one more column of bank is included to record all the transactions relating to bank." }, { "code": null, "e": 3664, "s": 3194, "text": "Note: In modern accounting, simple cash book is the most popular way to record cash transactions. The double column cash book or three column cash book is practically for academic purpose. A separate bank book is used to record all the banking transactions as they are more than cash transactions. These days, cash\nis used just to meet petty and routine expenditures of an organization. In most of the organizations, the salaries of employees are paid by bank transfer." }, { "code": null, "e": 3752, "s": 3664, "text": "Note: Cash book always shows debit balance, cash in hand, and a part of current assets." }, { "code": null, "e": 4165, "s": 3752, "text": "Cash book is just like a ledger account. There is no need to open a separate cash account in the ledger. The balance of cash book is directly posted to the trial balance. Since cash account is a real account, ruling is followed, i.e. what comes in – debit, and what goes out – credit. All the received cash is posted in the debit side and all payments and expenses are posted in the credit side of the cash book." }, { "code": null, "e": 4446, "s": 4165, "text": "Here, we have an additional Discount column on each side of the cash book. The debit side column of discount represents the discount to debtors of the company and the credit side of discount column means the discount received from our suppliers or creditors while making payments." }, { "code": null, "e": 4726, "s": 4446, "text": "The total of discount column of debit side of cash book is posted in the ledger account of ‘Discount Allowed to Customers’ account as ‘To Total As Per Cash Book’. Similarly, credit column of cash book is posted in ledger account of ‘Discount Received’ as ‘By total of cash book’." }, { "code": null, "e": 5004, "s": 4726, "text": "When one more column of Bank is added in both sides of the double column cash book to post all banking transactions, it is called triple column cash book. All banking transactions are routed through this cash book and there is no need to open a separate bank account in ledger." }, { "code": null, "e": 5290, "s": 5004, "text": "In any organization, there may be many petty transactions incurring for which payments have to be done. Therefore, cash is kept with an employee, who deals with it and makes regular payments out of it. To make it simple and secure, mostly a constant balance is kept with that employee." }, { "code": null, "e": 5634, "s": 5290, "text": "Suppose cashier pays Rs 5,000 to Mr A, who will pay day-to-day organization expenses out of it. Suppose Mr A spend Rs 4,200 out of it in a day, the main cashier pays Rs 4,200, so his balance of petty cash book will be again Rs 5,000. It is very useful system of accounting, as it saves the time of the main cashier and provides better control." }, { "code": null, "e": 5760, "s": 5634, "text": "We will soon discuss about ‘Analytical or Columnar Petty Cash Book’ which is most commonly used in most of the organizations." }, { "code": null, "e": 5881, "s": 5760, "text": "Purchase book is prepared to record all the credit purchases of an organization. Purchase book is not a purchase ledger." }, { "code": null, "e": 5996, "s": 5881, "text": "The features of a sale book are same as a purchase book, except for the fact that it records all the credit sales." }, { "code": null, "e": 6179, "s": 5996, "text": "Sometimes goods are to be retuned back to the supplier, for various reasons. The most common reason being defective goods or poor quality goods. In this case, a debit note is issued." }, { "code": null, "e": 6381, "s": 6179, "text": "The reason of Sale return is same as for purchase return. Sometimes customers return the goods if they don’t meet the quality standards promised. In such cases, a credit note is issued to the customer." }, { "code": null, "e": 6711, "s": 6381, "text": "Bills are raised by creditors to debtors. The debtors accept them and subsequently return them to the creditors. Bills accepted by debtors are called as ‘Bills Receivables’ in the books of creditors, and ‘Bills Payable’ in the books of debtors. We keep them in our record called ‘Bills Receivable Books’ and ‘Bills Payable Book’." }, { "code": null, "e": 6825, "s": 6711, "text": "Bills payable issues to the supplier of goods or services for payment, and the record is maintained in this book." }, { "code": null, "e": 7155, "s": 6825, "text": "There is a difference between a purchase book and a purchase ledger. A purchase book records only credit purchases and a purchase ledger records all the cash purchases in chronical order. The daily balance of purchase book is transferred to purchase ledger. Therefore, purchase ledger is a comprehensive account of all purchases." }, { "code": null, "e": 7208, "s": 7155, "text": "The same rule applies to sale book and sale ledgers." }, { "code": null, "e": 7472, "s": 7208, "text": "It is quite clear that maintaining a subsidiary book is facilitation to journal entries, practically it is not possible to post each and every transaction through journal entries, especially in big organizations because it makes the records bulky and unpractical." }, { "code": null, "e": 7736, "s": 7472, "text": "It is quite clear that maintaining a subsidiary book is facilitation to journal entries, practically it is not possible to post each and every transaction through journal entries, especially in big organizations because it makes the records bulky and unpractical." }, { "code": null, "e": 7857, "s": 7736, "text": "Maintenance of subsidiary books gives us more scientific, practical, specialized, controlled, and easy approach to work." }, { "code": null, "e": 7978, "s": 7857, "text": "Maintenance of subsidiary books gives us more scientific, practical, specialized, controlled, and easy approach to work." }, { "code": null, "e": 8226, "s": 7978, "text": "It provides us facility to divide the work among different departments like sale department, purchase department, cash department, bank department, etc. It makes each department more accountable and provides an easy way to audit and detect errors." }, { "code": null, "e": 8474, "s": 8226, "text": "It provides us facility to divide the work among different departments like sale department, purchase department, cash department, bank department, etc. It makes each department more accountable and provides an easy way to audit and detect errors." }, { "code": null, "e": 8779, "s": 8474, "text": "In modern days, the latest computer technology has set its base all over the world. More and more competent accounts professionals are offering their services. Accuracy, quick results, and compliance of law are the key factors of any organization. No one can ignore these factors in a competitive market." }, { "code": null, "e": 9084, "s": 8779, "text": "In modern days, the latest computer technology has set its base all over the world. More and more competent accounts professionals are offering their services. Accuracy, quick results, and compliance of law are the key factors of any organization. No one can ignore these factors in a competitive market." }, { "code": null, "e": 9263, "s": 9084, "text": "On a particular date, reconciliation of our bank balance with the balance of bank passbook is called bank reconciliation. The bank reconciliation is a statement that consists of:" }, { "code": null, "e": 9302, "s": 9263, "text": "Balance as per our cash book/bank book" }, { "code": null, "e": 9327, "s": 9302, "text": "Balance as per pass book" }, { "code": null, "e": 9366, "s": 9327, "text": "Reason for difference in both of above" }, { "code": null, "e": 9527, "s": 9366, "text": "This statement may be prepared at any time as per suitability and requirement of the firm, which depends upon the volume and number of transaction of the bank. " }, { "code": null, "e": 9698, "s": 9527, "text": "In these days, where most of the banking transactions are done electronically, the customer gets alerts for every transaction. Time to reconcile the bank is reduced more." }, { "code": null, "e": 9925, "s": 9698, "text": "Trial balance is a summary of all the debit and credit balances of ledger accounts. The total of debit side and credit side of trial balance should be matched. Trial balance is prepared on the last day of the accounting cycle." }, { "code": null, "e": 10352, "s": 9925, "text": "Trial balance provides us a comprehensive list of balances. With the help of that, we can draw financial reports of an organization. For example, the trading account can be analyzed to ascertain the gross profit, the profit and loss account is analyzed to ascertain the profit or Loss of that particular accounting year, and finally, the balance sheet of the concern is prepared to conclude the financial position of the firm." }, { "code": null, "e": 10486, "s": 10352, "text": "Financial statements are prepared to ascertain the profit or loss of the business, and to know the financial position of the company." }, { "code": null, "e": 10625, "s": 10486, "text": "Trading, profit & Loss accounts ascertain the net profit for an accounting period and balance sheet reflects the position of the business." }, { "code": null, "e": 10853, "s": 10625, "text": "All the above has almost a fixed format, just put all the balances of ledger accounts into the format given below with the help of the trial balance. With that, we may derive desired results in the shape of financial equations." }, { "code": null, "e": 10886, "s": 10853, "text": "For the period ending 31-03-2014" }, { "code": null, "e": 10903, "s": 10886, "text": "as on 31-03-2014" }, { "code": null, "e": 10914, "s": 10903, "text": "Capital XX" }, { "code": null, "e": 10932, "s": 10914, "text": "Add:Net Profit XX" }, { "code": null, "e": 10950, "s": 10932, "text": "Fixed Assets XXXX" }, { "code": null, "e": 10970, "s": 10950, "text": "Less:Description XX" }, { "code": null, "e": 11008, "s": 10970, "text": "The equation of equity is as follows:" }, { "code": null, "e": 11043, "s": 11008, "text": "Owner Equity = Assets – liability\n" }, { "code": null, "e": 11249, "s": 11043, "text": "The owner or the sole proprietor of a business makes investments, earns some profit on it, and withdraws some money out of it for his personal use called drawings. We may write this transaction as follows:" }, { "code": null, "e": 11316, "s": 11249, "text": "Investment (capital) ± Profit or Loss – drawings = Owner’s Equity\n" }, { "code": null, "e": 11413, "s": 11316, "text": "Assets that are convertible into cash within the next accounting year are called current assets." }, { "code": null, "e": 11661, "s": 11413, "text": "Cash in hand, cash in bank, fixed deposit receipts (FDRs), inventory, debtors, receivable bills, short-term investments, staff loan and advances; all these come\nunder current assets. In addition, prepaid expenses are also a part of current assets." }, { "code": null, "e": 11777, "s": 11661, "text": "Note: Prepaid expenses are not convertible into cash, but they save cash for the next financial or accounting year." }, { "code": null, "e": 11924, "s": 11777, "text": "Like current assets, current liabilities are immediate liabilities of the firm that are to be paid within one year from the date of balance sheet." }, { "code": null, "e": 12060, "s": 11924, "text": "Current liabilities primarily include sundry creditors, expenses payable, bills payable, short-term loans, advance from customers, etc." }, { "code": null, "e": 12093, "s": 12060, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 12107, "s": 12093, "text": " Manish Gupta" }, { "code": null, "e": 12139, "s": 12107, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 12151, "s": 12139, "text": " Blair Cook" }, { "code": null, "e": 12183, "s": 12151, "text": "\n 15 Lectures \n 59 mins\n" }, { "code": null, "e": 12201, "s": 12183, "text": " Prashant Panchal" }, { "code": null, "e": 12236, "s": 12201, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12250, "s": 12236, "text": " Ross Maynard" }, { "code": null, "e": 12285, "s": 12250, "text": "\n 12 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12304, "s": 12285, "text": " Dr. John McLellan" }, { "code": null, "e": 12335, "s": 12304, "text": "\n 5 Lectures \n 50 mins\n" }, { "code": null, "e": 12354, "s": 12335, "text": " Dr. John McLellan" }, { "code": null, "e": 12361, "s": 12354, "text": " Print" }, { "code": null, "e": 12372, "s": 12361, "text": " Add Notes" } ]
PHP | defined() function - GeeksforGeeks
23 Aug, 2019 The PHP defined() function is an inbuilt function in PHP which checks whether a constant is exists or not, in other words, defined or not. Syntax: bool defined($constant_name); Parameter: This function accepts a single parameter as mentioned above and described below. $constant_name: This is required parameter. It specifies the name of the constant. Return Value: This function returns TRUE if constant exists and FALSE otherwise. Note: This function is available for PHP 4.0.0 and newer version. Below examples illustrate the function: Example 1: <?phpdefine("constant_key", "value for the constant key");echo defined("constant_key");?> Output: 1 Example 2: checking with if condition after defining the constant. <?phpdefine("constant_key", "value for the constant key");if(defined("constant_key")){ echo "constant_key is defined";}else{ echo "constant_key is not defined";}?> Output: constant_key is defined Example 3: checking with if condition without defining the constant. <?php//define("constant_key", "value for the constant key");if(defined("constant_key")){ echo "constant_key is defined";}else{ echo "constant_key is not defined";}?> Output: constant_key is not defined PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? Create a drop-down list that options fetched from a MySQL database in PHP How to create admin login page using PHP? Different ways for passing data to view in Laravel Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24581, "s": 24553, "text": "\n23 Aug, 2019" }, { "code": null, "e": 24720, "s": 24581, "text": "The PHP defined() function is an inbuilt function in PHP which checks whether a constant is exists or not, in other words, defined or not." }, { "code": null, "e": 24728, "s": 24720, "text": "Syntax:" }, { "code": null, "e": 24758, "s": 24728, "text": "bool defined($constant_name);" }, { "code": null, "e": 24850, "s": 24758, "text": "Parameter: This function accepts a single parameter as mentioned above and described below." }, { "code": null, "e": 24933, "s": 24850, "text": "$constant_name: This is required parameter. It specifies the name of the constant." }, { "code": null, "e": 25014, "s": 24933, "text": "Return Value: This function returns TRUE if constant exists and FALSE otherwise." }, { "code": null, "e": 25080, "s": 25014, "text": "Note: This function is available for PHP 4.0.0 and newer version." }, { "code": null, "e": 25120, "s": 25080, "text": "Below examples illustrate the function:" }, { "code": null, "e": 25131, "s": 25120, "text": "Example 1:" }, { "code": "<?phpdefine(\"constant_key\", \"value for the constant key\");echo defined(\"constant_key\");?>", "e": 25221, "s": 25131, "text": null }, { "code": null, "e": 25229, "s": 25221, "text": "Output:" }, { "code": null, "e": 25232, "s": 25229, "text": "1\n" }, { "code": null, "e": 25299, "s": 25232, "text": "Example 2: checking with if condition after defining the constant." }, { "code": "<?phpdefine(\"constant_key\", \"value for the constant key\");if(defined(\"constant_key\")){ echo \"constant_key is defined\";}else{ echo \"constant_key is not defined\";}?>", "e": 25469, "s": 25299, "text": null }, { "code": null, "e": 25477, "s": 25469, "text": "Output:" }, { "code": null, "e": 25502, "s": 25477, "text": "constant_key is defined\n" }, { "code": null, "e": 25571, "s": 25502, "text": "Example 3: checking with if condition without defining the constant." }, { "code": "<?php//define(\"constant_key\", \"value for the constant key\");if(defined(\"constant_key\")){ echo \"constant_key is defined\";}else{ echo \"constant_key is not defined\";}?>", "e": 25743, "s": 25571, "text": null }, { "code": null, "e": 25751, "s": 25743, "text": "Output:" }, { "code": null, "e": 25780, "s": 25751, "text": "constant_key is not defined\n" }, { "code": null, "e": 25793, "s": 25780, "text": "PHP-function" }, { "code": null, "e": 25797, "s": 25793, "text": "PHP" }, { "code": null, "e": 25814, "s": 25797, "text": "Web Technologies" }, { "code": null, "e": 25818, "s": 25814, "text": "PHP" }, { "code": null, "e": 25916, "s": 25818, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25925, "s": 25916, "text": "Comments" }, { "code": null, "e": 25938, "s": 25925, "text": "Old Comments" }, { "code": null, "e": 26020, "s": 25938, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 26084, "s": 26020, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 26158, "s": 26084, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 26200, "s": 26158, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 26251, "s": 26200, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 26307, "s": 26251, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26340, "s": 26307, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26402, "s": 26340, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26445, "s": 26402, "text": "How to fetch data from an API in ReactJS ?" } ]
JFreeChart - Line Chart
A line chart or line graph displays information as a series of data points (markers) connected by straight line segments. Line Chart shows how data changes at equal time frequency. This chapter demonstrates how we can use JFreeChart to create Line Chart from a given set of business data. The following example draws a line chart to show a trend of number of schools opened in different years starting from 1970. Given data is as follows − Following is the code to create Line Chart from the information above given. This code helps you to embed a line chart in any AWT based application. import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; public class LineChart_AWT extends ApplicationFrame { public LineChart_AWT( String applicationTitle , String chartTitle ) { super(applicationTitle); JFreeChart lineChart = ChartFactory.createLineChart( chartTitle, "Years","Number of Schools", createDataset(), PlotOrientation.VERTICAL, true,true,false); ChartPanel chartPanel = new ChartPanel( lineChart ); chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 367 ) ); setContentPane( chartPanel ); } private DefaultCategoryDataset createDataset( ) { DefaultCategoryDataset dataset = new DefaultCategoryDataset( ); dataset.addValue( 15 , "schools" , "1970" ); dataset.addValue( 30 , "schools" , "1980" ); dataset.addValue( 60 , "schools" , "1990" ); dataset.addValue( 120 , "schools" , "2000" ); dataset.addValue( 240 , "schools" , "2010" ); dataset.addValue( 300 , "schools" , "2014" ); return dataset; } public static void main( String[ ] args ) { LineChart_AWT chart = new LineChart_AWT( "School Vs Years" , "Numer of Schools vs years"); chart.pack( ); RefineryUtilities.centerFrameOnScreen( chart ); chart.setVisible( true ); } } Let us keep the above Java code in LineChart_AWT.java file, and then compile and run it from the command prompted as − $javac LineChart_AWT.java $java LineChart_AWT If everything is fine, it will compile and run to generate the following Line Graph − Let us re-write the above example to generate a JPEG image from a command line. import java.io.*; import org.jfree.chart.JFreeChart; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; public class LineChart { public static void main( String[ ] args ) throws Exception { DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset(); line_chart_dataset.addValue( 15 , "schools" , "1970" ); line_chart_dataset.addValue( 30 , "schools" , "1980" ); line_chart_dataset.addValue( 60 , "schools" , "1990" ); line_chart_dataset.addValue( 120 , "schools" , "2000" ); line_chart_dataset.addValue( 240 , "schools" , "2010" ); line_chart_dataset.addValue( 300 , "schools" , "2014" ); JFreeChart lineChartObject = ChartFactory.createLineChart( "Schools Vs Years","Year", "Schools Count", line_chart_dataset,PlotOrientation.VERTICAL, true,true,false); int width = 640; /* Width of the image */ int height = 480; /* Height of the image */ File lineChart = new File( "LineChart.jpeg" ); ChartUtilities.saveChartAsJPEG(lineChart ,lineChartObject, width ,height); } } Let us keep the above Java code in LineChart.java file, and then compile and run it from the command prompted as − $javac LineChart.java $java LineChart If everything is fine, it will compile and execute to create a JPEG image file named LineChart.jpeg in your current directory. Print Add Notes Bookmark this page
[ { "code": null, "e": 2122, "s": 1941, "text": "A line chart or line graph displays information as a series of data points (markers) connected by straight line segments. Line Chart shows how data changes at equal time frequency." }, { "code": null, "e": 2230, "s": 2122, "text": "This chapter demonstrates how we can use JFreeChart to create Line Chart from a given set of business data." }, { "code": null, "e": 2354, "s": 2230, "text": "The following example draws a line chart to show a trend of number of schools opened in different years starting from 1970." }, { "code": null, "e": 2381, "s": 2354, "text": "Given data is as follows −" }, { "code": null, "e": 2530, "s": 2381, "text": "Following is the code to create Line Chart from the information above given. This code helps you to embed a line chart in any AWT based application." }, { "code": null, "e": 4106, "s": 2530, "text": "import org.jfree.chart.ChartPanel;\nimport org.jfree.chart.ChartFactory;\nimport org.jfree.chart.JFreeChart;\nimport org.jfree.ui.ApplicationFrame;\nimport org.jfree.ui.RefineryUtilities;\nimport org.jfree.chart.plot.PlotOrientation;\nimport org.jfree.data.category.DefaultCategoryDataset;\n\npublic class LineChart_AWT extends ApplicationFrame {\n\n public LineChart_AWT( String applicationTitle , String chartTitle ) {\n super(applicationTitle);\n JFreeChart lineChart = ChartFactory.createLineChart(\n chartTitle,\n \"Years\",\"Number of Schools\",\n createDataset(),\n PlotOrientation.VERTICAL,\n true,true,false);\n \n ChartPanel chartPanel = new ChartPanel( lineChart );\n chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 367 ) );\n setContentPane( chartPanel );\n }\n\n private DefaultCategoryDataset createDataset( ) {\n DefaultCategoryDataset dataset = new DefaultCategoryDataset( );\n dataset.addValue( 15 , \"schools\" , \"1970\" );\n dataset.addValue( 30 , \"schools\" , \"1980\" );\n dataset.addValue( 60 , \"schools\" , \"1990\" );\n dataset.addValue( 120 , \"schools\" , \"2000\" );\n dataset.addValue( 240 , \"schools\" , \"2010\" );\n dataset.addValue( 300 , \"schools\" , \"2014\" );\n return dataset;\n }\n \n public static void main( String[ ] args ) {\n LineChart_AWT chart = new LineChart_AWT(\n \"School Vs Years\" ,\n \"Numer of Schools vs years\");\n\n chart.pack( );\n RefineryUtilities.centerFrameOnScreen( chart );\n chart.setVisible( true );\n }\n}" }, { "code": null, "e": 4225, "s": 4106, "text": "Let us keep the above Java code in LineChart_AWT.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 4275, "s": 4225, "text": "$javac LineChart_AWT.java \n$java LineChart_AWT \n" }, { "code": null, "e": 4361, "s": 4275, "text": "If everything is fine, it will compile and run to generate the following Line Graph −" }, { "code": null, "e": 4441, "s": 4361, "text": "Let us re-write the above example to generate a JPEG image from a command line." }, { "code": null, "e": 5677, "s": 4441, "text": "import java.io.*;\n\nimport org.jfree.chart.JFreeChart; \nimport org.jfree.chart.ChartFactory; \nimport org.jfree.chart.ChartUtilities; \nimport org.jfree.chart.plot.PlotOrientation;\nimport org.jfree.data.category.DefaultCategoryDataset;\n\npublic class LineChart {\n\n public static void main( String[ ] args ) throws Exception {\n DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset();\n line_chart_dataset.addValue( 15 , \"schools\" , \"1970\" );\n line_chart_dataset.addValue( 30 , \"schools\" , \"1980\" );\n line_chart_dataset.addValue( 60 , \"schools\" , \"1990\" );\n line_chart_dataset.addValue( 120 , \"schools\" , \"2000\" );\n line_chart_dataset.addValue( 240 , \"schools\" , \"2010\" ); \n line_chart_dataset.addValue( 300 , \"schools\" , \"2014\" );\n\n JFreeChart lineChartObject = ChartFactory.createLineChart(\n \"Schools Vs Years\",\"Year\",\n \"Schools Count\",\n line_chart_dataset,PlotOrientation.VERTICAL,\n true,true,false);\n\n int width = 640; /* Width of the image */\n int height = 480; /* Height of the image */ \n File lineChart = new File( \"LineChart.jpeg\" ); \n ChartUtilities.saveChartAsJPEG(lineChart ,lineChartObject, width ,height);\n }\n}" }, { "code": null, "e": 5792, "s": 5677, "text": "Let us keep the above Java code in LineChart.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 5833, "s": 5792, "text": "$javac LineChart.java \n$java LineChart\n" }, { "code": null, "e": 5960, "s": 5833, "text": "If everything is fine, it will compile and execute to create a JPEG image file named LineChart.jpeg in your current directory." }, { "code": null, "e": 5967, "s": 5960, "text": " Print" }, { "code": null, "e": 5978, "s": 5967, "text": " Add Notes" } ]
MATLAB - Vector Dot Product
Dot product of two vectors a = (a1, a2, ..., an) and b = (b1, b2, ..., bn) is given by − a.b = ∑(ai.bi) Dot product of two vectors a and b is calculated using the dot function. dot(a, b); Create a script file with the following code − v1 = [2 3 4]; v2 = [1 2 3]; dp = dot(v1, v2); disp('Dot Product:'); disp(dp); When you run the file, it displays the following result − Dot Product: 20 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2230, "s": 2141, "text": "Dot product of two vectors a = (a1, a2, ..., an) and b = (b1, b2, ..., bn) is given by −" }, { "code": null, "e": 2245, "s": 2230, "text": "a.b = ∑(ai.bi)" }, { "code": null, "e": 2318, "s": 2245, "text": "Dot product of two vectors a and b is calculated using the dot function." }, { "code": null, "e": 2330, "s": 2318, "text": "dot(a, b);\n" }, { "code": null, "e": 2377, "s": 2330, "text": "Create a script file with the following code −" }, { "code": null, "e": 2456, "s": 2377, "text": "v1 = [2 3 4];\nv2 = [1 2 3];\ndp = dot(v1, v2);\ndisp('Dot Product:'); \ndisp(dp);" }, { "code": null, "e": 2514, "s": 2456, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 2534, "s": 2514, "text": "Dot Product:\n 20\n" }, { "code": null, "e": 2567, "s": 2534, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 2580, "s": 2567, "text": " Nouman Azam" }, { "code": null, "e": 2615, "s": 2580, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 2628, "s": 2615, "text": " Nouman Azam" }, { "code": null, "e": 2661, "s": 2628, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 2670, "s": 2661, "text": " Sanjeev" }, { "code": null, "e": 2703, "s": 2670, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 2719, "s": 2703, "text": " TELCOMA Global" }, { "code": null, "e": 2752, "s": 2719, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 2768, "s": 2752, "text": " TELCOMA Global" }, { "code": null, "e": 2801, "s": 2768, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 2818, "s": 2801, "text": " Phinite Academy" }, { "code": null, "e": 2825, "s": 2818, "text": " Print" }, { "code": null, "e": 2836, "s": 2825, "text": " Add Notes" } ]
How to Save a Plot to a File Using Matplotlib? - GeeksforGeeks
03 Jan, 2021 Matplotlib is a widely used python library to plot graphs, plots, charts, etc. show() method is used to display graphs as output, but don’t save it in any file. To save generated graphs in a file on storage disk, savefig() method is used. savefig() : Save the current figure. Syntax: pyplot.savefig(fname, dpi=None, facecolor=’w’, edgecolor=’w’, orientation=’portrait’, papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None, metadata=None) Parameters: fname : path or name of output file with extension. If extension is not provided plot is saved as png file. Supported file formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff. dpi : dots per inch resolution of figure facecolor : facecolor of figure edgecolor : edgecolor of figure orientation : landscape or portrait format : The file format, e.g. ‘png’, ‘pdf’, ‘svg’, etc. transparent : If it is True, the patches of axes will all be transparent Steps: Plot a graphUse pyplot.savefig() method to save generated plot in a file Plot a graph Use pyplot.savefig() method to save generated plot in a file Example: Python3 import matplotlib.pyplot as plt # Creating datayear = ['2010', '2002', '2004', '2006', '2008']production = [25, 15, 35, 30, 10] # Plotting barchartplt.bar(year, production) # Saving the figure.plt.savefig("output.jpg") # Saving figure by changing parameter valuesplt.savefig("output1", facecolor='y', bbox_inches="tight", pad_inches=0.3, transparent=True) Output: Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n03 Jan, 2021" }, { "code": null, "e": 24532, "s": 24292, "text": "Matplotlib is a widely used python library to plot graphs, plots, charts, etc. show() method is used to display graphs as output, but don’t save it in any file. To save generated graphs in a file on storage disk, savefig() method is used." }, { "code": null, "e": 24569, "s": 24532, "text": "savefig() : Save the current figure." }, { "code": null, "e": 24774, "s": 24569, "text": "Syntax: pyplot.savefig(fname, dpi=None, facecolor=’w’, edgecolor=’w’, orientation=’portrait’, papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None, metadata=None)" }, { "code": null, "e": 24786, "s": 24774, "text": "Parameters:" }, { "code": null, "e": 24986, "s": 24786, "text": "fname : path or name of output file with extension. If extension is not provided plot is saved as png file. Supported file formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff." }, { "code": null, "e": 25027, "s": 24986, "text": "dpi : dots per inch resolution of figure" }, { "code": null, "e": 25059, "s": 25027, "text": "facecolor : facecolor of figure" }, { "code": null, "e": 25092, "s": 25059, "text": "edgecolor : edgecolor of figure" }, { "code": null, "e": 25129, "s": 25092, "text": "orientation : landscape or portrait" }, { "code": null, "e": 25186, "s": 25129, "text": "format : The file format, e.g. ‘png’, ‘pdf’, ‘svg’, etc." }, { "code": null, "e": 25260, "s": 25186, "text": "transparent : If it is True, the patches of axes will all be transparent" }, { "code": null, "e": 25267, "s": 25260, "text": "Steps:" }, { "code": null, "e": 25340, "s": 25267, "text": "Plot a graphUse pyplot.savefig() method to save generated plot in a file" }, { "code": null, "e": 25353, "s": 25340, "text": "Plot a graph" }, { "code": null, "e": 25414, "s": 25353, "text": "Use pyplot.savefig() method to save generated plot in a file" }, { "code": null, "e": 25423, "s": 25414, "text": "Example:" }, { "code": null, "e": 25431, "s": 25423, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # Creating datayear = ['2010', '2002', '2004', '2006', '2008']production = [25, 15, 35, 30, 10] # Plotting barchartplt.bar(year, production) # Saving the figure.plt.savefig(\"output.jpg\") # Saving figure by changing parameter valuesplt.savefig(\"output1\", facecolor='y', bbox_inches=\"tight\", pad_inches=0.3, transparent=True)", "e": 25802, "s": 25431, "text": null }, { "code": null, "e": 25810, "s": 25802, "text": "Output:" }, { "code": null, "e": 25817, "s": 25810, "text": "Picked" }, { "code": null, "e": 25835, "s": 25817, "text": "Python-matplotlib" }, { "code": null, "e": 25842, "s": 25835, "text": "Python" }, { "code": null, "e": 25940, "s": 25842, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25972, "s": 25940, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26014, "s": 25972, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26070, "s": 26014, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26112, "s": 26070, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26143, "s": 26112, "text": "Python | os.path.join() method" }, { "code": null, "e": 26198, "s": 26143, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26220, "s": 26198, "text": "Defaultdict in Python" }, { "code": null, "e": 26259, "s": 26220, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26288, "s": 26259, "text": "Create a directory in Python" } ]
Select last 20 records ordered in ascending order in MySQL?
To select last 20 records in ascending order, you can use subquery LIMIT clause. The syntax is as follows SELECT *FROM ( SELECT *FROM yourTableName ORDER BY yourColumnName desc limit 20 ) anyVariableName order by anyVariableName.yourColumnName; To understand the above syntax, let us create a table. The query to create a table is as follows mysql> create table ProductInformation -> ( -> ProductId int, -> ProductName varchar(100), -> ProductPrice int -> ); Query OK, 0 rows affected (0.50 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into ProductInformation values(101,'Product-1',200); Query OK, 1 row affected (0.16 sec) mysql> insert into ProductInformation values(102,'Product-2',300); Query OK, 1 row affected (0.23 sec) mysql> insert into ProductInformation values(103,'Product-3',700); Query OK, 1 row affected (0.09 sec) mysql> insert into ProductInformation values(104,'Product-4',100); Query OK, 1 row affected (0.15 sec) mysql> insert into ProductInformation values(105,'Product-5',1500); Query OK, 1 row affected (0.18 sec) mysql> insert into ProductInformation values(106,'Product-6',1200); Query OK, 1 row affected (0.18 sec) mysql> insert into ProductInformation values(107,'Product-7',1300); Query OK, 1 row affected (0.17 sec) mysql> insert into ProductInformation values(108,'Product-8',1600); Query OK, 1 row affected (0.29 sec) mysql> insert into ProductInformation values(109,'Product-9',1250); Query OK, 1 row affected (0.15 sec) mysql> insert into ProductInformation values(110,'Product-10',1900); Query OK, 1 row affected (0.15 sec) mysql> insert into ProductInformation values(111,'Product-11',1870); Query OK, 1 row affected (0.13 sec) mysql> insert into ProductInformation values(112,'Product-12',1876); Query OK, 1 row affected (0.11 sec) mysql> insert into ProductInformation values(113,'Product-13',1869); Query OK, 1 row affected (0.19 sec) mysql> insert into ProductInformation values(114,'Product-14',1456); Query OK, 1 row affected (0.25 sec) mysql> insert into ProductInformation values(115,'Product-15',1860); Query OK, 1 row affected (0.16 sec) mysql> insert into ProductInformation values(116,'Product-16',359); Query OK, 1 row affected (0.21 sec) mysql> insert into ProductInformation values(117,'Product-17',1667); Query OK, 1 row affected (0.09 sec) mysql> insert into ProductInformation values(118,'Product-18',1467); Query OK, 1 row affected (0.11 sec) mysql> insert into ProductInformation values(119,'Product-19',2134); Query OK, 1 row affected (0.24 sec) mysql> insert into ProductInformation values(120,'Product-20',3450); Query OK, 1 row affected (0.10 sec) mysql> insert into ProductInformation values(121,'Product-21',198); Query OK, 1 row affected (0.22 sec) mysql> insert into ProductInformation values(122,'Product-22',195); Query OK, 1 row affected (0.21 sec) mysql> insert into ProductInformation values(123,'Product-23',10000); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement. The query is as follows mysql> select *from ProductInformation; The following is the output +-----------+-------------+--------------+ | ProductId | ProductName | ProductPrice | +-----------+-------------+--------------+ | 101 | Product-1 | 200 | | 102 | Product-2 | 300 | | 103 | Product-3 | 700 | | 104 | Product-4 | 100 | | 105 | Product-5 | 1500 | | 106 | Product-6 | 1200 | | 107 | Product-7 | 1300 | | 108 | Product-8 | 1600 | | 109 | Product-9 | 1250 | | 110 | Product-10 | 1900 | | 111 | Product-11 | 1870 | | 112 | Product-12 | 1876 | | 113 | Product-13 | 1869 | | 114 | Product-14 | 1456 | | 115 | Product-15 | 1860 | | 116 | Product-16 | 359 | | 117 | Product-17 | 1667 | | 118 | Product-18 | 1467 | | 119 | Product-19 | 2134 | | 120 | Product-20 | 3450 | | 121 | Product-21 | 198 | | 122 | Product-22 | 195 | | 123 | Product-23 | 10000 | +-----------+-------------+--------------+ 23 rows in set (0.00 sec) Here is the query to select last 20 records from the table in ascending order mysql> select *from -> ( -> select *from ProductInformation order by ProductId desc limit 20 -> ) t1 order by t1.ProductId asc; The following is the output +-----------+-------------+--------------+ | ProductId | ProductName | ProductPrice | +-----------+-------------+--------------+ | 104 | Product-4 | 100 | | 105 | Product-5 | 1500 | | 106 | Product-6 | 1200 | | 107 | Product-7 | 1300 | | 108 | Product-8 | 1600 | | 109 | Product-9 | 1250 | | 110 | Product-10 | 1900 | | 111 | Product-11 | 1870 | | 112 | Product-12 | 1876 | | 113 | Product-13 | 1869 | | 114 | Product-14 | 1456 | | 115 | Product-15 | 1860 | | 116 | Product-16 | 359 | | 117 | Product-17 | 1667 | | 118 | Product-18 | 1467 | | 119 | Product-19 | 2134 | | 120 | Product-20 | 3450 | | 121 | Product-21 | 198 | | 122 | Product-22 | 195 | | 123 | Product-23 | 10000 | +-----------+-------------+--------------+ 20 rows in set (0.00 sec) If you want the records in descending order, then use desc. The query is as follows to get result in descending order. mysql> select *from -> ( -> select *from ProductInformation order by ProductId desc limit 20 -> ) t2 order by t2.ProductId desc; The following is the output +-----------+-------------+--------------+ | ProductId | ProductName | ProductPrice | +-----------+-------------+--------------+ | 123 | Product-23 | 10000 | | 122 | Product-22 | 195 | | 121 | Product-21 | 198 | | 120 | Product-20 | 3450 | | 119 | Product-19 | 2134 | | 118 | Product-18 | 1467 | | 117 | Product-17 | 1667 | | 116 | Product-16 | 359 | | 115 | Product-15 | 1860 | | 114 | Product-14 | 1456 | | 113 | Product-13 | 1869 | | 112 | Product-12 | 1876 | | 111 | Product-11 | 1870 | | 110 | Product-10 | 1900 | | 109 | Product-9 | 1250 | | 108 | Product-8 | 1600 | | 107 | Product-7 | 1300 | | 106 | Product-6 | 1200 | | 105 | Product-5 | 1500 | | 104 | Product-4 | 100 | +-----------+-------------+--------------+ 20 rows in set (0.00 sec)
[ { "code": null, "e": 1168, "s": 1062, "text": "To select last 20 records in ascending order, you can use subquery LIMIT clause. The syntax is as follows" }, { "code": null, "e": 1310, "s": 1168, "text": "SELECT *FROM\n(\n SELECT *FROM yourTableName ORDER BY yourColumnName desc limit 20\n)\nanyVariableName order by anyVariableName.yourColumnName;" }, { "code": null, "e": 1407, "s": 1310, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1576, "s": 1407, "text": "mysql> create table ProductInformation\n -> (\n -> ProductId int,\n -> ProductName varchar(100),\n -> ProductPrice int\n -> );\nQuery OK, 0 rows affected (0.50 sec)" }, { "code": null, "e": 1655, "s": 1576, "text": "Insert some records in the table using insert command. The query is as follows" }, { "code": null, "e": 4077, "s": 1655, "text": "mysql> insert into ProductInformation values(101,'Product-1',200);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into ProductInformation values(102,'Product-2',300);\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into ProductInformation values(103,'Product-3',700);\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into ProductInformation values(104,'Product-4',100);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into ProductInformation values(105,'Product-5',1500);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into ProductInformation values(106,'Product-6',1200);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into ProductInformation values(107,'Product-7',1300);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into ProductInformation values(108,'Product-8',1600);\nQuery OK, 1 row affected (0.29 sec)\n\nmysql> insert into ProductInformation values(109,'Product-9',1250);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into ProductInformation values(110,'Product-10',1900);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into ProductInformation values(111,'Product-11',1870);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into ProductInformation values(112,'Product-12',1876);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into ProductInformation values(113,'Product-13',1869);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into ProductInformation values(114,'Product-14',1456);\nQuery OK, 1 row affected (0.25 sec)\n\nmysql> insert into ProductInformation values(115,'Product-15',1860);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into ProductInformation values(116,'Product-16',359);\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into ProductInformation values(117,'Product-17',1667);\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into ProductInformation values(118,'Product-18',1467);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into ProductInformation values(119,'Product-19',2134);\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into ProductInformation values(120,'Product-20',3450);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into ProductInformation values(121,'Product-21',198);\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into ProductInformation values(122,'Product-22',195);\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into ProductInformation values(123,'Product-23',10000);\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 4160, "s": 4077, "text": "Display all records from the table using select statement. The query is as follows" }, { "code": null, "e": 4200, "s": 4160, "text": "mysql> select *from ProductInformation;" }, { "code": null, "e": 4228, "s": 4200, "text": "The following is the output" }, { "code": null, "e": 5415, "s": 4228, "text": "+-----------+-------------+--------------+\n| ProductId | ProductName | ProductPrice |\n+-----------+-------------+--------------+\n| 101 | Product-1 | 200 |\n| 102 | Product-2 | 300 |\n| 103 | Product-3 | 700 |\n| 104 | Product-4 | 100 |\n| 105 | Product-5 | 1500 |\n| 106 | Product-6 | 1200 |\n| 107 | Product-7 | 1300 |\n| 108 | Product-8 | 1600 |\n| 109 | Product-9 | 1250 |\n| 110 | Product-10 | 1900 |\n| 111 | Product-11 | 1870 |\n| 112 | Product-12 | 1876 |\n| 113 | Product-13 | 1869 |\n| 114 | Product-14 | 1456 |\n| 115 | Product-15 | 1860 |\n| 116 | Product-16 | 359 |\n| 117 | Product-17 | 1667 |\n| 118 | Product-18 | 1467 |\n| 119 | Product-19 | 2134 |\n| 120 | Product-20 | 3450 |\n| 121 | Product-21 | 198 |\n| 122 | Product-22 | 195 |\n| 123 | Product-23 | 10000 |\n+-----------+-------------+--------------+\n23 rows in set (0.00 sec)" }, { "code": null, "e": 5493, "s": 5415, "text": "Here is the query to select last 20 records from the table in ascending order" }, { "code": null, "e": 5630, "s": 5493, "text": "mysql> select *from\n -> (\n -> select *from ProductInformation order by ProductId desc limit 20\n -> ) t1 order by t1.ProductId asc;" }, { "code": null, "e": 5658, "s": 5630, "text": "The following is the output" }, { "code": null, "e": 6716, "s": 5658, "text": "+-----------+-------------+--------------+\n| ProductId | ProductName | ProductPrice |\n+-----------+-------------+--------------+\n| 104 | Product-4 | 100 |\n| 105 | Product-5 | 1500 |\n| 106 | Product-6 | 1200 |\n| 107 | Product-7 | 1300 |\n| 108 | Product-8 | 1600 |\n| 109 | Product-9 | 1250 |\n| 110 | Product-10 | 1900 |\n| 111 | Product-11 | 1870 |\n| 112 | Product-12 | 1876 |\n| 113 | Product-13 | 1869 |\n| 114 | Product-14 | 1456 |\n| 115 | Product-15 | 1860 |\n| 116 | Product-16 | 359 |\n| 117 | Product-17 | 1667 |\n| 118 | Product-18 | 1467 |\n| 119 | Product-19 | 2134 |\n| 120 | Product-20 | 3450 |\n| 121 | Product-21 | 198 |\n| 122 | Product-22 | 195 |\n| 123 | Product-23 | 10000 |\n+-----------+-------------+--------------+\n20 rows in set (0.00 sec)" }, { "code": null, "e": 6835, "s": 6716, "text": "If you want the records in descending order, then use desc. The query is as follows to get result in descending order." }, { "code": null, "e": 6973, "s": 6835, "text": "mysql> select *from\n -> (\n -> select *from ProductInformation order by ProductId desc limit 20\n -> ) t2 order by t2.ProductId desc;" }, { "code": null, "e": 7001, "s": 6973, "text": "The following is the output" }, { "code": null, "e": 8059, "s": 7001, "text": "+-----------+-------------+--------------+\n| ProductId | ProductName | ProductPrice |\n+-----------+-------------+--------------+\n| 123 | Product-23 | 10000 |\n| 122 | Product-22 | 195 |\n| 121 | Product-21 | 198 |\n| 120 | Product-20 | 3450 |\n| 119 | Product-19 | 2134 |\n| 118 | Product-18 | 1467 |\n| 117 | Product-17 | 1667 |\n| 116 | Product-16 | 359 |\n| 115 | Product-15 | 1860 |\n| 114 | Product-14 | 1456 |\n| 113 | Product-13 | 1869 |\n| 112 | Product-12 | 1876 |\n| 111 | Product-11 | 1870 |\n| 110 | Product-10 | 1900 |\n| 109 | Product-9 | 1250 |\n| 108 | Product-8 | 1600 |\n| 107 | Product-7 | 1300 |\n| 106 | Product-6 | 1200 |\n| 105 | Product-5 | 1500 |\n| 104 | Product-4 | 100 |\n+-----------+-------------+--------------+\n20 rows in set (0.00 sec)" } ]
How to use the GetValue() method of array class in C#?
The GetValue() method of array class in C# gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer. We have set the array values first using the Array.CreateInstance method. Array arr = Array.CreateInstance(typeof(String), 3, 6); arr.SetValue("One", 0, 0); arr.SetValue("Two", 0, 1); arr.SetValue("Three", 0, 2); arr.SetValue("Four", 0, 3); arr.SetValue("Five", 1, 4); arr.SetValue("Six", 1, 5); arr.SetValue("Seven", 1, 2); arr.SetValue("Eight", 1, 3); Then loop throught the array length. This will display all the values using the GetValue() method. for (int i = 0; i < a; i++) for (int j = 0; j < b; j++) Console.WriteLine( arr.GetValue(i, j)); Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo { class Program { static void Main(string[] args) { Array arr = Array.CreateInstance(typeof(String), 3, 6); arr.SetValue("One", 0, 0); arr.SetValue("Two", 0, 1); arr.SetValue("Three", 0, 2); arr.SetValue("Four", 0, 3); arr.SetValue("Five", 1, 4); arr.SetValue("Six", 1, 5); arr.SetValue("Seven", 1, 2); arr.SetValue("Eight", 1, 3); int a = arr.GetLength(0); int b = arr.GetLength(1); // Getting values for (int i = 0; i <a; i++) for (int j = 0; j < b; j++) Console.WriteLine( arr.GetValue(i, j)); Console.ReadLine(); } } } One Two Three Four Seven Eight Five Six
[ { "code": null, "e": 1220, "s": 1062, "text": "The GetValue() method of array class in C# gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer." }, { "code": null, "e": 1294, "s": 1220, "text": "We have set the array values first using the Array.CreateInstance method." }, { "code": null, "e": 1574, "s": 1294, "text": "Array arr = Array.CreateInstance(typeof(String), 3, 6);\narr.SetValue(\"One\", 0, 0);\narr.SetValue(\"Two\", 0, 1);\narr.SetValue(\"Three\", 0, 2);\narr.SetValue(\"Four\", 0, 3);\narr.SetValue(\"Five\", 1, 4);\narr.SetValue(\"Six\", 1, 5);\narr.SetValue(\"Seven\", 1, 2);\narr.SetValue(\"Eight\", 1, 3);" }, { "code": null, "e": 1673, "s": 1574, "text": "Then loop throught the array length. This will display all the values using the GetValue() method." }, { "code": null, "e": 1769, "s": 1673, "text": "for (int i = 0; i < a; i++)\nfor (int j = 0; j < b; j++)\nConsole.WriteLine( arr.GetValue(i, j));" }, { "code": null, "e": 1780, "s": 1769, "text": " Live Demo" }, { "code": null, "e": 2566, "s": 1780, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n Array arr = Array.CreateInstance(typeof(String), 3, 6);\n arr.SetValue(\"One\", 0, 0);\n arr.SetValue(\"Two\", 0, 1);\n arr.SetValue(\"Three\", 0, 2);\n arr.SetValue(\"Four\", 0, 3);\n arr.SetValue(\"Five\", 1, 4);\n arr.SetValue(\"Six\", 1, 5);\n arr.SetValue(\"Seven\", 1, 2);\n arr.SetValue(\"Eight\", 1, 3);\n int a = arr.GetLength(0);\n int b = arr.GetLength(1);\n // Getting values\n for (int i = 0; i <a; i++)\n for (int j = 0; j < b; j++)\n Console.WriteLine( arr.GetValue(i, j));\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2607, "s": 2566, "text": "One\nTwo\nThree\nFour\n\nSeven\nEight\nFive\nSix" } ]
Angular 6 - Templates
Angular 6 uses the <ng-template> as the tag similar to Angular 4 instead of <template> which is used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because there is a name conflict between the <template> tag and the html <template> standard tag. It will deprecate completely going ahead. Let us now use the template along with the if else condition and see the output. <!--The content below is only a placeholder and can be replaced.--> <div style = "text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select (change) = "changemonths($event)" name = "month"> <option *ngFor = "let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf = "isavailable;then condition1 else condition2">Condition is valid.</span> <ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template> </div> <button (click) = "myClickFunction($event)">Click Me</button> For the Span tag, we have added the if statement with the else condition and will call template condition1, else condition2. The templates are to be called as follows − <ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template> If the condition is true, then the condition1 template is called, otherwise condition2. import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 6 Project!'; //array of months. months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = false; myClickFunction(event) { this.isavailable = false; } changemonths(event) { alert("Changed month from the Dropdown"); console.log(event); } } The output in the browser is as follows − The variable isavailable is false so the condition2 template is printed. If you click the button, the respective template will be called. If you inspect the browser, you will see that you never get the span tag in the dom. The following example will help you understand the same. If you inspect the browser, you will see that the dom does not have the span tag. It has the Condition is invalid from template in the dom. The following line of code in html will help us get the span tag in the dom. <!--The content below is only a placeholder and can be replaced.--> <div style = "text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select (change) = "changemonths($event)" name = "month"> <option *ngFor = "let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf = "isavailable; else condition2">Condition is valid.</span> <ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template> </div> <button (click)="myClickFunction($event)">Click Me</button> If we remove the then condition, we get the "Condition is valid" message in the browser and the span tag is also available in the dom. For example, in app.component.ts, we have made the isavailable variable as true. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2309, "s": 1995, "text": "Angular 6 uses the <ng-template> as the tag similar to Angular 4 instead of <template> which is used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because there is a name conflict between the <template> tag and the html <template> standard tag. It will deprecate completely going ahead." }, { "code": null, "e": 2390, "s": 2309, "text": "Let us now use the template along with the if else condition and see the output." }, { "code": null, "e": 3019, "s": 2390, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n<div> Months :\n <select (change) = \"changemonths($event)\" name = \"month\">\n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n<div>\n <span *ngIf = \"isavailable;then condition1 else condition2\">Condition is valid.</span>\n <ng-template #condition1>Condition is valid from template</ng-template>\n <ng-template #condition2>Condition is invalid from template</ng-template>\n</div>\n<button (click) = \"myClickFunction($event)\">Click Me</button>" }, { "code": null, "e": 3144, "s": 3019, "text": "For the Span tag, we have added the if statement with the else condition and will call template condition1, else condition2." }, { "code": null, "e": 3188, "s": 3144, "text": "The templates are to be called as follows −" }, { "code": null, "e": 3335, "s": 3188, "text": "<ng-template #condition1>Condition is valid from template</ng-template>\n<ng-template #condition2>Condition is invalid from template</ng-template>\n" }, { "code": null, "e": 3423, "s": 3335, "text": "If the condition is true, then the condition1 template is called, otherwise condition2." }, { "code": null, "e": 4011, "s": 3423, "text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 6 Project!';\n //array of months.\n months = [\"January\", \"February\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n isavailable = false;\n myClickFunction(event) {\n this.isavailable = false;\n }\n changemonths(event) {\n alert(\"Changed month from the Dropdown\");\n console.log(event);\n }\n}" }, { "code": null, "e": 4053, "s": 4011, "text": "The output in the browser is as follows −" }, { "code": null, "e": 4333, "s": 4053, "text": "The variable isavailable is false so the condition2 template is printed. If you click the button, the respective template will be called. If you inspect the browser, you will see that you never get the span tag in the dom. The following example will help you understand the same." }, { "code": null, "e": 4473, "s": 4333, "text": "If you inspect the browser, you will see that the dom does not have the span tag. It has the Condition is invalid from template in the dom." }, { "code": null, "e": 4550, "s": 4473, "text": "The following line of code in html will help us get the span tag in the dom." }, { "code": null, "e": 5162, "s": 4550, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n<div> Months :\n <select (change) = \"changemonths($event)\" name = \"month\">\n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n<div>\n <span *ngIf = \"isavailable; else condition2\">Condition is valid.</span>\n <ng-template #condition1>Condition is valid from template</ng-template>\n <ng-template #condition2>Condition is invalid from template</ng-template>\n</div>\n<button (click)=\"myClickFunction($event)\">Click Me</button>" }, { "code": null, "e": 5378, "s": 5162, "text": "If we remove the then condition, we get the \"Condition is valid\" message in the browser and the span tag is also available in the dom. For example, in app.component.ts, we have made the isavailable variable as true." }, { "code": null, "e": 5413, "s": 5378, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5427, "s": 5413, "text": " Anadi Sharma" }, { "code": null, "e": 5462, "s": 5427, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5476, "s": 5462, "text": " Anadi Sharma" }, { "code": null, "e": 5511, "s": 5476, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5531, "s": 5511, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 5566, "s": 5531, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5583, "s": 5566, "text": " Frahaan Hussain" }, { "code": null, "e": 5616, "s": 5583, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 5628, "s": 5616, "text": " Senol Atac" }, { "code": null, "e": 5663, "s": 5628, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5675, "s": 5663, "text": " Senol Atac" }, { "code": null, "e": 5682, "s": 5675, "text": " Print" }, { "code": null, "e": 5693, "s": 5682, "text": " Add Notes" } ]
Downloading historical stock prices in Python | by Rohan Joseph | Towards Data Science
Open up a notebook and follow along: What we need is pandas (the bread and butter for data science in python), yfinance for downloading the historical stock prices from yahoo finance, datetime and time which provides functions to manipulate dates and times, requests for sending HTTP requests and io for handling strings. import pandas as pdimport yfinance as yfimport datetimeimport timeimport requestsimport io Next, we want to provide the start and end dates, during which period we want the daily stock prices. Below, I have provided the start date as 1st February 2020 (approximate beginning of this year’s misery) and end date as 11th October 2020, the current date when I executed this code. You could set the start and end date to anything you like- but what I am trying to analyze is the price fluctuation from pre-pandemic times till now. start = datetime.datetime(2020,2,1)end = datetime.datetime(2020,10,11) We want to get the stock ticker symbols listed on NASDAQ. You can skip this step if you know exactly the companies you want the historical stock prices for (example: Tesla -> TSLA, Facebook -> FB etc). But the idea here is to look beyond the popular companies and unearth some interesting price movements for the not-so-well-known companies. The code below would access the URL containing a CSV file with the company names and their stock symbol, and convert it to a pandas dataframe. url="https://pkgstore.datahub.io/core/nasdaq-listings/nasdaq-listed_csv/data/7665719fb51081ba0bd834fde71ce822/nasdaq-listed_csv.csv"s = requests.get(url).contentcompanies = pd.read_csv(io.StringIO(s.decode('utf-8'))) Some of the companies provided in this dataset may be delisted or may not be available to download. Let’s take a look at how this dataset looks like: From this dataset, let’s extract only the Symbols and convert them into a list. Symbols = companies['Symbol'].tolist() Iterate over each stock symbol and using yahoo finance API, download the daily stock prices between the start and end dates. Append all the individual stock info and create the analytical dataset. Also, note that some symbols may be unavailable to download, for which we have added the ‘try’ and ‘except’ clauses to handle them. # create empty dataframestock_final = pd.DataFrame()# iterate over each symbolfor i in Symbols: # print the symbol which is being downloaded print( str(Symbols.index(i)) + str(' : ') + i, sep=',', end=',', flush=True) try: # download the stock price stock = [] stock = yf.download(i,start=start, end=end, progress=False) # append the individual stock prices if len(stock) == 0: None else: stock['Name']=i stock_final = stock_final.append(stock,sort=False) except Exception: None This is how the final dataset looks like. stock_final.head() Voila! For each stock symbol and date, we have the opening, high, low and closing and adjusted closing price, along with the volume traded. This article covers the first step of stock market analysis which is creating the analytical dataset. The next step would be diving further into this dataset to through exploratory data analysis, and machine learning models. Connect on LinkedIn and find notebook on Github.
[ { "code": null, "e": 209, "s": 172, "text": "Open up a notebook and follow along:" }, { "code": null, "e": 494, "s": 209, "text": "What we need is pandas (the bread and butter for data science in python), yfinance for downloading the historical stock prices from yahoo finance, datetime and time which provides functions to manipulate dates and times, requests for sending HTTP requests and io for handling strings." }, { "code": null, "e": 585, "s": 494, "text": "import pandas as pdimport yfinance as yfimport datetimeimport timeimport requestsimport io" }, { "code": null, "e": 1021, "s": 585, "text": "Next, we want to provide the start and end dates, during which period we want the daily stock prices. Below, I have provided the start date as 1st February 2020 (approximate beginning of this year’s misery) and end date as 11th October 2020, the current date when I executed this code. You could set the start and end date to anything you like- but what I am trying to analyze is the price fluctuation from pre-pandemic times till now." }, { "code": null, "e": 1092, "s": 1021, "text": "start = datetime.datetime(2020,2,1)end = datetime.datetime(2020,10,11)" }, { "code": null, "e": 1434, "s": 1092, "text": "We want to get the stock ticker symbols listed on NASDAQ. You can skip this step if you know exactly the companies you want the historical stock prices for (example: Tesla -> TSLA, Facebook -> FB etc). But the idea here is to look beyond the popular companies and unearth some interesting price movements for the not-so-well-known companies." }, { "code": null, "e": 1577, "s": 1434, "text": "The code below would access the URL containing a CSV file with the company names and their stock symbol, and convert it to a pandas dataframe." }, { "code": null, "e": 1794, "s": 1577, "text": "url=\"https://pkgstore.datahub.io/core/nasdaq-listings/nasdaq-listed_csv/data/7665719fb51081ba0bd834fde71ce822/nasdaq-listed_csv.csv\"s = requests.get(url).contentcompanies = pd.read_csv(io.StringIO(s.decode('utf-8')))" }, { "code": null, "e": 1894, "s": 1794, "text": "Some of the companies provided in this dataset may be delisted or may not be available to download." }, { "code": null, "e": 1944, "s": 1894, "text": "Let’s take a look at how this dataset looks like:" }, { "code": null, "e": 2024, "s": 1944, "text": "From this dataset, let’s extract only the Symbols and convert them into a list." }, { "code": null, "e": 2063, "s": 2024, "text": "Symbols = companies['Symbol'].tolist()" }, { "code": null, "e": 2188, "s": 2063, "text": "Iterate over each stock symbol and using yahoo finance API, download the daily stock prices between the start and end dates." }, { "code": null, "e": 2392, "s": 2188, "text": "Append all the individual stock info and create the analytical dataset. Also, note that some symbols may be unavailable to download, for which we have added the ‘try’ and ‘except’ clauses to handle them." }, { "code": null, "e": 2987, "s": 2392, "text": "# create empty dataframestock_final = pd.DataFrame()# iterate over each symbolfor i in Symbols: # print the symbol which is being downloaded print( str(Symbols.index(i)) + str(' : ') + i, sep=',', end=',', flush=True) try: # download the stock price stock = [] stock = yf.download(i,start=start, end=end, progress=False) # append the individual stock prices if len(stock) == 0: None else: stock['Name']=i stock_final = stock_final.append(stock,sort=False) except Exception: None" }, { "code": null, "e": 3029, "s": 2987, "text": "This is how the final dataset looks like." }, { "code": null, "e": 3048, "s": 3029, "text": "stock_final.head()" }, { "code": null, "e": 3188, "s": 3048, "text": "Voila! For each stock symbol and date, we have the opening, high, low and closing and adjusted closing price, along with the volume traded." }, { "code": null, "e": 3413, "s": 3188, "text": "This article covers the first step of stock market analysis which is creating the analytical dataset. The next step would be diving further into this dataset to through exploratory data analysis, and machine learning models." } ]
How do I pass environment variables to Docker containers?
Suppose you are using a MySQL Docker container and you want to pass environment variables to your container while running the container. It’s always a good idea to isolate the services from the configuration and it’s always advised to use environment variables for this purpose. Predominantly, there are three different ways through which we can pass environment variables to our Docker containers. These are by using the -e, --env-file, and the ENV instruction inside the Dockerfile. Let’s check out all these methods one by one with examples. To demonstrate this example, let’s use the alpine image by pulling it from Dockerhub. $ docker pull alpine:latest We can use the --env or it’s shorthand version -e to pass the environment variables as key-value pairs through the Docker run command. The syntax of the Docker run command is - $ docker run [OPTIONS] IMAGE [COMMAND] [ARG...] Let’s use this syntax to run a container associated with the alpine image and pass our environment variables using the -e flag. $ docker run -it --name=myalpine --env ENVVARIABLE1=foobar alpine:latest bash This command uses the -i and -t options to run the container interactively and open the bash. The --name option is used to give a name to the container. The --env option is used to pass the environment variable called ENVVARIABLE with a value foobar to the container. Now you have access to the bash of the container. Inside the bash, execute the env command. This will list all the environment variables of the container. # env Moreover, if you already have an environment variable in your local machine and you want to pass this environment variable to the container, you can omit the value of the variable. $ docker run -it --name=myalpine --env VARIABLE2 alpine:latest env This will directly set the environment variable called VARIABLE2 by taking it’s value from the local machine. If you want to pass a limited number of environment variables to the container, you can use the previous method. However, if the number of the environment variables to be passed is large, you can store the variables in the text file in key-value format and pass the name of this file using the --env-file option in the Docker run command. It will automatically read and import these variables from the mentioned file. Create a file called env.txt with the following content. ENV1 = VALUE1 ENV2 = VALUE2 ENV3 = VALUE3 Now, you can use the following command to create a container called myalpine and pass the environment variables from this file using the --env-file option. $ docker run -it --name=myalpine --env-file env.txt alpine:latest env Please note that the file must exist in the same path where you are executing this command in your local machine. If not, mention the full path of the file. This command will list all the environment variables in the container and you will find the ones mentioned in the env.txt file as well. If you are trying to build an image using the Dockerfile, you can pass the environment variables using the ENV instruction. The syntax of this instruction is - ENV <key> = <value> ... The values that you pass will be the environment variables for all the subsequent instructions in your Dockerfile. Examples are - ENV MY_NAME="Jane Anniston" ENV MY_PET=The\ Dog ENV MY_CAT=TOMMY Similar to command line parsing, you will have to escape quotes and spaces using backslashes. All the environment variables will persist throughout the container lifecycle. If you want to pass only a single environment variable with one ENV instruction, you can also omit the equal operator. To sum up, in this article, we saw three different ways to pass environment variables to a container. These were the -e or --env and --env-file options as well as using the ENV instruction while creating images using a Dockerfile. Based on your requirements, you can use any of these methods. Also, please make sure that you do not pass any sensitive information such as passwords, passphrases, etc as they might lead to the leak of sensitive information and might affect your entire application or image.
[ { "code": null, "e": 1341, "s": 1062, "text": "Suppose you are using a MySQL Docker container and you want to pass environment variables to your container while running the container. It’s always a good idea to isolate the services from the configuration and it’s always advised to use environment variables for this purpose." }, { "code": null, "e": 1607, "s": 1341, "text": "Predominantly, there are three different ways through which we can pass environment variables to our Docker containers. These are by using the -e, --env-file, and the ENV instruction inside the Dockerfile. Let’s check out all these methods one by one with examples." }, { "code": null, "e": 1693, "s": 1607, "text": "To demonstrate this example, let’s use the alpine image by pulling it from Dockerhub." }, { "code": null, "e": 1721, "s": 1693, "text": "$ docker pull alpine:latest" }, { "code": null, "e": 1898, "s": 1721, "text": "We can use the --env or it’s shorthand version -e to pass the environment variables as key-value pairs through the Docker run command. The syntax of the Docker run command is -" }, { "code": null, "e": 1946, "s": 1898, "text": "$ docker run [OPTIONS] IMAGE [COMMAND] [ARG...]" }, { "code": null, "e": 2074, "s": 1946, "text": "Let’s use this syntax to run a container associated with the alpine image and pass our environment variables using the -e flag." }, { "code": null, "e": 2152, "s": 2074, "text": "$ docker run -it --name=myalpine --env ENVVARIABLE1=foobar alpine:latest bash" }, { "code": null, "e": 2420, "s": 2152, "text": "This command uses the -i and -t options to run the container interactively and open the bash. The --name option is used to give a name to the container. The --env option is used to pass the environment variable called ENVVARIABLE with a value foobar to the container." }, { "code": null, "e": 2575, "s": 2420, "text": "Now you have access to the bash of the container. Inside the bash, execute the env command. This will list all the environment variables of the container." }, { "code": null, "e": 2582, "s": 2575, "text": "# env\n" }, { "code": null, "e": 2763, "s": 2582, "text": "Moreover, if you already have an environment variable in your local machine and you want to pass this environment variable to the container, you can omit the value of the variable." }, { "code": null, "e": 2830, "s": 2763, "text": "$ docker run -it --name=myalpine --env VARIABLE2 alpine:latest env" }, { "code": null, "e": 2940, "s": 2830, "text": "This will directly set the environment variable called VARIABLE2 by taking it’s value from the local machine." }, { "code": null, "e": 3358, "s": 2940, "text": "If you want to pass a limited number of environment variables to the container, you can use the previous method. However, if the number of the environment variables to be passed is large, you can store the variables in the text file in key-value format and pass the name of this file using the --env-file option in the Docker run command. It will automatically read and import these variables from the mentioned file." }, { "code": null, "e": 3415, "s": 3358, "text": "Create a file called env.txt with the following content." }, { "code": null, "e": 3457, "s": 3415, "text": "ENV1 = VALUE1\nENV2 = VALUE2\nENV3 = VALUE3" }, { "code": null, "e": 3613, "s": 3457, "text": "Now, you can use the following command to create a container called myalpine and pass the environment variables from this file using the --env-file option." }, { "code": null, "e": 3683, "s": 3613, "text": "$ docker run -it --name=myalpine --env-file env.txt alpine:latest env" }, { "code": null, "e": 3976, "s": 3683, "text": "Please note that the file must exist in the same path where you are executing this command in your local machine. If not, mention the full path of the file. This command will list all the environment variables in the container and you will find the ones mentioned in the env.txt file as well." }, { "code": null, "e": 4136, "s": 3976, "text": "If you are trying to build an image using the Dockerfile, you can pass the environment variables using the ENV instruction. The syntax of this instruction is -" }, { "code": null, "e": 4160, "s": 4136, "text": "ENV <key> = <value> ..." }, { "code": null, "e": 4290, "s": 4160, "text": "The values that you pass will be the environment variables for all the subsequent instructions in your Dockerfile. Examples are -" }, { "code": null, "e": 4355, "s": 4290, "text": "ENV MY_NAME=\"Jane Anniston\"\nENV MY_PET=The\\ Dog\nENV MY_CAT=TOMMY" }, { "code": null, "e": 4647, "s": 4355, "text": "Similar to command line parsing, you will have to escape quotes and spaces using backslashes. All the environment variables will persist throughout the container lifecycle. If you want to pass only a single environment variable with one ENV instruction, you can also omit the equal operator." }, { "code": null, "e": 5153, "s": 4647, "text": "To sum up, in this article, we saw three different ways to pass environment variables to a container. These were the -e or --env and --env-file options as well as using the ENV instruction while creating images using a Dockerfile. Based on your requirements, you can use any of these methods. Also, please make sure that you do not pass any sensitive information such as passwords, passphrases, etc as they might lead to the leak of sensitive information and might affect your entire application or image." } ]
Sum of cubes of even and odd natural numbers - GeeksforGeeks
09 Oct, 2018 We know that sum of cubes of first n natural numbers is = (n(n+1)/2)2. Sum of cube of first n even natural numbers23 + 43 + 63 + ......... + (2n)3 Even Sum = 23 + 43 + 63 + .... + (2n)3 if we multiply by 23 then = 23 x (13 + 23 + 32 + .... + (n)3) = 23 + 43 + 63 + ......... + (2n)3 = 23 (n(n+1)/2)2 = 8(n(n+1))2/4 = 2(n(n+1))2 Example : Sum of cube of first 4 even numbers = 23 + 43 + 63 + 83 put n = 4 = 2(n(n+1))2 = 2*(4*(4+1))2 = 2(4*5)2 = 2(20)2 = 800 8 + 64 + 256 + 512 = 800 Program for Sum of cubes of first n even numbers Sum of cube of first n odd natural numbersWe need to compute 13 + 33 + 53 + .... + (2n-1)3 OddSum = (Sum of cubes of all 2n numbers) - (Sum of cubes of first n even numbers) = (2n(2n+1)/2)2 - 2(n(n+1))2 = n2(2n+1)2 - 2* n2(n+1)2 = n2[(2n+1)2 - 2*(n+1)2] = n2[4n2 + 1 + 4n - 2n2 - 2 - 4n] = n2(2n2 - 1) Example : Sum of cube of first 4 odd numbers = 13 + 33 + 53 + 73 put n = 4 = n2(2n2 - 1) = 42(2*(4)2 - 1) = 16(32-1) = 496 1 + 27 + 125 + 343 = 496 Program for Sum of cubes of first n odd numbers maths-cube series series-sum Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find GCD or HCF of two numbers Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ Sieve of Eratosthenes Euclidean algorithms (Basic and Extended) Algorithm to solve Rubik's Cube
[ { "code": null, "e": 25062, "s": 25034, "text": "\n09 Oct, 2018" }, { "code": null, "e": 25133, "s": 25062, "text": "We know that sum of cubes of first n natural numbers is = (n(n+1)/2)2." }, { "code": null, "e": 25209, "s": 25133, "text": "Sum of cube of first n even natural numbers23 + 43 + 63 + ......... + (2n)3" }, { "code": null, "e": 25443, "s": 25209, "text": "Even Sum = 23 + 43 + 63 + .... + (2n)3\n if we multiply by 23 then \n = 23 x (13 + 23 + 32 + .... + (n)3)\n = 23 + 43 + 63 + ......... + (2n)3\n = 23 (n(n+1)/2)2\n = 8(n(n+1))2/4\n = 2(n(n+1))2\n" }, { "code": null, "e": 25453, "s": 25443, "text": "Example :" }, { "code": null, "e": 25665, "s": 25453, "text": "Sum of cube of first 4 even numbers = 23 + 43 + 63 + 83 \n put n = 4 = 2(n(n+1))2\n = 2*(4*(4+1))2\n = 2(4*5)2\n = 2(20)2\n = 800\n 8 + 64 + 256 + 512 = 800\n" }, { "code": null, "e": 25714, "s": 25665, "text": "Program for Sum of cubes of first n even numbers" }, { "code": null, "e": 25806, "s": 25714, "text": " Sum of cube of first n odd natural numbersWe need to compute 13 + 33 + 53 + .... + (2n-1)3" }, { "code": null, "e": 26071, "s": 25806, "text": "OddSum = (Sum of cubes of all 2n numbers) - (Sum of cubes of first n even numbers)\n = (2n(2n+1)/2)2 - 2(n(n+1))2 \n = n2(2n+1)2 - 2* n2(n+1)2\n = n2[(2n+1)2 - 2*(n+1)2]\n = n2[4n2 + 1 + 4n - 2n2 - 2 - 4n]\n = n2(2n2 - 1)\n" }, { "code": null, "e": 26081, "s": 26071, "text": "Example :" }, { "code": null, "e": 26273, "s": 26081, "text": "Sum of cube of first 4 odd numbers = 13 + 33 + 53 + 73 \n put n = 4 = n2(2n2 - 1)\n = 42(2*(4)2 - 1)\n = 16(32-1)\n = 496\n 1 + 27 + 125 + 343 = 496\n" }, { "code": null, "e": 26321, "s": 26273, "text": "Program for Sum of cubes of first n odd numbers" }, { "code": null, "e": 26332, "s": 26321, "text": "maths-cube" }, { "code": null, "e": 26339, "s": 26332, "text": "series" }, { "code": null, "e": 26350, "s": 26339, "text": "series-sum" }, { "code": null, "e": 26363, "s": 26350, "text": "Mathematical" }, { "code": null, "e": 26376, "s": 26363, "text": "Mathematical" }, { "code": null, "e": 26383, "s": 26376, "text": "series" }, { "code": null, "e": 26481, "s": 26383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26490, "s": 26481, "text": "Comments" }, { "code": null, "e": 26503, "s": 26490, "text": "Old Comments" }, { "code": null, "e": 26545, "s": 26503, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 26569, "s": 26545, "text": "Merge two sorted arrays" }, { "code": null, "e": 26612, "s": 26569, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 26626, "s": 26612, "text": "Prime Numbers" }, { "code": null, "e": 26675, "s": 26626, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 26709, "s": 26675, "text": "Program for factorial of a number" }, { "code": null, "e": 26730, "s": 26709, "text": "Operators in C / C++" }, { "code": null, "e": 26752, "s": 26730, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 26794, "s": 26752, "text": "Euclidean algorithms (Basic and Extended)" } ]
Python 3 - Tkinter Radiobutton
This widget implements a multiple-choice button, which is a way to offer many possible selections to the user and lets user choose only one of them. In order to implement this functionality, each group of radiobuttons must be associated to the same variable and each one of the buttons must symbolize a single value. You can use the Tab key to switch from one radionbutton to another. Here is the simple syntax to create this widget − w = Radiobutton ( master, option, ... ) master − This represents the parent window. master − This represents the parent window. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. activebackground The background color when the mouse is over the radiobutton. activeforeground The foreground color when the mouse is over the radiobutton. anchor If the widget inhabits a space larger than it needs, this option specifies where the radiobutton will sit in that space. The default is anchor = CENTER. bg The normal background color behind the indicator and label. bitmap To display a monochrome image on a radiobutton, set this option to a bitmap. borderwidth The size of the border around the indicator part itself. Default is 2 pixels. command A procedure to be called every time the user changes the state of this radiobutton. cursor If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the radiobutton. font The font used for the text. fg The color used to render the text. height The number of lines (not pixels) of text on the radiobutton. Default is 1. highlightbackground The color of the focus highlight when the radiobutton does not have focus. highlightcolor The color of the focus highlight when the radiobutton has the focus. image To display a graphic image instead of text for this radiobutton, set this option to an image object. justify If the text contains multiple lines, this option controls how the text is justified: CENTER (the default), LEFT, or RIGHT. padx How much space to leave to the left and right of the radiobutton and text. Default is 1. pady How much space to leave above and below the radiobutton and text. Default is 1. relief Specifies the appearance of a decorative border around the label. The default is FLAT; for other values. selectcolor The color of the radiobutton when it is set. Default is red. selectimage If you are using the image option to display a graphic instead of text when the radiobutton is cleared, you can set the selectimage option to a different image that will be displayed when the radiobutton is set. state The default is state = NORMAL, but you can set state = DISABLED to gray out the control and make it unresponsive. If the cursor is currently over the radiobutton, the state is ACTIVE. text The label displayed next to the radiobutton. Use newlines ("\n") to display multiple lines of text. textvariable To slave the text displayed in a label widget to a control variable of class StringVar, set this option to that variable. underline You can display an underline (_) below the nth letter of the text, counting from 0, by setting this option to n. The default is underline = -1, which means no underlining. value When a radiobutton is turned on by the user, its control variable is set to its current value option. If the control variable is an IntVar, give each radiobutton in the group a different integer value option. If the control variable is a StringVar, give each radiobutton a different string value option. variable The control variable that this radiobutton shares with the other radiobuttons in the group. This can be either an IntVar or a StringVar. width Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its contents. wraplength You can limit the number of characters in each line by setting this option to the desired number. The default value, 0, means that lines will be broken only at newlines. deselect() Clears (turns off) the radiobutton. flash() Flashes the radiobutton a few times between its active and normal colors, but leaves it the way it started. invoke() You can call this method to get the same actions that would occur if the user clicked on the radiobutton to change its state. select() Sets (turns on) the radiobutton. Try the following example yourself − # !/usr/bin/python3 from tkinter import * def sel(): selection = "You selected the option " + str(var.get()) label.config(text = selection) root = Tk() var = IntVar() R1 = Radiobutton(root, text = "Option 1", variable = var, value = 1, command = sel) R1.pack( anchor = W ) R2 = Radiobutton(root, text = "Option 2", variable = var, value = 2, command = sel) R2.pack( anchor = W ) R3 = Radiobutton(root, text = "Option 3", variable = var, value = 3, command = sel) R3.pack( anchor = W) label = Label(root) label.pack() root.mainloop() When the above code is executed, it produces the following result − 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": 2489, "s": 2340, "text": "This widget implements a multiple-choice button, which is a way to offer many possible selections to the user and lets user choose only one of them." }, { "code": null, "e": 2725, "s": 2489, "text": "In order to implement this functionality, each group of radiobuttons must be associated to the same variable and each one of the buttons must symbolize a single value. You can use the Tab key to switch from one radionbutton to another." }, { "code": null, "e": 2775, "s": 2725, "text": "Here is the simple syntax to create this widget −" }, { "code": null, "e": 2817, "s": 2775, "text": "w = Radiobutton ( master, option, ... )\n" }, { "code": null, "e": 2861, "s": 2817, "text": "master − This represents the parent window." }, { "code": null, "e": 2905, "s": 2861, "text": "master − This represents the parent window." }, { "code": null, "e": 3045, "s": 2905, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 3185, "s": 3045, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 3202, "s": 3185, "text": "activebackground" }, { "code": null, "e": 3263, "s": 3202, "text": "The background color when the mouse is over the radiobutton." }, { "code": null, "e": 3280, "s": 3263, "text": "activeforeground" }, { "code": null, "e": 3341, "s": 3280, "text": "The foreground color when the mouse is over the radiobutton." }, { "code": null, "e": 3348, "s": 3341, "text": "anchor" }, { "code": null, "e": 3501, "s": 3348, "text": "If the widget inhabits a space larger than it needs, this option specifies where the radiobutton will sit in that space. The default is anchor = CENTER." }, { "code": null, "e": 3504, "s": 3501, "text": "bg" }, { "code": null, "e": 3564, "s": 3504, "text": "The normal background color behind the indicator and label." }, { "code": null, "e": 3571, "s": 3564, "text": "bitmap" }, { "code": null, "e": 3648, "s": 3571, "text": "To display a monochrome image on a radiobutton, set this option to a bitmap." }, { "code": null, "e": 3660, "s": 3648, "text": "borderwidth" }, { "code": null, "e": 3738, "s": 3660, "text": "The size of the border around the indicator part itself. Default is 2 pixels." }, { "code": null, "e": 3746, "s": 3738, "text": "command" }, { "code": null, "e": 3830, "s": 3746, "text": "A procedure to be called every time the user changes the state of this radiobutton." }, { "code": null, "e": 3837, "s": 3830, "text": "cursor" }, { "code": null, "e": 3974, "s": 3837, "text": "If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the radiobutton." }, { "code": null, "e": 3979, "s": 3974, "text": "font" }, { "code": null, "e": 4007, "s": 3979, "text": "The font used for the text." }, { "code": null, "e": 4010, "s": 4007, "text": "fg" }, { "code": null, "e": 4045, "s": 4010, "text": "The color used to render the text." }, { "code": null, "e": 4052, "s": 4045, "text": "height" }, { "code": null, "e": 4127, "s": 4052, "text": "The number of lines (not pixels) of text on the radiobutton. Default is 1." }, { "code": null, "e": 4147, "s": 4127, "text": "highlightbackground" }, { "code": null, "e": 4222, "s": 4147, "text": "The color of the focus highlight when the radiobutton does not have focus." }, { "code": null, "e": 4237, "s": 4222, "text": "highlightcolor" }, { "code": null, "e": 4306, "s": 4237, "text": "The color of the focus highlight when the radiobutton has the focus." }, { "code": null, "e": 4312, "s": 4306, "text": "image" }, { "code": null, "e": 4413, "s": 4312, "text": "To display a graphic image instead of text for this radiobutton, set this option to an image object." }, { "code": null, "e": 4421, "s": 4413, "text": "justify" }, { "code": null, "e": 4544, "s": 4421, "text": "If the text contains multiple lines, this option controls how the text is justified: CENTER (the default), LEFT, or RIGHT." }, { "code": null, "e": 4549, "s": 4544, "text": "padx" }, { "code": null, "e": 4638, "s": 4549, "text": "How much space to leave to the left and right of the radiobutton and text. Default is 1." }, { "code": null, "e": 4643, "s": 4638, "text": "pady" }, { "code": null, "e": 4723, "s": 4643, "text": "How much space to leave above and below the radiobutton and text. Default is 1." }, { "code": null, "e": 4730, "s": 4723, "text": "relief" }, { "code": null, "e": 4835, "s": 4730, "text": "Specifies the appearance of a decorative border around the label. The default is FLAT; for other values." }, { "code": null, "e": 4847, "s": 4835, "text": "selectcolor" }, { "code": null, "e": 4908, "s": 4847, "text": "The color of the radiobutton when it is set. Default is red." }, { "code": null, "e": 4920, "s": 4908, "text": "selectimage" }, { "code": null, "e": 5132, "s": 4920, "text": "If you are using the image option to display a graphic instead of text when the radiobutton is cleared, you can set the selectimage option to a different image that will be displayed when the radiobutton is set." }, { "code": null, "e": 5138, "s": 5132, "text": "state" }, { "code": null, "e": 5322, "s": 5138, "text": "The default is state = NORMAL, but you can set state = DISABLED to gray out the control and make it unresponsive. If the cursor is currently over the radiobutton, the state is ACTIVE." }, { "code": null, "e": 5327, "s": 5322, "text": "text" }, { "code": null, "e": 5427, "s": 5327, "text": "The label displayed next to the radiobutton. Use newlines (\"\\n\") to display multiple lines of text." }, { "code": null, "e": 5440, "s": 5427, "text": "textvariable" }, { "code": null, "e": 5562, "s": 5440, "text": "To slave the text displayed in a label widget to a control variable of class StringVar, set this option to that variable." }, { "code": null, "e": 5572, "s": 5562, "text": "underline" }, { "code": null, "e": 5744, "s": 5572, "text": "You can display an underline (_) below the nth letter of the text, counting from 0, by setting this option to n. The default is underline = -1, which means no underlining." }, { "code": null, "e": 5750, "s": 5744, "text": "value" }, { "code": null, "e": 6054, "s": 5750, "text": "When a radiobutton is turned on by the user, its control variable is set to its current value option. If the control variable is an IntVar, give each radiobutton in the group a different integer value option. If the control variable is a StringVar, give each radiobutton a different string value option." }, { "code": null, "e": 6063, "s": 6054, "text": "variable" }, { "code": null, "e": 6200, "s": 6063, "text": "The control variable that this radiobutton shares with the other radiobuttons in the group. This can be either an IntVar or a StringVar." }, { "code": null, "e": 6206, "s": 6200, "text": "width" }, { "code": null, "e": 6326, "s": 6206, "text": "Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its contents." }, { "code": null, "e": 6337, "s": 6326, "text": "wraplength" }, { "code": null, "e": 6507, "s": 6337, "text": "You can limit the number of characters in each line by setting this option to the desired number. The default value, 0, means that lines will be broken only at newlines." }, { "code": null, "e": 6518, "s": 6507, "text": "deselect()" }, { "code": null, "e": 6554, "s": 6518, "text": "Clears (turns off) the radiobutton." }, { "code": null, "e": 6562, "s": 6554, "text": "flash()" }, { "code": null, "e": 6670, "s": 6562, "text": "Flashes the radiobutton a few times between its active and normal colors, but leaves it the way it started." }, { "code": null, "e": 6679, "s": 6670, "text": "invoke()" }, { "code": null, "e": 6805, "s": 6679, "text": "You can call this method to get the same actions that would occur if the user clicked on the radiobutton to change its state." }, { "code": null, "e": 6814, "s": 6805, "text": "select()" }, { "code": null, "e": 6847, "s": 6814, "text": "Sets (turns on) the radiobutton." }, { "code": null, "e": 6884, "s": 6847, "text": "Try the following example yourself −" }, { "code": null, "e": 7482, "s": 6884, "text": "# !/usr/bin/python3\nfrom tkinter import *\n\ndef sel():\n selection = \"You selected the option \" + str(var.get())\n label.config(text = selection)\n\nroot = Tk()\nvar = IntVar()\nR1 = Radiobutton(root, text = \"Option 1\", variable = var, value = 1,\n command = sel)\nR1.pack( anchor = W )\n\nR2 = Radiobutton(root, text = \"Option 2\", variable = var, value = 2,\n command = sel)\nR2.pack( anchor = W )\n\nR3 = Radiobutton(root, text = \"Option 3\", variable = var, value = 3,\n command = sel)\nR3.pack( anchor = W)\n\nlabel = Label(root)\nlabel.pack()\nroot.mainloop()" }, { "code": null, "e": 7551, "s": 7482, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 7588, "s": 7551, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7604, "s": 7588, "text": " Malhar Lathkar" }, { "code": null, "e": 7637, "s": 7604, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 7656, "s": 7637, "text": " Arnab Chakraborty" }, { "code": null, "e": 7691, "s": 7656, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 7713, "s": 7691, "text": " In28Minutes Official" }, { "code": null, "e": 7747, "s": 7713, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 7775, "s": 7747, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7810, "s": 7775, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 7824, "s": 7810, "text": " Lets Kode It" }, { "code": null, "e": 7857, "s": 7824, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 7874, "s": 7857, "text": " Abhilash Nelson" }, { "code": null, "e": 7881, "s": 7874, "text": " Print" }, { "code": null, "e": 7892, "s": 7881, "text": " Add Notes" } ]
How to use “OR” condition in MySQL CASE expression?
Set the same condition like “OR” in a MySQL CASE expression. Let us first create a sample table. Following is the query mysql> create table caseOrConditionDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(100), -> Score int -> ); Query OK, 0 rows affected (0.49 sec) Following is the query to insert some records in the table using insert command: mysql> insert into caseOrConditionDemo(Name,Score) values('Larry',85); Query OK, 1 row affected (0.18 sec) mysql> insert into caseOrConditionDemo(Name,Score) values('Sam',74); Query OK, 1 row affected (0.20 sec) mysql> insert into caseOrConditionDemo(Name,Score) values('Mike',76); Query OK, 1 row affected (0.16 sec) mysql> insert into caseOrConditionDemo(Name,Score) values('Carol',65); Query OK, 1 row affected (0.20 sec) Following is the query to display records from the table using select command: mysql> select *from caseOrConditionDemo; This will produce the following output +----+-------+-------+ | Id | Name | Score | +----+-------+-------+ | 1 | Larry | 85 | | 2 | Sam | 74 | | 3 | Mike | 76 | | 4 | Carol | 65 | +----+-------+-------+ 4 rows in set (0.00 sec) Following is the query to use a condition like “OR” in MySQL CASE expression: mysql> select Id,Name,Score, -> case when Score > 75 then 'Better Score' -> when Score > 70 then 'Good Score' -> else 'Not Good Score' -> end as 'Performance' -> from caseOrConditionDemo; This will produce the following output +----+-------+-------+----------------+ | Id | Name | Score | Performance | +----+-------+-------+----------------+ | 1 | Larry | 85 | Better Score | | 2 | Sam | 74 | Good Score | | 3 | Mike | 76 | Better Score | | 4 | Carol | 65 | Not Good Score | +----+-------+-------+----------------+ 4 rows in set (0.04 sec)
[ { "code": null, "e": 1159, "s": 1062, "text": "Set the same condition like “OR” in a MySQL CASE expression. Let us first create a sample table." }, { "code": null, "e": 1182, "s": 1159, "text": "Following is the query" }, { "code": null, "e": 1367, "s": 1182, "text": "mysql> create table caseOrConditionDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(100),\n -> Score int\n -> );\nQuery OK, 0 rows affected (0.49 sec)" }, { "code": null, "e": 1448, "s": 1367, "text": "Following is the query to insert some records in the table using insert command:" }, { "code": null, "e": 1876, "s": 1448, "text": "mysql> insert into caseOrConditionDemo(Name,Score) values('Larry',85);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into caseOrConditionDemo(Name,Score) values('Sam',74);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into caseOrConditionDemo(Name,Score) values('Mike',76);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into caseOrConditionDemo(Name,Score) values('Carol',65);\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 1955, "s": 1876, "text": "Following is the query to display records from the table using select command:" }, { "code": null, "e": 1996, "s": 1955, "text": "mysql> select *from caseOrConditionDemo;" }, { "code": null, "e": 2035, "s": 1996, "text": "This will produce the following output" }, { "code": null, "e": 2244, "s": 2035, "text": "+----+-------+-------+\n| Id | Name | Score |\n+----+-------+-------+\n| 1 | Larry | 85 |\n| 2 | Sam | 74 |\n| 3 | Mike | 76 |\n| 4 | Carol | 65 |\n+----+-------+-------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2322, "s": 2244, "text": "Following is the query to use a condition like “OR” in MySQL CASE expression:" }, { "code": null, "e": 2525, "s": 2322, "text": "mysql> select Id,Name,Score,\n -> case when Score > 75 then 'Better Score'\n -> when Score > 70 then 'Good Score'\n -> else 'Not Good Score'\n -> end as 'Performance'\n -> from caseOrConditionDemo;" }, { "code": null, "e": 2564, "s": 2525, "text": "This will produce the following output" }, { "code": null, "e": 2909, "s": 2564, "text": "+----+-------+-------+----------------+\n| Id | Name | Score | Performance |\n+----+-------+-------+----------------+\n| 1 | Larry | 85 | Better Score |\n| 2 | Sam | 74 | Good Score |\n| 3 | Mike | 76 | Better Score |\n| 4 | Carol | 65 | Not Good Score |\n+----+-------+-------+----------------+\n4 rows in set (0.04 sec)" } ]
agetty command in Linux with Examples - GeeksforGeeks
08 Oct, 2021 agetty is a Linux version of getty. getty short for “get tty” is a Unix program running on a host computer that manages physical or virtual terminals to allow multi-user access. Linux provides virtual terminal(tty) which is similar to the regular Linux terminal. agetty command opens a virtual terminal(tty port), prompts for a login name and invokes the /bin/login command. Syntax: agetty [options] port [baud_rate...] [term] Arguments: port: It is a pathname relative to the /dev directory. If a “-” is specified, then this command considers that its standard input is already connected to a tty port and that a connection to a remote user has already been established. baud_rate, ... : It is a comma-separated list of one or more baud rates. It should be specified in the descending order. term : It is the value to be used for the TERM environment variable. Options: -8, –8bits: Assume 8-bit tty. -a, –autologin: Automatic login for the specified user. -c, –noreset: Do not reset control mode. -E, –remote: Typically the login(1) command is given a remote hostname when called by something such as telnetd(8). This option allows agetty to pass what it is using for a hostname to login(1) for use in utmp(5). -h, –flow-control: Enables CTS/RTS handshaking (flow control). -i, –noissue: Do not display issue file. -J –noclear: Do not clear the screen before prompt. -m, –extract-baud: Use extract baud rate during connect. -n, –skip-login: Do not prompt for login. -p, –login-pause: Wait for the user to press any key before the login prompt. -R, –hangup: Call vhangup() to do a virtual hangup of the specified terminal. -s, –keep-baud: Try to keep previously used baud rate. -t, –timeout: It will terminate the login session if no user name can be read within timeout seconds. -U, –detect-case: This is used to turn on the support for detecting uppercase-only terminal. For more details about the options you can run the following command on the terminal: agetty --help Examples: 1) agetty -8 – linux -8 option for 8-bit tty. ‘-‘ for specifies that standard input is already connected to a tty port. baud rate is optional so not used here. ‘linux’ is value of TERM environment variable. 2) agetty -8 -t 5 – linux -t 5 is the login process timeout. 3) agetty -h -t 60 tty 9600 vtxxx tty refers to the device /dev/tty. 9600 is the bits per second bound rate. vtxxx is the TERM environment variable to indicate that a VTxxx terminal is connecting, in the previous example ‘linux’ is used as TERM env. -h activates CTS/RTS handshaking (flow control). -t 60 allows 60 seconds for someone to attempt to log in before the modem is hung up. 4) agetty -a -h -t 60 tty 9600 vt102 -a specifies autologin. 5) agetty –version To display the version information. 6) agetty -a -h -t 60 -U -s -m tty 9600 vt100 -U detects the uppercase terminal. -s try to use existing baud rate. -m use exact baud rate specified in the command. akshaysingh98088 sagar0719kumar linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples tee command in Linux with examples Tail command in Linux with examples touch command in Linux with Examples
[ { "code": null, "e": 24116, "s": 24088, "text": "\n08 Oct, 2021" }, { "code": null, "e": 24492, "s": 24116, "text": "agetty is a Linux version of getty. getty short for “get tty” is a Unix program running on a host computer that manages physical or virtual terminals to allow multi-user access. Linux provides virtual terminal(tty) which is similar to the regular Linux terminal. agetty command opens a virtual terminal(tty port), prompts for a login name and invokes the /bin/login command. " }, { "code": null, "e": 24502, "s": 24492, "text": "Syntax: " }, { "code": null, "e": 24546, "s": 24502, "text": "agetty [options] port [baud_rate...] [term]" }, { "code": null, "e": 24559, "s": 24546, "text": "Arguments: " }, { "code": null, "e": 24793, "s": 24559, "text": "port: It is a pathname relative to the /dev directory. If a “-” is specified, then this command considers that its standard input is already connected to a tty port and that a connection to a remote user has already been established." }, { "code": null, "e": 24914, "s": 24793, "text": "baud_rate, ... : It is a comma-separated list of one or more baud rates. It should be specified in the descending order." }, { "code": null, "e": 24983, "s": 24914, "text": "term : It is the value to be used for the TERM environment variable." }, { "code": null, "e": 24994, "s": 24983, "text": "Options: " }, { "code": null, "e": 25024, "s": 24994, "text": "-8, –8bits: Assume 8-bit tty." }, { "code": null, "e": 25080, "s": 25024, "text": "-a, –autologin: Automatic login for the specified user." }, { "code": null, "e": 25121, "s": 25080, "text": "-c, –noreset: Do not reset control mode." }, { "code": null, "e": 25335, "s": 25121, "text": "-E, –remote: Typically the login(1) command is given a remote hostname when called by something such as telnetd(8). This option allows agetty to pass what it is using for a hostname to login(1) for use in utmp(5)." }, { "code": null, "e": 25398, "s": 25335, "text": "-h, –flow-control: Enables CTS/RTS handshaking (flow control)." }, { "code": null, "e": 25439, "s": 25398, "text": "-i, –noissue: Do not display issue file." }, { "code": null, "e": 25491, "s": 25439, "text": "-J –noclear: Do not clear the screen before prompt." }, { "code": null, "e": 25548, "s": 25491, "text": "-m, –extract-baud: Use extract baud rate during connect." }, { "code": null, "e": 25590, "s": 25548, "text": "-n, –skip-login: Do not prompt for login." }, { "code": null, "e": 25668, "s": 25590, "text": "-p, –login-pause: Wait for the user to press any key before the login prompt." }, { "code": null, "e": 25746, "s": 25668, "text": "-R, –hangup: Call vhangup() to do a virtual hangup of the specified terminal." }, { "code": null, "e": 25801, "s": 25746, "text": "-s, –keep-baud: Try to keep previously used baud rate." }, { "code": null, "e": 25903, "s": 25801, "text": "-t, –timeout: It will terminate the login session if no user name can be read within timeout seconds." }, { "code": null, "e": 25996, "s": 25903, "text": "-U, –detect-case: This is used to turn on the support for detecting uppercase-only terminal." }, { "code": null, "e": 26083, "s": 25996, "text": "For more details about the options you can run the following command on the terminal: " }, { "code": null, "e": 26097, "s": 26083, "text": "agetty --help" }, { "code": null, "e": 26108, "s": 26097, "text": "Examples: " }, { "code": null, "e": 26130, "s": 26108, "text": "1) agetty -8 – linux " }, { "code": null, "e": 26155, "s": 26130, "text": "-8 option for 8-bit tty." }, { "code": null, "e": 26229, "s": 26155, "text": "‘-‘ for specifies that standard input is already connected to a tty port." }, { "code": null, "e": 26269, "s": 26229, "text": "baud rate is optional so not used here." }, { "code": null, "e": 26316, "s": 26269, "text": "‘linux’ is value of TERM environment variable." }, { "code": null, "e": 26343, "s": 26316, "text": "2) agetty -8 -t 5 – linux " }, { "code": null, "e": 26378, "s": 26343, "text": "-t 5 is the login process timeout." }, { "code": null, "e": 26413, "s": 26378, "text": "3) agetty -h -t 60 tty 9600 vtxxx " }, { "code": null, "e": 26448, "s": 26413, "text": "tty refers to the device /dev/tty." }, { "code": null, "e": 26488, "s": 26448, "text": "9600 is the bits per second bound rate." }, { "code": null, "e": 26629, "s": 26488, "text": "vtxxx is the TERM environment variable to indicate that a VTxxx terminal is connecting, in the previous example ‘linux’ is used as TERM env." }, { "code": null, "e": 26678, "s": 26629, "text": "-h activates CTS/RTS handshaking (flow control)." }, { "code": null, "e": 26764, "s": 26678, "text": "-t 60 allows 60 seconds for someone to attempt to log in before the modem is hung up." }, { "code": null, "e": 26802, "s": 26764, "text": "4) agetty -a -h -t 60 tty 9600 vt102 " }, { "code": null, "e": 26826, "s": 26802, "text": "-a specifies autologin." }, { "code": null, "e": 26882, "s": 26826, "text": "5) agetty –version To display the version information. " }, { "code": null, "e": 26929, "s": 26882, "text": "6) agetty -a -h -t 60 -U -s -m tty 9600 vt100 " }, { "code": null, "e": 26964, "s": 26929, "text": "-U detects the uppercase terminal." }, { "code": null, "e": 26998, "s": 26964, "text": "-s try to use existing baud rate." }, { "code": null, "e": 27047, "s": 26998, "text": "-m use exact baud rate specified in the command." }, { "code": null, "e": 27064, "s": 27047, "text": "akshaysingh98088" }, { "code": null, "e": 27079, "s": 27064, "text": "sagar0719kumar" }, { "code": null, "e": 27093, "s": 27079, "text": "linux-command" }, { "code": null, "e": 27100, "s": 27093, "text": "Picked" }, { "code": null, "e": 27111, "s": 27100, "text": "Linux-Unix" }, { "code": null, "e": 27209, "s": 27111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27247, "s": 27209, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27282, "s": 27247, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 27317, "s": 27282, "text": "tar command in Linux with examples" }, { "code": null, "e": 27353, "s": 27317, "text": "curl command in Linux with Examples" }, { "code": null, "e": 27391, "s": 27353, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27429, "s": 27391, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 27464, "s": 27429, "text": "Cat command in Linux with examples" }, { "code": null, "e": 27499, "s": 27464, "text": "tee command in Linux with examples" }, { "code": null, "e": 27535, "s": 27499, "text": "Tail command in Linux with examples" } ]
NativeScript - Data Binding
Data binding is one of the advanced concepts supported by NativeScript. NativeScript follows Angular data binding concept as closely as possible. Data binding enables the UI component to show/update the current value of the application data model without any programming effort. NativeScript supports two type of data binding. They are as follows − One-Way data binding − Update the UI whenever the model is changed. Two-Way data binding − Sync the UI and model. Whenever the model is updated, UI is updated automatically and also whenever the UI gets data from user (UI gets updated), the model will be updated. Let us learn both the concepts in this section. NativeScript provides a simple option to enable one-way data binding in a UI component. To enable one-way data binding, just add square bracket in the property of the target UI and then assign it the necessary model’s property. For example, to update the text content of a Label component, just change the UI code as below − <Label [text]='this.model.prop' /> Here, this.model.prop refers to the property of the model, this.model. Let us change our BlankNgApp to understand the one-way data binding. Add a new model, User (src/model/user.ts) as follows − export class User { name: string } Step 2 Open UI of our component, src/app/home/home.component.html and update the code as below − <ActionBar> <Label text="Home"></Label> </ActionBar> <GridLayout columns="*" rows="auto, auto, auto"> <Button text="Click here to greet" class="-primary" color='gray' (tap)='onButtonTap($event)' row='1' column='0'> </Button> <Label [text]='this.user.name' row='2' column='0' height="50px" textAlignment='center' style='font-size: 16px; font-weight: bold; margin: 0px 32px 0 25px;'> </Label> </GridLayout> Here, Label’s text is set to the user model’s property name. Label’s text is set to the user model’s property name. Button tap event is attached to onButtonTap method. Button tap event is attached to onButtonTap method. Open code of the home component, src/app/home/home.component.ts and update the code as below − import { Component, OnInit } from "@angular/core"; import { User } from "../../model/user" @Component({ selector: "Home", templateUrl: "./home.component.html" }) export class HomeComponent implements OnInit { public user: User; constructor() { // Use the component constructor to inject providers. this.user = new User(); this.user.name = "User1"; } ngOnInit(): void { // Init your component properties here. } onButtonTap(args: EventData) { this.user.name = 'User2'; } } Here, user model is imported user model is imported User object is created in component’s constructor User object is created in component’s constructor onButtonTap event is implemented. Implementation of onButtonTap updates the User object and set name of the property as User2 onButtonTap event is implemented. Implementation of onButtonTap updates the User object and set name of the property as User2 Compile and run the application and click the button to change the model and it will automatically change the Label text. The initial and final state of the application is as follows − One Way Data Binding Initial State is shown below − One Way Data Binding Final State is shown below − NativeScript also provides two-way data binding for advanced functionality. It binds the model data to UI and also binds the data updated in UI to model. To do two-way data binding, use ngModel property and then surround it with [] and () as below − <TextField [(ngModel)] = 'this.user.name'></TextField> Let us change the BlankNgApp application to better understand the two-way data binding. Import NativeScriptFormsModule into the HomeModule (src/app/home/home.module.ts) as specified below − import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; import { NativeScriptCommonModule } from "nativescript-angular/common"; import { HomeRoutingModule } from "./home-routing.module"; import { HomeComponent } from "./home.component"; import { NativeScriptFormsModule } from "nativescript-angular/forms"; @NgModule({ imports: [ NativeScriptCommonModule, HomeRoutingModule, NativeScriptFormsModule ], declarations: [ HomeComponent ], schemas: [ NO_ERRORS_SCHEMA ] }) export class HomeModule { } Here, NativeScriptFormsModule enables the two-way data binding. Otherwise, the two-way data binding will not work as expected. Change the UI of the home component as given below − <ActionBar> <Label text="Home"></Label></ActionBar> <GridLayout columns="*" rows="auto, auto"> <TextField hint="Username" row='0' column='0' color="gray" backgroundColor="lightyellow" height="75px" [(ngModel)]='this.user.name'> </TextField> <Label [text]='this.user.name' row='1' column='0' height="50px" textAlignment='center' style='font-size: 16px; font-weight: bold; margin: 0px 32px 0 25px;'> </Label> </GridLayout> Here, Label component’s text property is set with one-way data binding. If the model user is updated, then its text property will automatically get updated. TextField component sets the ngModel as this.user.name. If the model user is updated, then it’s text property will automatically get updated. At the same time, if user changes the TextField’s value, then the model gets updated as well. If the model gets updated, it will trigger Label’s text property changes as well. So, if user changes data, then it will show in Label’s text property. Run the application and try to change the value of text box. The initial and final state of the application will be similar as specified below − Two-way data binding – Initial state is given below − Two-way data binding – Final state is shown below − 22 Lectures 1 hours TELCOMA Global Print Add Notes Bookmark this page
[ { "code": null, "e": 2384, "s": 2105, "text": "Data binding is one of the advanced concepts supported by NativeScript. NativeScript follows Angular data binding concept as closely as possible. Data binding enables the UI component to show/update the current value of the application data model without any programming effort." }, { "code": null, "e": 2454, "s": 2384, "text": "NativeScript supports two type of data binding. They are as follows −" }, { "code": null, "e": 2522, "s": 2454, "text": "One-Way data binding − Update the UI whenever the model is changed." }, { "code": null, "e": 2718, "s": 2522, "text": "Two-Way data binding − Sync the UI and model. Whenever the model is updated, UI is updated automatically and also whenever the UI gets data from user (UI gets updated), the model will be updated." }, { "code": null, "e": 2766, "s": 2718, "text": "Let us learn both the concepts in this section." }, { "code": null, "e": 2994, "s": 2766, "text": "NativeScript provides a simple option to enable one-way data binding in a UI component. To enable one-way data binding, just add square bracket in the property of the target UI and then assign it the necessary model’s property." }, { "code": null, "e": 3091, "s": 2994, "text": "For example, to update the text content of a Label component, just change the UI code as below −" }, { "code": null, "e": 3127, "s": 3091, "text": "<Label [text]='this.model.prop' />\n" }, { "code": null, "e": 3133, "s": 3127, "text": "Here," }, { "code": null, "e": 3198, "s": 3133, "text": "this.model.prop refers to the property of the model, this.model." }, { "code": null, "e": 3267, "s": 3198, "text": "Let us change our BlankNgApp to understand the one-way data binding." }, { "code": null, "e": 3322, "s": 3267, "text": "Add a new model, User (src/model/user.ts) as follows −" }, { "code": null, "e": 3362, "s": 3322, "text": "export class User { \n name: string \n}" }, { "code": null, "e": 3369, "s": 3362, "text": "Step 2" }, { "code": null, "e": 3459, "s": 3369, "text": "Open UI of our component, src/app/home/home.component.html and update the code as below −" }, { "code": null, "e": 3905, "s": 3459, "text": "<ActionBar> \n <Label text=\"Home\"></Label> \n</ActionBar>\n<GridLayout columns=\"*\" rows=\"auto, auto, auto\"> \n <Button text=\"Click here to greet\" class=\"-primary\" color='gray' \n (tap)='onButtonTap($event)' row='1' column='0'>\n </Button> \n <Label [text]='this.user.name' row='2' column='0' \n height=\"50px\" textAlignment='center' style='font-size: 16px; \n font-weight: bold; margin: 0px 32px 0 25px;'>\n </Label> \n</GridLayout>" }, { "code": null, "e": 3911, "s": 3905, "text": "Here," }, { "code": null, "e": 3966, "s": 3911, "text": "Label’s text is set to the user model’s property name." }, { "code": null, "e": 4021, "s": 3966, "text": "Label’s text is set to the user model’s property name." }, { "code": null, "e": 4073, "s": 4021, "text": "Button tap event is attached to onButtonTap method." }, { "code": null, "e": 4125, "s": 4073, "text": "Button tap event is attached to onButtonTap method." }, { "code": null, "e": 4220, "s": 4125, "text": "Open code of the home component, src/app/home/home.component.ts and update the code as below −" }, { "code": null, "e": 4765, "s": 4220, "text": "import { Component, OnInit } from \"@angular/core\"; \nimport { User } from \"../../model/user\" \n@Component({\n selector: \"Home\", \n templateUrl: \"./home.component.html\" \n}) \nexport class HomeComponent implements OnInit { \n public user: User; \n constructor() {\n // Use the component constructor to inject providers. \n this.user = new User(); \n this.user.name = \"User1\"; \n }\n ngOnInit(): void { \n // Init your component properties here. \n } \n onButtonTap(args: EventData) { \n this.user.name = 'User2'; \n } \n}" }, { "code": null, "e": 4771, "s": 4765, "text": "Here," }, { "code": null, "e": 4794, "s": 4771, "text": "user model is imported" }, { "code": null, "e": 4817, "s": 4794, "text": "user model is imported" }, { "code": null, "e": 4867, "s": 4817, "text": "User object is created in component’s constructor" }, { "code": null, "e": 4917, "s": 4867, "text": "User object is created in component’s constructor" }, { "code": null, "e": 5043, "s": 4917, "text": "onButtonTap event is implemented. Implementation of onButtonTap updates the User object and set name of the property as User2" }, { "code": null, "e": 5169, "s": 5043, "text": "onButtonTap event is implemented. Implementation of onButtonTap updates the User object and set name of the property as User2" }, { "code": null, "e": 5291, "s": 5169, "text": "Compile and run the application and click the button to change the model and it will automatically change the Label text." }, { "code": null, "e": 5354, "s": 5291, "text": "The initial and final state of the application is as follows −" }, { "code": null, "e": 5406, "s": 5354, "text": "One Way Data Binding Initial State is shown below −" }, { "code": null, "e": 5456, "s": 5406, "text": "One Way Data Binding Final State is shown below −" }, { "code": null, "e": 5610, "s": 5456, "text": "NativeScript also provides two-way data binding for advanced functionality. It binds the model data to UI and also binds the data updated in UI to model." }, { "code": null, "e": 5706, "s": 5610, "text": "To do two-way data binding, use ngModel property and then surround it with [] and () as below −" }, { "code": null, "e": 5762, "s": 5706, "text": "<TextField [(ngModel)] = 'this.user.name'></TextField>\n" }, { "code": null, "e": 5850, "s": 5762, "text": "Let us change the BlankNgApp application to better understand the two-way data binding." }, { "code": null, "e": 5952, "s": 5850, "text": "Import NativeScriptFormsModule into the HomeModule (src/app/home/home.module.ts) as specified below −" }, { "code": null, "e": 6516, "s": 5952, "text": "import { NgModule, NO_ERRORS_SCHEMA } from \"@angular/core\"; \nimport { NativeScriptCommonModule } from \"nativescript-angular/common\"; \nimport { HomeRoutingModule } from \"./home-routing.module\"; \nimport { HomeComponent } from \"./home.component\"; \nimport { NativeScriptFormsModule } from \"nativescript-angular/forms\";\n@NgModule({ \n imports: [ \n NativeScriptCommonModule, \n HomeRoutingModule, \n NativeScriptFormsModule \n ], \n declarations: [ \n HomeComponent \n ], \n schemas: [ \n NO_ERRORS_SCHEMA \n ]\n}) \nexport class HomeModule { }" }, { "code": null, "e": 6522, "s": 6516, "text": "Here," }, { "code": null, "e": 6643, "s": 6522, "text": "NativeScriptFormsModule enables the two-way data binding. Otherwise, the two-way data binding will not work as expected." }, { "code": null, "e": 6696, "s": 6643, "text": "Change the UI of the home component as given below −" }, { "code": null, "e": 7154, "s": 6696, "text": "<ActionBar> <Label text=\"Home\"></Label></ActionBar> \n<GridLayout columns=\"*\" rows=\"auto, auto\"> \n <TextField hint=\"Username\" row='0' column='0' color=\"gray\" \n backgroundColor=\"lightyellow\" height=\"75px\" [(ngModel)]='this.user.name'>\n </TextField> \n <Label [text]='this.user.name' row='1' column='0' height=\"50px\" \n textAlignment='center' style='font-size: 16px; font-weight: bold; \n margin: 0px 32px 0 25px;'>\n </Label> \n</GridLayout>" }, { "code": null, "e": 7160, "s": 7154, "text": "Here," }, { "code": null, "e": 7311, "s": 7160, "text": "Label component’s text property is set with one-way data binding. If the model user is updated, then its text property will automatically get updated." }, { "code": null, "e": 7699, "s": 7311, "text": "TextField component sets the ngModel as this.user.name. If the model user is updated, then it’s text property will automatically get updated. At the same time, if user changes the TextField’s value, then the model gets updated as well. If the model gets updated, it will trigger Label’s text property changes as well. So, if user changes data, then it will show in Label’s text property." }, { "code": null, "e": 7760, "s": 7699, "text": "Run the application and try to change the value of text box." }, { "code": null, "e": 7844, "s": 7760, "text": "The initial and final state of the application will be similar as specified below −" }, { "code": null, "e": 7898, "s": 7844, "text": "Two-way data binding – Initial state is given below −" }, { "code": null, "e": 7950, "s": 7898, "text": "Two-way data binding – Final state is shown below −" }, { "code": null, "e": 7983, "s": 7950, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 7999, "s": 7983, "text": " TELCOMA Global" }, { "code": null, "e": 8006, "s": 7999, "text": " Print" }, { "code": null, "e": 8017, "s": 8006, "text": " Add Notes" } ]